670. Maximum Swap
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
Method Explanation
To find the maximum number after at most one swap, we should aim to place the largest possible digit at the most significant position (leftmost). This suggests a greedy approach.
Solution
Maximum Swap in Python
class Solution:
def maximumSwap(self, num: int) -> int:
# Convert the number to a list of characters (strings).
s = list(str(num))
n = len(s)
# last_indices[d] stores the last index of digit d.
last_indices = {int(digit): i for i, digit in enumerate(s)}
# Iterate through the digits from left to right.
for i in range(n):
current_digit = int(s[i])
# Search for the largest digit `d` (from 9 down to current_digit + 1)
# that could be to the right of the current position.
for d in range(9, current_digit, -1):
# Check if this larger digit `d` exists and its last occurrence is to the right.
if d in last_indices and last_indices[d] > i:
# If found, swap the current digit with the last occurrence
# of that larger digit.
j = last_indices[d]
s[i], s[j] = s[j], s[i]
# After one swap, we are done. Join and convert back to int.
return int("".join(s))
# If no swap was made, return the original number.
return num
Maximum Swap in Java
class Solution {
public int maximumSwap(int num) {
// Convert the number to a character array.
char[] digits = String.valueOf(num).toCharArray();
int n = digits.length;
// lastIndices[d] will store the last index of digit d.
int[] lastIndices = new int[10];
for (int i = 0; i < n; i++) {
lastIndices[digits[i] - '0'] = i;
}
// Iterate through the digits from left to right.
for (int i = 0; i < n; i++) {
int currentDigit = digits[i] - '0';
// Search for the largest digit `d` (from 9 down to currentDigit+1)
// that appears after the current position.
for (int d = 9; d > currentDigit; d--) {
if (lastIndices[d] > i) {
// If we find such a digit, we swap the current digit
// with the last occurrence of that larger digit.
char temp = digits[i];
digits[i] = digits[lastIndices[d]];
digits[lastIndices[d]] = temp;
// After one swap, we have the maximum possible number.
// Convert the char array back to an integer and return.
return Integer.parseInt(new String(digits));
}
}
}
// If no swap was performed, the number is already the largest possible.
return num;
}
}
Maximum Swap in C++
class Solution {
public:
int maximumSwap(int num) {
// Convert the number to a string to easily manipulate its digits.
std::string s = std::to_string(num);
int n = s.length();
// last_indices[d] stores the last index of digit d.
std::vector<int> last_indices(10, 0);
for (int i = 0; i < n; ++i) {
last_indices[s[i] - '0'] = i;
}
// Iterate through the digits from left to right.
for (int i = 0; i < n; ++i) {
// For the current digit s[i], find the largest possible digit `d`
// that can be swapped with it to make the number larger.
// We search from 9 down to s[i] - '0' + 1.
for (int d = 9; d > s[i] - '0'; --d) {
// Check if this larger digit `d` appears later in the number.
if (last_indices[d] > i) {
// If so, we've found our swap.
// Swap s[i] with the last occurrence of digit d.
std::swap(s[i], s[last_indices[d]]);
// After one swap, we are done. Convert the string back to int and return.
return std::stoi(s);
}
}
}
// If no swap was made, the number is already in its largest form.
return num;
}
};
Maximum Swap in TypeScript
function maximumSwap(num: number): number {
// Convert the number to a string, then to an array of characters.
const s: string[] = String(num).split('');
const n: number = s.length;
// lastIndices[d] will store the last index of digit d.
const lastIndices: number[] = new Array(10).fill(-1);
for (let i = 0; i < n; i++) {
lastIndices[parseInt(s[i])] = i;
}
// Iterate through the digits from left to right.
for (let i = 0; i < n; i++) {
const currentDigit = parseInt(s[i]);
// Search for the largest digit `d` (from 9 down to currentDigit + 1)
// that appears after the current position.
for (let d = 9; d > currentDigit; d--) {
if (lastIndices[d] > i) {
// If we find such a digit, swap the current digit
// with the last occurrence of that larger digit.
[s[i], s[lastIndices[d]]] = [s[lastIndices[d]], s[i]];
// After one swap, we have the maximum possible number.
// Join the array back into a string and parse it as a number.
return parseInt(s.join(''));
}
}
}
// If no swap was performed, the number is already the largest possible.
return num;
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.