Problem Description
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 any number of swaps.
Key Insights
- Digits can be classified into two categories: even and odd.
- We can freely swap digits within each category to form the largest number possible.
- The largest number can be achieved by sorting even digits and odd digits independently in descending order.
- After sorting, we reconstruct the number by placing the digits back in their original positions according to their parity.
Space and Time Complexity
Time Complexity: O(n log n), where n is the number of digits in the number (due to sorting). Space Complexity: O(n), for storing the digits and the sorted digits.
Solution
To solve this problem, we will follow these steps:
- Convert the number into a list of its digits.
- Separate the digits into two lists based on their parity: one for even digits and another for odd digits.
- Sort both lists in descending order.
- Reconstruct the number by iterating through the original list of digits and replacing them with the next largest digit from the corresponding sorted list based on their parity.
This approach ensures that we get the largest possible number after the allowed swaps.