Maximum Swap

Medium

Topics
MathGreedy

Given a non-negative integer n, you may swap two digits at most once to get the maximum valued number. Return that maximum value.

Example 1

20713263
At most one swap is allowed, so it must buy the most at the leftmost position it can. Swapping the shaded digits gives 7236. Recording each digit’s last position first makes this one left-to-right pass.
Cells are the decimal digits, with their positions below.
Input:  n = 2736
Output: 7236
Explanation: Swap 2 and 7.

Example 2

90917233
The digits are already in non-increasing order, so no swap can improve the number and the answer is 9973.
Input:  n = 9973
Output: 9973

Constraints

  • 0 <= n <= 10^8
Editorial — intuition, approach, complexity and pitfalls

Intuition

Exactly one swap is allowed, so the gain comes from fixing the most significant digit possible. Scan from the left and stop at the first position that some later digit can improve; swapping anywhere further right is worth strictly less.

The second decision is subtler. Among the later digits that beat the current one, take the largest value, and if that value occurs more than once take its rightmost occurrence. Pushing the displaced small digit as far right as possible costs the least.

Approach

  1. Turn the number into a digit list and record, for each digit value 0–9, the last index at which it appears.
  2. Walk the positions left to right. At position i, look for the largest digit value k > d[i] whose last occurrence lies after i.
  3. On the first hit, swap and return immediately — this is the one swap.
  4. If the walk finishes with no hit, the number is already maximal; return it unchanged.

Dry Run

n = 98368        digits  [9, 8, 3, 6, 8]
last index of each digit   {3: 2, 6: 3, 8: 4, 9: 0}

  i=0  digit 9   largest later digit above 9 : none, move on
  i=1  digit 8   largest later digit above 8 : none, move on
  i=2  digit 3   largest later digit above 3 : 8, last seen at index 4  -> swap

after swap  [9, 8, 8, 6, 3]   ->  98863

Complexity

  • Time — O(d): where d is the digit count. Each position probes at most ten candidate digit values, a constant, so the work is linear in the digits. At n <= 10⁸ that is at most nine positions.
  • Space — O(d) for the digit list, plus a ten-entry table. Both are constant at the stated bound, which is why calling this O(1) space is defensible — but say why it is bounded rather than asserting O(1).

Common Pitfalls

  • Recording the first occurrence of each digit instead of the last. On 1993 that swaps the leading 1 with the 9 at index 1 and returns 9193; the correct answer is 9913, which comes from using the 9 at index 2.
  • Swapping the global maximum digit into position 0 unconditionally. If position 0 already holds the largest digit you must move on, not swap it with itself or with a later equal digit.
  • Forgetting to return the input untouched when no improving swap exists, as on 9973.
  • Sorting the digits in descending order. That is the answer to a different problem — any number of swaps.
  • Doing the comparison on characters without converting to integers. '9' > '8' happens to agree for single digits, but the ten-entry last-index table is keyed by value and mixing the two representations is where this goes wrong.

Full Solution — all languages

class Solution:
    def maximumSwap(self, n):
        d = list(str(n))
        last = {int(c): i for i, c in enumerate(d)}
        for i, c in enumerate(d):
            for k in range(9, int(c), -1):
                if last.get(k, -1) > i:
                    d[i], d[last[k]] = d[last[k]], d[i]
                    return int(''.join(d))
        return n
Asked at TikTok
SensAI
Beta
Tap the mic to stop voice mode