Largest Number After Digit Swaps by Parity Problem
Description
LeetCode Problem 2231.
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 <= 10^9
Solution
Approach: Counting
Digits may only be swapped with digits of the same parity, so the best number puts the largest odd digits in the odd positions and the largest even digits in the even positions, while each position keeps its parity.
Count how many times each digit occurs. Keep two pointers idx = [8, 9], the largest even and odd digit that might still be unused. Go through the digits of num from left to right. For a digit of parity p, move idx[p] down by 2 until its count is non-zero, append that digit to the answer and decrease its count.
Complexity: O(log num) time and space.
class Solution:
def largestInteger(self, num: int) -> int:
nums = [int(c) for c in str(num)]
cnt = Counter(nums)
idx = [8, 9]
ans = 0
for x in nums:
while cnt[idx[x & 1]] == 0:
idx[x & 1] -= 2
ans = ans * 10 + idx[x & 1]
cnt[idx[x & 1]] -= 1
return ans