HardNo. 1067LeetCode Premium

Digit Count in Range — LeetCode 1067 Python Solution

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

PythonSolution
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

Time
O(n·m) (typical)
Space · auxiliary
O(n·m)or optimized

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

Related problems
No.ProblemDifficulty
0062Unique PathsMedium
0070Climbing StairsEasy
0096Unique Binary Search TreesMedium
0233Number of Digit OneHard
0241Different Ways to Add ParenthesesMedium
0279Perfect SquaresMedium

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.

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