Python 0233.py
class Solution:
# chop off a single digit per round
@cache
def compute(self, n):
if n == 0:
return 0
if n < 10:
return 1
# process highest digit first
s = str(n)
first = int(s[0])
withoutFirst = 0
digits = len(s)
if digits > 1:
withoutFirst = int(s[1:])
shift = 10**(digits - 1)
# e.g. if n = 345 => first = 3, shift = 100, digits = 2, withoutFirst = 45
# brute-force results:
# < 10 => 1
# < 100 => 20
# < 1000 => 300
# < 10000 => 4000
# < 100000 => 50000
# ...
result = first * (digits - 1) * shift // 10
if first > 1:
result += shift
else:
result += withoutFirst + 1 # initial 1 appears for each number
# count 1s for n without its first digit
result += self.compute(withoutFirst)
return result
def countDigitOne(self, n: int) -> int:
return self.compute(n)
Difficulty
and has an acceptance rate of about 39% (300k+ submissions).
Typical patterns to solve this problem:
- Dynamic Programming
- Math
- Recursion
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The presented module defines a Solution class that computes the total number of times the digit 1 appears in the decimal representation of all integers from 0 up to a given non-negative integer n. The public entry point is countDigitOne, which forwards the request to a memoized helper method compute. The algorithm works by decomposing the target number into its most significant digit and the remainder, applying a closed-form contribution for the leading digit, and then recursing on the suffix.
Core Logic
The recursion is anchored by two simple base cases. When the input is exactly zero the function returns zero because no positive integer has been examined. When the input is a single-digit positive number the answer is one, reflecting the solitary occurrence of the digit 1 in the range [0, n].
if n == 0:
return 0
if n < 10:
return 1
For numbers with two or more digits the algorithm first converts the integer to a string to isolate the most significant digit (first) and the remaining part (withoutFirst). The length of the string (digits) determines the positional weight (shift) of the leading digit, which is a power of ten equal to 10**(digits-1).
s = str(n)
first = int(s[0])
withoutFirst = 0
digits = len(s)
if digits > 1:
withoutFirst = int(s[1:])
shift = 10**(digits - 1)
The variable result accumulates the count contributed by the most significant digit across the entire range. The formula
first * (digits - 1) * shift // 10
captures the regular pattern that each full block of size shift contributes (digits-1) * shift // 10 occurrences of 1 in the lower positions, multiplied by the number of complete blocks (first).
When the leading digit exceeds one, an additional full block of size shift is added because the numbers from first * shift up to (first+1) * shift - 1 contain a complete set of lower-position 1 occurrences.
result = first * (digits - 1) * shift // 10
if first > 1:
result += shift
If the leading digit equals one, the contribution from the most significant position is limited to the numbers that actually appear in the suffix. In that case the algorithm adds withoutFirst + 1, which counts the 1 appearing as the most significant digit for each number from shift up to n.
else:
result += withoutFirst + 1 # initial 1 appears for each number
Finally, the function recurses on the suffix withoutFirst to account for 1 occurrences in the lower positions of numbers that share the same most significant digit. The recursive call is memoized, so repeated sub-problems are resolved instantly.
result += self.compute(withoutFirst)
return result
The public method simply forwards the request to the cached helper:
def countDigitOne(self, n: int) -> int:
return self.compute(n)
Edge Cases
The implementation explicitly handles the situation where the input is zero, returning a count of zero without further processing. For any single-digit positive input (1 through 9) the function returns one, correctly reflecting that only the number 1 contributes a single occurrence of the digit 1.
When the most significant digit is exactly one, the algorithm adds withoutFirst + 1 instead of a full shift. This adjustment ensures that the count does not over-estimate the contribution of the leading 1 for numbers that do not complete a full block of size shift.
Conversely, when the most significant digit exceeds one, the addition of a full shift correctly captures the complete set of lower-position 1 occurrences that appear in the extra block introduced by the higher leading digit.
The recursion terminates safely because each call reduces the number of digits by at least one, eventually reaching one of the base cases.
Performance Optimizations
A notable optimization is the use of the @cache decorator on compute. This memoization mechanism stores the result of each distinct argument, guaranteeing that any repeated evaluation of the same suffix value is answered in constant time. Since the recursion explores each suffix only once, the overall work is proportional to the number of digit positions rather than the magnitude of n.
The algorithm avoids iterating over every integer in the range. Instead, it leverages arithmetic relationships between digit positions, employing integer division and multiplication to compute contributions in closed form. This eliminates the need for per-number inspection and reduces the computational load dramatically.
String conversion is performed only once per recursive level to extract the leading digit and the remainder. Subsequent calculations rely exclusively on integer arithmetic (int, **, //, +), which is efficient in Python.
By combining memoization with a mathematically driven decomposition of the problem, the solution achieves rapid execution even for very large input values, scaling with the number of digits rather than the numeric size of the input.
ELI5 - Simplified Explanation
Imagine you have a big stack of number cards starting from zero all the way up to a number you pick. Your goal is to see how many times the digit one appears on all those cards combined.
When the number is very small, like a single digit, the answer is easy because one only shows up once. If the number is bigger, counting every single one by checking every card takes a super long time. Instead, this helper looks at the very front digit of the number to guess how many ones appear in that position for all the numbers that came before it.
It does this by chopping off the first digit one piece at a time. By looking at the front, it can use a shortcut to skip counting every single number. Once it knows how many ones were in that front spot, it tucks that answer away so it does not have to do the work again. Then, it looks at the rest of the number that is left over and plays the same game until there is nothing left to count. Adding all those smaller answers together gives the final total of every single one.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | C# | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | aylei | Rust | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| gaosq0604 | Python | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| wisdompeak | C++ | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, C#, Go, Java, Python, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| aylei | Rust | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| gaosq0604 | Python | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| wisdompeak | C++ | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 172: Factorial Trailing Zeroes
- problem 1215: Stepping Numbers
Solved On The Same Day
- problem 195: Tenth Line
- problem 53: Maximum Subarray
- problem 56: Merge Intervals
- problem 78: Subsets
- problem 86: Partition List
- problem 89: Gray Code
- problem 90: Subsets II
- problem 98: Validate Binary Search Tree
- problem 179: Largest Number
- problem 456: 132 Pattern
- problem 473: Matchsticks to Square
- problem 542: 01 Matrix
- problem 916: Word Subsets
- problem 1930: Unique Length-3 Palindromic Subsequences
- problem 295: Find Median from Data Stream
- problem 315: Count of Smaller Numbers After Self
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality