Number of Digit One — LeetCode 233 Python Solution

HardRecursionMathDynamic Programming
Problem
#233
Reading time
2 min

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

MeasureComplexity
TimeO(m^2 \times D)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview