Skip to content
Problem 670 · LeetCode 670(opens in a new tab)

Maximum Swap

MediumGreedy algorithms

You get a non-negative integer num. You may pick two of its digits and trade their places, or leave the number alone. You get one trade at most.

Return the largest number you can end up with.

Example 1

Input:  num = 1993
Output: 9913
Why:    move the last 9 to the front; the 1 goes where it was
2 more examples and the constraints

Example 2

Input:  num = 8761
Output: 8761
Why:    the digits already fall from left to right

Example 3

Input:  num = 3829
Output: 9823
Why:    the 9 at the end trades places with the leading 3

Constraints

  • 0 ≤ num ≤ 100,000,000
  • So num has at most 9 digits

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try every swapO(d²)
  2. Rightmost bigger digitO(d)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a 9-digit numberVerdict
Try every swapO(d²)
Simple; rebuilds the number 36 times
Rightmost bigger digitO(d)
Best; one pass and one swap

d = number of digits in num (at most 9).

Edge cases to test

  • Zero or one digit. 0 and 7 have nothing to swap, so they come back as they are.
  • Already the largest. 8761 or 99999999: no digit has a bigger one after it, so return num.
  • Repeated big digit. 1993 must use the last 9, giving 9913, not 9193.
  • Zeros in the number. 100000000 stays put: moving a 0 forward only makes it smaller. 1001 becomes 1100.
  • Improve past the front. 98368: the 9 and 8 are fine, the 3 trades with the last 8 to give 98863.

Common mistakes

  • Swapping with the first copy of the biggest digit instead of the last one.
  • Swapping the first digit with the overall maximum even when the first digit already is that maximum.
  • Forgetting the no-swap case and always making a trade.

How to talk through it

  1. 1Clarify. Is one swap allowed or required? Can num be 0? It fits in 9 digits?
  2. 2Give the brute force. Try every pair of positions and keep the largest number: O(d²).
  3. 3Find the greedy rule. The leftmost digit that can grow is the one to change; take the biggest digit after it.
  4. 4Handle ties. Use the rightmost copy of that digit, found from a last-index table.
  5. 5Test out loud. Run 1993, 8761 and 0 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?