File: split-with-minimum-sum/solution.py

Date: 2026-06-06

Time: 19:15

Purpose

This file solves LeetCode 2578: Split With Minimum Sum. Given a positive integer, split its digits into two new numbers such that their sum is minimized. The file owns both the solution implementation and its unit tests, following the repo's convention of colocating solution + tests in a single solution.py.

Key Components

minsumoftwonumbers(num: int) -> int

The core solver. Contract: accepts a positive integer (10 <= num <= 10^9), returns the minimum possible sum after splitting its digits into exactly two numbers.

Algorithm (greedy, sort-and-deal):

1. Convert num to its digit characters and sort them ascending.

2. Deal digits round-robin into two accumulators (parts[0] and parts[1]), alternating by index.

3. Convert both strings back to integers and return their sum.

This works because the greedy optimal strategy is: place the smallest digits in the highest-significance positions, and distribute evenly across both numbers so neither accumulates disproportionate magnitude. Sorting ensures smallest-first; round-robin ensures balanced length (differ by at most 1 digit).

TestMinSumOfTwoNumbers

Six test cases covering: the two LeetCode examples, the minimum-length input (2 digits), repeated digits, a large 9-digit input, and a number with embedded zeros (verifying that leading zeros in string parts are handled correctly by int() conversion).

Patterns

Dependencies

Imports: Only unittest from stdlib — no external dependencies.

Imported by: The testsolution.py files listed in the "Imported By" section don't actually import *this* file — that list appears to be a repo-wide cross-reference artifact. The real consumer is split-with-minimum-sum/testsolution.py, which likely imports minsumoftwonumbers from this module.

Flow


num=4325
  → str(num) = "4325"
  → sorted("4325") = ['2', '3', '4', '5']
  → deal: i=0 → parts[0]="2", i=1 → parts[1]="3", i=2 → parts[0]="24", i=3 → parts[1]="35"
  → int("24") + int("35") = 59

The round-robin assignment parts[i % 2] means even-indexed (0th, 2nd, ...) sorted digits go to parts[0] and odd-indexed go to parts[1]. Since digits are sorted ascending, the smallest digit becomes the leading digit of parts[0], second-smallest leads parts[1], and so on — minimizing place-value contribution.

Invariants

Error Handling

None. The function trusts its caller to provide a valid positive integer per the LeetCode constraint (10 <= num <= 10^9). No validation, no exception handling. Invalid inputs (negative, zero, single-digit) would produce silently wrong results or crash on int("") if num had fewer than 2 digits.

Topics to Explore

Beliefs