Largest Number After Digit Swaps by Parity - Problem
Maximize Your Number Through Strategic Digit Swapping!

You're given a positive integer num and have a special power: you can swap any two digits that share the same parity (both odd or both even). Your mission is to rearrange the digits to create the largest possible number.

Key Rules:
• Even digits (0, 2, 4, 6, 8) can only swap with other even digits
• Odd digits (1, 3, 5, 7, 9) can only swap with other odd digits
• You can perform unlimited swaps

Goal: Return the maximum possible value after optimal swapping.

Example: Given 1234, you can swap 1↔3 and 2↔4 independently to get 3412.

Input & Output

example_1.py — Basic Case
$ Input: num = 1234
Output: 3412
💡 Note: We can swap odd digits (1↔3) and even digits (2↔4) independently. The optimal arrangement puts the largest odd digit (3) first, largest even digit (4) second, remaining odd (1) third, and remaining even (2) last.
example_2.py — All Same Parity
$ Input: num = 65875
Output: 87655
💡 Note: All digits are odd, so we can rearrange them in any order. To get the largest number, we sort them in descending order: [8,7,6,5,5].
example_3.py — Already Optimal
$ Input: num = 247
Output: 427
💡 Note: Even digits: [2,4] → sort to [4,2]. Odd digits: [7] stays [7]. Reconstruction following original positions (odd,even,odd) gives us 427.

Visualization

Tap to expand
The Parity Sorting Dance: 1234 → 34121Red (Odd)2Blue (Even)3Red (Odd)4Blue (Even)Step 1: Group by ColorRed Group[1, 3]Blue Group[2, 4]Step 2: Sort by Height (Descending)Red Sorted[3, 1]Blue Sorted[4, 2]Step 3: Reconstruct FormationPlace tallest of each color in original positions:34123412
Understanding the Visualization
1
Identify Groups
Separate red dancers (odd digits) from blue dancers (even digits)
2
Sort by Height
Arrange each color group in descending order by height (digit value)
3
Reconstruct Formation
Place dancers back in their original color positions, but now optimally sorted
Key Takeaway
🎯 Key Insight: Since digits of the same parity can be rearranged freely, we simply need to sort each parity group in descending order and place them back optimally!

Time & Space Complexity

Time Complexity
⏱️
O(n log n)

Single sorting operation dominates the time complexity

n
2n
Linearithmic
Space Complexity
O(1)

In-place sorting with only constant extra space

n
2n
Linear Space

Constraints

  • 1 ≤ num ≤ 109
  • num consists of positive digits only (no leading zeros)
  • The input is guaranteed to be a valid positive integer
Asked in
Amazon 15 Google 12 Meta 8 Microsoft 6
42.4K Views
Medium Frequency
~15 min Avg. Time
1.8K 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