Maximum Swap
Table of Contents + −
You get one swap. Just one. Move two digits and make the number as big as you can. It sounds easy. But the trick is knowing which two digits to swap. The interviewer wants to see if you can find the best swap fast, not just try them all.
🎯 The Problem
You get a number and you want to make it as large as you can. Here are the rules.
- You may swap two digits at most once.
- You may also choose to swap nothing.
- Return the largest number you can make.
Say the number is 2736. The best move is to swap the 2 and the 7. That gives 7236. No other single swap makes it bigger. The biggest digit you can pull forward is the key idea. We call it the best digit to bring to the front.
Input: num = 2736Output: 7236
Explanation: swap the 2 and the 7 to get 7236, the largest possible.If the number is already the biggest, like 9973, you swap nothing and return it as is.
Here are the digits laid out. We look for a bigger digit later that can move up to an early spot.
🐢 Approach 1: Try Every Swap (Brute Force)
The idea in one line: try every pair of digit positions and keep the biggest result.
The idea:
- Pick a first position.
- Pick a second position.
- Swap them and read the new number.
- Keep the biggest number you ever see.
How it works:
- Loop over every first position.
- For each, loop over every second position.
- Swap, compare with the best so far, then undo.
- After all pairs, return the biggest.
Why it is weak:
- For a number with
ddigits there are aboutdtimesdpairs. - That is O(d²) work.
- Fine for short numbers, but it does far more work than needed.
Here is the brute-force code for that idea:
def maximum_swap(num): digits = list(str(num)) best = num
for i in range(len(digits)): for j in range(i + 1, len(digits)): copy = digits[:] copy[i], copy[j] = copy[j], copy[i] best = max(best, int("".join(copy)))
return best
print(maximum_swap(2736))⚡ Approach 2: Last Occurrence Greedy (Best)
The idea in one line: pull the largest later digit into the earliest spot, and swap its rightmost copy.
The idea:
- A bigger digit in an early spot always makes the number larger.
- So scan from the left and look for a bigger digit sitting to the right.
- Bring that bigger digit forward with one swap.
The catch about duplicates:
- The same big digit can appear more than once on the right.
- Swap its last occurrence, the rightmost copy.
- That keeps the bigger value in the important early spot and pushes the smaller digit far right.
How it works:
- Record the last position of each digit
0to9. - Scan the digits from the left.
- At each spot, check digits
9down to one above the current digit. - The first bigger digit whose last position is to the right wins. Swap and stop.
Why it is fast:
- One setup pass, then one left-to-right scan.
- Each digit is looked at once. So it runs in O(d) time.
Here is the dry run on 2736. We find the best digit to pull forward.
Steps to Solve
- Turn the number into a list of digits.
- Record the last position where each digit
0to9appears. - Scan the digits from left to right.
- At each position, check digits
9down to current plus one. If a bigger digit appears later, swap with its last position and stop. - Turn the digit list back into a number and return it.
This Python version uses a list of digit characters and a dictionary for each digit’s last position.
def maximum_swap(num): digits = list(str(num)) # turn number into digits last = {int(d): i for i, d in enumerate(digits)} # last spot
for i, d in enumerate(digits): for big in range(9, int(d), -1): # try bigger digits first if last.get(big, -1) > i: # bigger digit sits later j = last[big] digits[i], digits[j] = digits[j], digits[i] # one swap return int("".join(digits)) return num # already the largest
print(maximum_swap(2736))The output of the above code will be:
7236Let us walk through the Python version line by line. The line digits = list(str(num)) turns 2736 into the list ['2', '7', '3', '6']. We work on digits, not the raw number, because swapping single digits is easy on a list.
The line last = {int(d): i for i, d in enumerate(digits)} records the last position of each digit. Because we walk left to right and overwrite, the final stored index for any digit is its rightmost spot. So last[7] is 1 and last[6] is 3.
The outer loop for i, d in enumerate(digits) scans from the left. The inner loop for big in range(9, int(d), -1) tries the biggest digits first. We start at 9 and go down to just above the current digit. We want the largest possible improvement, so checking from 9 down finds it first.
The line if last.get(big, -1) > i is the heart of it. It asks if a bigger digit sits to the right of the current spot. If yes, swapping pulls that bigger digit forward. We do the swap with digits[i], digits[j] = digits[j], digits[i] and return at once. We return immediately because we only get one swap. If no swap ever helps, the number was already the largest, so we return num unchanged.
⏱️ Time and Space Complexity
The brute force tries every pair of positions, so it is O(d²) for d digits. The greedy scan records last positions once, then walks the digits one time. The inner check over 9 down is a constant, so the whole thing is O(d). We store the digits and a tiny table of ten slots, so the space is O(d).
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Brute force (try every swap) | O(d²) | O(d) |
| Last occurrence greedy | O(d) | O(d) |
Tip
The insight to say out loud is that you want the biggest digit as far left as possible, and you swap its rightmost copy. Naming the last occurrence rule shows the interviewer you see why the greedy choice is safe.
🧩 Key Takeaways
- ✅ You get only one swap, so spend it on the biggest gain.
- ✅ Pull the largest later digit into the earliest spot you can.
- ✅ Always swap the last occurrence of that big digit, not the first.
- ✅ Record each digit’s last position once, then scan left to right.
- ✅ This turns an O(d²) search into a single O(d) pass.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
How many swaps are you allowed in the Maximum Swap problem?
Why: You may swap two digits at most once, or swap nothing if the number is already the largest.
- 2
To make the number larger, which digit do we want to move forward?
Why: Bringing the largest later digit into an early spot gives the biggest increase.
- 3
Why do we swap the last occurrence of the big digit?
Why: Using the rightmost copy keeps the bigger digit in the important early position and moves the smaller one far right.
- 4
What is the time complexity of the greedy last-occurrence approach for d digits?
Why: Recording last positions and one left-to-right scan with a constant inner check is O(d).