Solution: Maximum Swap
Let’s solve the Maximum Swap problem using the Greedy Techniques pattern.
We'll cover the following
Statement
Given an integer num
, return the maximum number that can be formed by swapping at least two digits once.
Constraints:
num
Solution
The problem involves maximizing a number by swapping two digits at most once. The key idea is to find a smaller digit on the left and a larger digit on the right that can be swapped to create the largest possible number. By scanning the digits from right to left, we can identify the optimal pair for swapping in a single pass, ensuring efficiency. This approach uses a greedy algorithm, as it makes the best possible decision at each step to maximize the number.
Here’s the step-by-step implementation of the solution:
Convert the input number to a string and then to a list of digits. This allows easy manipulation of individual digits.
Use the
max_digit_index
to track the index of the maximum digit encountered so far (starting from the right).Use
index_1
andindex_2
to track the indices of the two digits to be swapped. Initially, set these toto indicate no valid swap has been found. Traverse the list of digits from the least significant (rightmost) to the most significant (leftmost). For each digit:
If the current digit is greater than the digit on
max_digit_index
, update themax_digit_index
to the current index.Otherwise, if it’s smaller, update
index_1
andindex_2
to potentially mark these digits to be swapped.
If both
index_1
andindex_2
have been updated (indicating a valid swap is found), swap the digits at these indices.After the swap, convert the list of digits back to a string and then to an integer, which is returned as the result.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.