HardNo. 0233

Number of Digit One — LeetCode 233 Python Solution

Topics
Recursion, Math, Dynamic Programming
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

PythonSolution
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

Time
O(m2 × D)
Space · auxiliary
O(m2)

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

Related problems
No.ProblemDifficulty
0241Different Ways to Add ParenthesesMedium
0486Predict the WinnerMedium
0509Fibonacci NumberEasy
0010Regular Expression MatchingHard
0044Wildcard MatchingHard
0062Unique PathsMedium

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(m2 × D).

What is the space complexity of LeetCode 233. Number of Digit One?

The Python solution on this page uses O(m2) 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.

Free to download. Check it runs on your machine, then pick a plan.