Maximum Swap
Medium
Topics
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
Input: n = 2736 Output: 7236 Explanation: Swap 2 and 7.
Example 2
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
- Turn the number into a digit list and record, for each digit value 0–9, the last index at which it appears.
- Walk the positions left to right. At position
i, look for the largest digit valuek > d[i]whose last occurrence lies afteri. - On the first hit, swap and return immediately — this is the one swap.
- 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] -> 98863Complexity
- Time — O(d): where
dis the digit count. Each position probes at most ten candidate digit values, a constant, so the work is linear in the digits. Atn <= 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
1993that swaps the leading 1 with the 9 at index 1 and returns9193; the correct answer is9913, 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 nimport java.util.*;
class Solution {
public int maximumSwap(int n) {
char[] d = Integer.toString(n).toCharArray();
int[] last = new int[10];
for (int i = 0; i < d.length; i++) last[d[i] - '0'] = i;
for (int i = 0; i < d.length; i++) {
for (int k = 9; k > d[i] - '0'; k--) {
if (last[k] > i) {
char t = d[i];
d[i] = d[last[k]];
d[last[k]] = t;
return Integer.parseInt(new String(d));
}
}
}
return n;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int maximumSwap(int n) {
string d = to_string(n);
int last[10] = {0};
for (int i = 0; i < (int)d.size(); i++) last[d[i] - '0'] = i;
for (int i = 0; i < (int)d.size(); i++) {
for (int k = 9; k > d[i] - '0'; k--) {
if (last[k] > i) {
swap(d[i], d[last[k]]);
return stoi(d);
}
}
}
return n;
}
};/**
* @param {number} n
* @return {number}
*/ var maximumSwap = function(n) {
const d = String(n).split('');
const last = {};
for (let i = 0; i < d.length; i++) last[d[i]] = i;
for (let i = 0; i < d.length; i++) {
for (let k = 9; k > +d[i]; k--) {
if (last[k] !== undefined && last[k] > i) {
const t = d[i];
d[i] = d[last[k]];
d[last[k]] = t;
return parseInt(d.join(''), 10);
}
}
}
return n;
};