Maximum Swap

Make a number as large as possible by swapping two of its digits at most once.

Given a non-negative integer num, at most 108, you may swap two of its digits once, or not at all. Return the largest number you can get.

Example 1
Input: num = 2736
Output: 7236
Explanation: swap 2 and 7.
Example 2
Input: num = 9973
Output: 9973
Explanation: no swap helps.
Example 3
Input: num = 1993
Output: 9913
Explanation: swap the 1 with the last 9, not the first.
Solution

The Idea

Write 2736 on four cards, one digit per card. You may trade the places of two cards once. Which trade gives the biggest number? The leftmost card counts most: the 2 is worth 2000, while the 7 next to it is worth only 700. Putting the 7 in front gives 7236, and no other trade beats it.

So the swap should raise the leftmost digit that can be raised. In 9973 no digit has a bigger one after it, because the digits already go down from left to right, and that is why no swap helps. In 2736 the very first digit, 2, can grow, so that is where the swap goes.

Example 3, 1993, raises one more question. The 1 in front can grow, and the biggest digit after it is 9. But there are two 9s, at position 1 and position 2, counting positions from 0 on the left. Which one should move to the front?

Look at the picture below. Swapping the 1 with the first 9 gives 9193, and swapping it with the last 9 gives 9913. Both put a 9 in front, so the difference is where the 1 lands. With the last 9, the 1 goes as far right as it can, where a small digit costs the least.

The digits of 1993 at positions 0 to 3. Swapping the 1 at position 0 with the last 9, at position 2, gives 9913; swapping it with the first 9 gives 9193. A table keeps the last position of each digit: 1 at 0, 9 at 2, 3 at 3.

The table on the right, headed "last position of each digit", is how we find that 9 quickly. Read 1993 from left to right and write down each digit's position as you meet it. The 9 is seen at position 1, then at position 2, and the later position 2 is the one kept.

So the whole answer is one choice: the leftmost digit that has a bigger digit somewhere after it, swapped with the last copy of the biggest such digit. Settling the most important digit first and never coming back to it is called a greedy choice, and here it is safe, because nothing to the right can make up for a smaller digit further left.

Solution Approach

Turning that idea into code means settling three things: which position to change, which digit to bring there, and how to find that digit's last position fast, after a look at the simple way of trying every swap.

Trying every swap

Why not try every pair of positions, build each new number and keep the largest? For 1993 there are only six pairs, so this is a fine first program. But every pair builds a whole new number, so the work grows with the cube of the digit count. It also never says why a swap wins, while the rule from the idea goes straight to the right swap.

Which position to change

Where does the swap go? Walk the digits from the left and stop at the first position that has a bigger digit somewhere after it. Every digit before that position is already at least as big as all the digits after it, so no swap can raise it. If the walk finds no such position, as in 9973, the number is returned as it is.

Which digit to bring in

Which bigger digit should come in? The biggest one that appears later, because it raises the changed position the most. Digits only go from 0 to 9, so we can simply try 9, then 8, and so on, down to one more than the current digit. The first value that appears after the position wins.

Finding the last copy quickly

How do we know whether a value appears later, and where its last copy is? Before the walk, one pass over the digits fills an array of ten cells, one per digit value, with each value's last position. A value appears after the position being changed exactly when its last position is greater, and that same cell says which copy to swap with.

Java Solution

The method maximumSwap works in these steps:

  1. First, turn the number into an array of characters with Integer.toString(num).toCharArray() and call it digits, so each digit can be read and swapped by its position.
  2. Create last, an int array of 10 cells, one per digit value. A loop over digits from left to right stores each position in the cell of its digit, so a later copy overwrites an earlier one. For 1993, last[9] ends up as 2.
  3. A second loop moves i over the positions from the left. Inside it, an inner loop counts d down from 9 to one more than the digit at i, trying the bigger values, largest first.
  4. When last[d] > i, the value d appears after position i. Swap digits[i] with digits[last[d]], turn the characters back into a number with Integer.parseInt and return it.
  5. If the loops finish without a swap, no digit has a bigger one after it, so return num unchanged.

The num limit of 108 keeps the result to at most nine digits, which always fits in an int, so Integer.parseInt is safe.

The main method runs the three examples, 0, a single digit, a number whose first two digits are already the best, and 1001, whose front digit has only an equal digit after it.

Java
public class MaximumSwap {

    public static int maximumSwap(int num) {
        char[] digits = Integer.toString(num).toCharArray();
        int[] last = new int[10];                 // last[d]: last position of digit d
        for (int i = 0; i < digits.length; i++) {
            last[digits[i] - '0'] = i;
        }
        for (int i = 0; i < digits.length; i++) {
            for (int d = 9; d > digits[i] - '0'; d--) {   // bigger digits, largest first
                if (last[d] > i) {                        // does d appear after position i?
                    char t = digits[i];
                    digits[i] = digits[last[d]];
                    digits[last[d]] = t;
                    return Integer.parseInt(new String(digits));
                }
            }
        }
        return num;                               // no swap makes it bigger
    }

    public static void main(String[] args) {
        int[] tests = {2736, 9973, 1993, 0, 7, 98368, 1001};
        for (int num : tests) {
            System.out.println(num + " -> " + maximumSwap(num));
        }
    }
}

Running it prints:

Output
2736 -> 7236
9973 -> 9973
1993 -> 9913
0 -> 0
7 -> 7
98368 -> 98863
1001 -> 1100

Look at 1993 -> 9913: the 1 traded places with the 9 at position 2, the one stored in last[9], and not with the 9 at position 1. For 0 and 7 there is no second digit to swap with, so both come back as they were.

The line 98368 -> 98863 shows the walk skipping positions. Nothing after the 9 is bigger, and nothing after the 8 is bigger either, so the swap happens at position 2. There the 3 trades with the 8 at the end.

The last line, 1001 -> 1100, also skips a position. The front 1 has another 1 after it, but an equal digit is not bigger, so it stays. The 0 at position 1 then takes the last 1, and the result is 1100.

Complexity

The method reads the digits once to fill last, then walks them once more with a short check per position.

  • Time: O(n), because the first loop visits each of the n digits once, and the walk tries at most nine bigger values at each position before it swaps or moves on.
  • Space: O(n), because digits and the string built from it hold all n digits, while last always has ten cells, whatever the number.

Making the leftmost digits as good as possible is also the rule in Remove K Digits.