Largest Number After Digit Swaps by Parity - Problem
You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits).
Return the largest possible value of num after performing any number of such swaps.
Note: Digits with the same parity can be rearranged in any order to maximize the number.
Input & Output
Example 1 — Basic Case
$
Input:
num = 1234
›
Output:
3214
💡 Note:
Odd digits [1,3] can be rearranged to [3,1], even digits [2,4] to [4,2]. Result: 3214
Example 2 — Same Parity Only
$
Input:
num = 65875
›
Output:
87655
💡 Note:
Odd digits [5,7,5] sorted descending: [7,5,5]. Even digits [6,8] sorted: [8,6]. Result: 87655
Example 3 — Already Optimal
$
Input:
num = 247
›
Output:
427
💡 Note:
Even digits [2,4] become [4,2], odd digit [7] stays. Result: 427
Constraints
- 1 ≤ num ≤ 109
- num consists of digits only
Visualization
Tap to expand
Understanding the Visualization
1
Input
Number 1234 with odd digits [1,3] and even digits [2,4]
2
Process
Sort odds [3,1] and evens [4,2] in descending order
3
Output
Reconstruct to get maximum value: 3214
Key Takeaway
🎯 Key Insight: Digits of the same parity can be freely rearranged - sort them descending for maximum value
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code