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.
Example 1:
Input: num = 1234 Output: 3412 Explanation: Swap the digit 3 with the digit 1, this results in the number 3214. Swap the digit 2 with the digit 4, this results in the number 3412. Note that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number. Also note that we may not swap the digit 4 with the digit 1 since they are of different parities.
Example 2:
Input: num = 65875 Output: 87655 Explanation: Swap the digit 8 with the digit 6, this results in the number 85675. Swap the first digit 5 with the digit 7, this results in the number 87655. Note that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number.
Constraints:
1 <= num <= 109This approach involves separating digits based on parity (odd and even). Once separated, each group is sorted in descending order. The digits from these sorted lists are then re-assigned to their original positions.
The C solution converts the integer to a string to process each digit. It segregates odd and even digits, sorts each group in descending order, then reconstructs the number by placing sorted digits back in their original parity positions.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n log n) due to sorting, where n is the number of digits.
Space Complexity: O(n) for the storage of digits.
This approach utilizes priority queues (heaps) to efficiently sort and retrieve the largest elements of each parity group. This guarantees that when re-constructing the number from sorted parts, the retrieval operations are optimal.
In C++, the standard priority_queue is used for maintaining a max-heap property. This helps in efficiently sorting and accessing the largest elements while maintaining a structured and clear approach.
Python
Time Complexity: O(n log n) due to heap operations.
Space Complexity: O(n) for the heaps storing the digits.
| Approach | Complexity |
|---|---|
| Sort Parity Groups | Time Complexity: O(n log n) due to sorting, where n is the number of digits. |
| Priority Queue (Heap) Utilization | Time Complexity: O(n log n) due to heap operations. |
I solved too many Leetcode problems • NeetCodeIO • 101,495 views views
Watch 9 more video solutions →Practice Largest Number After Digit Swaps by Parity with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor