LeetCode 670: Maximum Swap Solution
Master LeetCode problem 670 (Maximum Swap), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation:
To solve this problem, we can iterate through the digits of the input number from left to right. For each digit, we will find the maximum digit that occurs to the right of it. If the maximum digit is greater than the current digit, we will swap them and return the result.
We can use a map to store the last occurrence index of each digit in the number. Then, while iterating through the digits, we check if there is a larger digit occurring to the right. If so, we swap the current digit with the maximum digit found and return the result.
- Time complexity: O(n), where n is the number of digits in the input number.
- Space complexity: O(1) since we are using a fixed-size map to store the last occurrence index of each digit.
: :
Solution Code
class Solution {
public int maximumSwap(int num) {
char[] digits = Integer.toString(num).toCharArray();
int[] lastIndex = new int[10];
for (int i = 0; i < digits.length; i++) {
lastIndex[digits[i] - '0'] = i;
}
for (int i = 0; i < digits.length; i++) {
for (int d = 9; d > digits[i] - '0'; d--) {
if (lastIndex[d] > i) {
char temp = digits[i];
digits[i] = digits[lastIndex[d]];
digits[lastIndex[d]] = temp;
return Integer.parseInt(new String(digits));
}
}
}
return num;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 670 (Maximum Swap)?
This page provides optimized solutions for LeetCode problem 670 (Maximum Swap) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 670 (Maximum Swap)?
The time complexity for LeetCode 670 (Maximum Swap) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 670 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 670 in Java, C++, or Python.