#2231
Largest Number After Digit Swaps by Parity
EasySortingHeap (Priority Queue)SortingTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution involves separating the digits into even and odd groups, sorting them in descending order, and then reconstructing the number. This approach is efficient because it directly targets the problem without generating permutations.
⚙️
Algorithm
4 steps- 1Step 1: Convert the number into a string to access each digit.
- 2Step 2: Separate the digits into two lists: one for even digits and one for odd digits.
- 3Step 3: Sort both lists in descending order.
- 4Step 4: Reconstruct the number by iterating through the original digits and replacing them with the largest available digit from the sorted lists based on parity.
solution.py16 lines
1# Full working Python code
2
3def largestNumber(num):
4 digits = list(str(num))
5 even_digits = sorted([d for d in digits if int(d) % 2 == 0], reverse=True)
6 odd_digits = sorted([d for d in digits if int(d) % 2 != 0], reverse=True)
7 even_index, odd_index = 0, 0
8 result = []
9 for d in digits:
10 if int(d) % 2 == 0:
11 result.append(even_digits[even_index])
12 even_index += 1
13 else:
14 result.append(odd_digits[odd_index])
15 odd_index += 1
16 return int(''.join(result))ℹ
Complexity note: The time complexity is O(n log n) due to the sorting of the even and odd digits, while the space complexity is O(n) for storing the digits.
- 1Digits can only be swapped if they share the same parity.
- 2Sorting the digits allows us to maximize the number by placing larger digits in more significant positions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.