File: largest-number-after-digit-swaps-by-parity/solution.py

Date: 2026-06-06

Time: 17:14

Purpose

This file is a self-contained solution to LeetCode 2231: Largest Number After Digit Swaps by Parity. It owns both the algorithm implementation and its test suite. The problem: given an integer, you can swap any two digits that share the same parity (both even or both odd) any number of times — return the largest value achievable.

Key Components

Solution.largestInteger(num: int) -> int

The core algorithm. Contract: accepts a positive integer, returns the largest integer obtainable by rearranging digits within their parity group while preserving each digit's parity-slot position.

TestLargestInteger

Eight test cases covering the examples from the problem, single digits, all-even, all-odd, repeated digits, and a large input with many zeros.

Patterns

Greedy sort-and-fill. Rather than simulating pairwise swaps (which could be O(n!) in the worst case), the solution recognizes that unlimited same-parity swaps let you rearrange each parity group freely. So the optimal strategy is: sort each group descending, then greedily assign the largest available same-parity digit to each position left-to-right.

This is the standard idiom for "unlimited swaps within a partition" problems — it reduces to independent sorting of each partition.

Dual-pointer reconstruction. Two index counters (oi, ei) walk through the sorted odd and even pools respectively. The original digit list determines which pointer advances at each position, guaranteeing parity-slot preservation.

Dependencies

Imports: Only unittest from the standard library — no external dependencies.

Imported by: The "Imported By" list in the prompt is misleading — those are test files from *other* problems that import unittest, not this file. This solution file is not imported by other solutions.

Flow

1. Decompose: str(num) → list of individual digit ints.

2. Partition & sort: Filter into odd/even sublists, each sorted descending (largest first).

3. Reconstruct: Walk the original digit positions. For each position, check the original digit's parity, pop the next value from the corresponding sorted pool, append to result.

4. Reassemble: Join digits into a string, convert back to int.

Example with num = 1234:

Invariants

Error Handling

None. The function trusts its input matches the LeetCode constraint (positive integer). No validation, no exceptions. This is appropriate for a competitive programming solution where the problem guarantees valid input.

Topics to Explore

Beliefs