Largest Number After Digit Swaps by Parity — LeetCode 2231 Python Solution

EasySortingHeap (Priority Queue)
Problem
#2231
Reading time
2 min

The problem

You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e.

Example

Input
num = 1234
Output
3412
Explanation
Swap the digit 3 with the digit 1, this results in the number 3214.

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(\log \textit{num})
SpaceO(\log \textit{num}) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2231. Largest Number After Digit Swaps by Parity is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Heap (Priority Queue).

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2231. Largest Number After Digit Swaps by Parity?
LeetCode 2231. Largest Number After Digit Swaps by Parity is rated Easy on LeetCode.
What is the time complexity of LeetCode 2231. Largest Number After Digit Swaps by Parity?
The Python solution on this page runs in O(\log \textit{num}).
What is the space complexity of LeetCode 2231. Largest Number After Digit Swaps by Parity?
The Python solution on this page uses O(\log \textit{num}) auxiliary space.
What topics does LeetCode 2231. Largest Number After Digit Swaps by Parity cover?
LeetCode 2231. Largest Number After Digit Swaps by Parity is tagged Sorting and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview