Leetcode 2231. Largest Number After Digit Swaps by Parity
You are given a positive integer num
. You may swap any two digits of num
that have the same parity (i.e., both are odd digits or both are even digits). Return the largest possible value of num
you can get by performing any number of swaps.
Example 1:
Input: num = 1234
Output: 3412
Explanation: Swap the digit 3 and the digit 1, and swap the digit 4 and the digit 2.
Example 2:
Input: num = 65875
Output: 87655
Explanation: Swap the digit 8 and the digit 6, and swap the digit 7 and the digit 5.
num
into two lists: one for even digits and one for odd digits.public class LargestNumberByParitySwap {
public static int largestInteger(int num) {
// Convert number to string for easy digit manipulation
String numStr = Integer.toString(num);
char[] digits = numStr.toCharArray();
// Lists to hold even and odd digits
List<Character> evens = new ArrayList<>();
List<Character> odds = new ArrayList<>();
// Separate digits into even and odd lists
for (char digit : digits) {
if ((digit - '0') % 2 == 0) {
evens.add(digit);
} else {
odds.add(digit);
}
}
// Sort the lists in descending order
Collections.sort(evens, Collections.reverseOrder());
Collections.sort(odds, Collections.reverseOrder());
// Indices to keep track of current position in the sorted lists
int evenIndex = 0;
int oddIndex = 0;
// Resultant array to construct the largest number
char[] result = new char[digits.length];
// Fill the resultant array with the largest possible digits of correct parity
for (int i = 0; i < digits.length; i++) {
if ((digits[i] - '0') % 2 == 0) {
result[i] = evens.get(evenIndex++);
} else {
result[i] = odds.get(oddIndex++);
}
}
// Convert the result array back to an integer
return Integer.parseInt(new String(result));
}
public static void main(String[] args) {
// Test cases
System.out.println(largestInteger(1234)); // Output: 3412
System.out.println(largestInteger(65875)); // Output: 87655
}
}
Overall Time Complexity: O(n log n)
This approach ensures that the result is constructed in the largest possible manner by considering parity-based swaps while ensuring efficiency.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?