Leetcode #2231: Largest Number After Digit Swaps by Parity
In this guide, we solve Leetcode #2231 Largest Number After Digit Swaps by Parity in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e.
Quick Facts
- Difficulty: Easy
- Premium: No
- Tags: Sorting, Heap (Priority Queue)
Intuition
We need to repeatedly access the smallest or largest element as the input changes.
A heap provides fast insertions and removals while keeping order.
Approach
Push candidates into the heap as you scan, and pop when you need the best element.
Keep the heap size bounded if the problem requires a top-k structure.
Steps:
- Push candidates into a heap.
- Pop the best candidate when needed.
- Maintain heap size or invariants.
Example
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.
Python Solution
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
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.