Number of Digit One — LeetCode 233 Python Solution
HardRecursionMathDynamic Programming
- Problem
- #233
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
Example
- Input
- n = 13
- Output
- 6
Python solution
Python
class Solution:
def countDigitOne(self, n: int) -> int:
@cache
def dfs(i: int, cnt: int, limit: bool) -> int:
if i >= len(s):
return cnt
up = int(s[i]) if limit else 9
ans = 0
for j in range(up + 1):
ans += dfs(i + 1, cnt + (j == 1), limit and j == up)
return ans
s = str(n)
return dfs(0, 0, True)Complexity
| Measure | Complexity |
|---|---|
| Time | O(m^2 \times D) |
| Space | O(m^2) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 233. Number of Digit One is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 233. Number of Digit One?
- LeetCode 233. Number of Digit One is rated Hard on LeetCode.
- What is the time complexity of LeetCode 233. Number of Digit One?
- The Python solution on this page runs in O(m^2 \times D).
- What is the space complexity of LeetCode 233. Number of Digit One?
- The Python solution on this page uses O(m^2) auxiliary space.
- What topics does LeetCode 233. Number of Digit One cover?
- LeetCode 233. Number of Digit One is tagged Recursion, Math and Dynamic Programming on LeetCode.