File: number-of-different-integers-in-a-string/solution.py

Date: 2026-06-06

Time: 18:16

number-of-different-integers-in-a-string/solution.py

Purpose

This file solves LeetCode 1805: Number of Different Integers in a String. It owns both the solution and its test suite in a single module — the standard layout across this repository.

Key Components

numdifferentintegers(word: str) -> int — The sole public function. Takes a mixed alphanumeric string and returns the count of distinct integers embedded in it. The contract: letters act as separators, leading zeros are normalized (so "1", "01", and "001" are all the same integer), and a string with no digits returns 0.

TestNumDifferentIntegers — Nine test cases covering the LeetCode examples plus edge cases (all-letters, all-digits, zeros, leading zeros).

Patterns

The solution follows a replace-split-normalize idiom in two lines:

1. re.sub(r'[a-z]', ' ', word) — Replace every lowercase letter with a space, leaving digit runs intact.

2. .split() — Split on whitespace, naturally handling consecutive letters (multiple spaces collapse).

3. {n.lstrip('0') or '0' for n in nums} — Set comprehension for dedup. lstrip('0') normalizes leading zeros; the or '0' fallback handles the all-zeros case (where lstrip would produce an empty string).

The len(set(...)) pattern is the idiomatic Python way to count distinct elements.

Dependencies

Imports: re (regex substitution) and unittest (test harness). No project-internal dependencies.

Imported by: The test_solution.py in this same directory, plus the "Imported By" list in the prompt is misleading — that list appears to be the full set of test files across the repo that share the same unittest import pattern, not actual importers of this module.

Flow


word = "a123bc34d8ef34"
  → re.sub letters → " 123  34 8  34"
  → split           → ["123", "34", "8", "34"]
  → set comprehension with lstrip('0')
                     → {"123", "34", "8"}
  → len             → 3

The entire transformation is a single expression pipeline — no loops, no mutable state.

Invariants

Error Handling

None. The function assumes valid input per LeetCode constraints. No try/except, no input validation. Invalid input (e.g., uppercase letters, special characters) would silently produce wrong results rather than raising.

Topics to Explore

Beliefs