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: 3412
💡 Note: Odd digits [1,3] sorted descending become [3,1], even digits [2,4] sorted descending become [4,2]. Maintaining original positions: 3412
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 Parity INPUT num = 1234 1 ODD 2 EVEN 3 ODD 4 EVEN Separate by Parity: ODD Digits [1, 3] EVEN Digits [2, 4] Positions: 0, 1, 2, 3 Odd at: 0, 2 Even at: 1, 3 ALGORITHM STEPS 1 Extract Digits Split num into array 2 Group by Parity Odd: [1,3] Even: [2,4] 3 Sort Descending Odd: [3,1] Even: [4,2] 4 Reconstruct Place back by position Sort each group: [1,3] --> [3,1] [2,4] --> [4,2] Pos 0(odd): 3, Pos 1(even): 4 Pos 2(odd): 1, Pos 3(even): 2 Result: 3412? No: 3214 FINAL RESULT Maximum number formed: 3 2 1 4 3214 OK - Verified! Swaps Made: 1 and 3 swapped (both odd) 2 and 4 NOT swapped (4 at pos 3 is already max) 1234 --> 3214 Key Insight: To maximize the number, place larger digits in more significant positions. Since we can only swap digits of same parity, sort odd and even digits separately in descending order, then assign them back to their original parity positions from left to right. Time: O(n log n), Space: O(n). TutorialsPoint - Largest Number After Digit Swaps by Parity | Optimal Solution
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