Maximum Swap (LeetCode 670): Solution and Explanation

Medium
Math
Greedy

You get a non-negative integer and may swap two of its digits once. Return the largest number you can make.

Intuition

Place value decides everything. Raising the leftmost digit by even 1 beats any change further right, so the swap should improve the first position that can be improved.

A position can only be improved if some larger digit sits to its right. Swapping with a digit on its left would push a smaller digit forward, which never helps.

Among the larger digits to the right, pick the biggest one. If that digit appears several times, use its rightmost copy: the smaller digit you push back then lands in the least valuable spot. For 1993, swapping the 1 with the last 9 gives 9913, while the first 9 would give 9193.

Approach: Greedy scan with a last-occurrence table

  1. Turn num into a list of digit characters.
  2. Record last[d], the rightmost index of each digit d.
  3. Scan positions i from left to right. For each, try k from 9 down to digits[i] + 1.
  4. The first k whose last[k] is greater than i is the best swap: swap digits[i] with digits[last[k]] and return the new number.
  5. If the scan finishes with no swap, the digits are already non-increasing, so return num.

Step-by-step example

num = 2736
  1. Digits are 2, 7, 3, 6. The last positions are: 2 at 0, 7 at 1, 3 at 2, 6 at 3.
  2. Position 0 holds 2. Probe 9 and 8: they do not appear. Probe 7: its last position is 1, which is to the right of 0.
  3. Swap positions 0 and 1. The digits become 7, 2, 3, 6.
  4. Return 7236.

Code: Python, Java, C++

1class Solution:
2    def maximumSwap(self, num: int) -> int:
3        digits = list(str(num))
4        last = {int(d): i for i, d in enumerate(digits)}
5        for i, d in enumerate(digits):
6            for k in range(9, int(d), -1):
7                if last.get(k, -1) > i:
8                    digits[i], digits[last[k]] = digits[last[k]], digits[i]
9                    return int("".join(digits))
10        return num
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(d)

Building the table is one pass over the d digits, and the scan does at most 9 probes per digit.

Space

O(d)

The digit list has d entries; the table has a fixed 10 slots.

Other approaches

Try every pair (time O(d^3), space O(d))

Swap every pair of positions, convert to a number, and keep the maximum. With at most 9 digits this is only 36 swaps, so it is fast in practice, but it does not show the greedy reasoning.

Right-to-left max tracking (time O(d), space O(d))

Walk from the right, remembering the index of the largest digit seen so far. Whenever a digit is smaller than that max, record the pair. The last pair recorded (the leftmost) is the swap to make.

Common mistakes

  • Swapping with the first copy of the largest digit instead of the last one. For 1993 that gives 9193 instead of 9913.
  • Comparing with >= instead of > when picking the digit. Swapping equal digits wastes the only swap.
  • Swapping the maximum digit of the whole number into position 0 without checking that position 0 can actually be improved. For 9973 the 9 is already in front.
  • Forgetting the no-swap case and returning a swapped number for inputs like 0 or 4321.

Frequently asked questions

Why use the rightmost copy of the bigger digit?

Both copies give the same digit at position i. The difference is where the smaller digit goes. Putting it at the rightmost copy keeps the other large copies in their more valuable positions.

Why scan from the left?

The leftmost position has the highest place value, so the first position that can be improved is where any improvement matters most. Later positions cannot make up for it.

What if the number has one digit?

There is nothing to swap with, so the scan makes no change and the original number is returned.