Digit Count in Range — LeetCode 1067 Python Solution

HardLeetCode PremiumMathDynamic Programming
Problem
#1067
Reading time
4 min

The problem

Given a single-digit integer d and two integers low and high, return the number of times that d occurs as a digit in all integers in the inclusive range [low, high].

Example

Input
d = 1, low = 1, high = 13
Output
6
Explanation
The digit d = 1 occurs 6 times in 1, 10, 11, 12, 13.

Python solution

Python
class Solution:
    def digitsCount(self, d: int, low: int, high: int) -> int:
        return self.f(high, d) - self.f(low - 1, d)

    def f(self, n, d):
        @cache
        def dfs(pos, cnt, lead, limit):
            if pos <= 0:
                return cnt
            up = a[pos] if limit else 9
            ans = 0
            for i in range(up + 1):
                if i == 0 and lead:
                    ans += dfs(pos - 1, cnt, lead, limit and i == up)
                else:
                    ans += dfs(pos - 1, cnt + (i == d), False, limit and i == up)
            return ans

        a = [0] * 11
        l = 0
        while n:
            l += 1
            a[l] = n % 10
            n //= 10
        return dfs(l, 0, True, True)

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1067. Digit Count in Range 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 1067. Digit Count in Range?
LeetCode 1067. Digit Count in Range is rated Hard on LeetCode.
What topics does LeetCode 1067. Digit Count in Range cover?
LeetCode 1067. Digit Count in Range is tagged Math and Dynamic Programming on LeetCode.
Is LeetCode 1067. Digit Count in Range a premium problem?
Yes. LeetCode 1067. Digit Count in Range is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

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