File: check-if-number-has-equal-digit-count-and-digit-value/solution.py

Date: 2026-06-06

Time: 15:41

Purpose

This file solves LeetCode 2283: Check if Number Has Equal Digit Count and Digit Value. It's a self-describing number check: given a string num of length n, verify that for every index i (0 through n-1), the digit i appears in num exactly int(num[i]) times.

For example, "1210" is valid: digit 0 appears 1 time, digit 1 appears 2 times, digit 2 appears 1 time, digit 3 appears 0 times.

Key Components

Solution.digitCount(self, num: str) -> bool — The core method. Counts digit frequencies with Counter, then checks every index against its expected count in a single all() expression.

rearrange_array — A module-level alias that binds Solution().digitCount to a bare function name. This is a project convention so tests can import a uniform entry point without caring about the Solution class.

Patterns

Counter + all() — A common idiom in this repo for frequency-validation problems. Counter(num) builds the frequency map in O(n), then all(...) short-circuits on the first mismatch. The string-to-int conversion (int(num[i])) and int-to-string conversion (str(i)) bridge the two representations: Counter keys are characters, but i is an integer index.

Missing-key safetyCounter returns 0 for absent keys, so count[str(i)] never raises KeyError even when digit i doesn't appear in num. This is load-bearing — a plain dict would break here.

Dependencies

Imports: collections.Counter — the only dependency.

Imported by: The corresponding test_solution.py imports from this module. The massive "Imported By" list in the context is a red herring — that's the test harness's shared import mechanism pulling in all solution modules, not a real dependency relationship.

Flow

1. Counter(num) builds a {char: count} dict from the input string.

2. range(len(num)) iterates index i from 0 to n-1.

3. For each i, compare count[str(i)] (actual frequency of digit i) against int(num[i]) (expected frequency declared at position i).

4. all() returns True only if every index satisfies the equality.

Invariants

Error Handling

None. The function trusts the caller to pass a valid digit string per the LeetCode contract. Passing non-digit characters or an empty string would produce wrong results silently, not exceptions (thanks to Counter's defaulting behavior).

Topics to Explore

Beliefs