Maximum Swap

Swap at most two digits once to make a number as large as possible — last-occurrence lookup.

Medium
Time O(n) Space O(1)
LeetCode
3 min read
greedy string

Problem#

Swap any two digits at most once to maximize the resulting integer.

Examples#

  • 27367236
  • 99739973

Constraints#

  • 0 <= num <= 10^8.

Approach#

Record last[d] = last index of each digit. Walk left-to-right; for each position, look for any larger digit d (9 down to current+1) whose last occurrence is to the right — swap and return.

Solution#

Maximum Swap
class Solution {
public:
int maximumSwap(int num) {
string s = to_string(num);
int last[10] = {0};
for (int i = 0; i < (int)s.size(); ++i) last[s[i] - '0'] = i;
for (int i = 0; i < (int)s.size(); ++i) {
for (int d = 9; d > s[i] - '0'; --d) {
if (last[d] > i) {
swap(s[i], s[last[d]]);
return stoi(s);
}
}
}
return num;
}
};

Editorial#

For each position left-to-right, the greedy ideal is to swap in the largest digit available later in the string. The “later” requirement is what makes this a swap (not a re-arrangement). Walking digits 9 down to current+1 finds the largest improvement at the leftmost position — the highest-impact swap.

Complexity#

  • Time: O(n × 10) = O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.