LeetCode 2231: Largest Number After Digit Swaps by Parity Solution
Master LeetCode problem 2231 (Largest Number After Digit Swaps by Parity), a easy 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.
2231. Largest Number After Digit Swaps by Parity
Problem Explanation
Explanation
To find the largest possible value of the given number after swapping digits with the same parity, we can follow these steps:
- Separate the digits of the number into two lists, one for even digits and one for odd digits.
- Sort both lists in descending order.
- Combine the digits from both lists to form the largest number while ensuring that we swap digits only within the same parity group.
Time complexity: O(n log n) where n is the number of digits in the input number. Space complexity: O(n)
Solution Code
class Solution {
public int maximumSwap(int num) {
char[] digits = String.valueOf(num).toCharArray();
int[] lastIndexes = new int[10];
for (int i = 0; i < digits.length; i++) {
lastIndexes[digits[i] - '0'] = i;
}
for (int i = 0; i < digits.length; i++) {
for (int j = 9; j > digits[i] - '0'; j--) {
if (lastIndexes[j] > i) {
char temp = digits[i];
digits[i] = digits[lastIndexes[j]];
digits[lastIndexes[j]] = 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 2231 (Largest Number After Digit Swaps by Parity)?
This page provides optimized solutions for LeetCode problem 2231 (Largest Number After Digit Swaps by Parity) 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 2231 (Largest Number After Digit Swaps by Parity)?
The time complexity for LeetCode 2231 (Largest Number After Digit Swaps by Parity) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2231 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2231 in Java, C++, or Python.