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
Largest Number After Digit Swaps by ParityInput: 12341234oddevenoddevenGroup & Sort[3,1][4,2]odds sorted ↓evens sorted ↓Reconstruct3214Output: 3214Maximum possible value achieved!
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
Asked in
Google 15 Amazon 12
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen