Digit Count in Range Problem
Description
LeetCode Problem 1067.
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 1:
Input: d = 1, low = 1, high = 13
Output: 6
Explanation: The digit d = 1 occurs 6 times in 1, 10, 11, 12, 13.
Note that the digit d = 1 occurs twice in the number 11.
Example 2:
Input: d = 3, low = 100, high = 250
Output: 35
Explanation: The digit d = 3 occurs 35 times in 103,113,123,130,131,...,238,239,243.
Constraints:
0 <= d <= 91 <= low <= high <= 2 * 10^8
Solution
Approach: Count Place by Place
Let count(n) be the number of times d is written in 1, 2, ..., n. The answer is count(high) - count(low - 1).
To compute count(n), look at one place at a time (ones, tens, hundreds, ...) with value p, and ask: for how many numbers in 1..n is the digit at this place equal to d? Split n around that place into higher = n / (10p), the digit cur = (n / p) % 10, and lower = n % p. For example, n = 3141 and p = 10 give higher = 31, cur = 4, lower = 1.
For d > 0:
- with a prefix of
0 .. higher - 1in front of the digit, every one of thependings is allowed:higher * pnumbers; - with prefix exactly
higher, it depends oncur: allpendings ifcur > d, the endings0..lower(that islower + 1numbers) ifcur == d, and none ifcur < d.
For d = 0 there is a catch: a 0 written in front of a number is a leading zero and is not counted. So the prefix must be at least 1: prefixes 1 .. higher - 1 give (higher - 1) * p, prefix higher gives p if cur > 0 and lower + 1 if cur == 0, and once higher is 0 no number has a written 0 at this place or any higher one.
Check with d = 1, n = 13: the ones place gives 1 * 1 + 1 = 2 (the numbers 1 and 11), the tens place gives 0 + (3 + 1) = 4 (10 to 13), total 6.
Complexity: O(log n) time, one step per digit, and O(1) extra space.
class Solution:
def digitsCount(self, d: int, low: int, high: int) -> int:
return self.count(high, d) - self.count(low - 1, d)
def count(self, n: int, d: int) -> int:
"""How many times digit d is written in 1, 2, ..., n."""
total = 0
p = 1 # the place we look at: ones, tens, hundreds, ...
while p <= n:
higher, cur, lower = n // (p * 10), n // p % 10, n % p
if d > 0:
# Prefixes 0 .. higher - 1 allow every lower part; prefix higher depends on cur.
total += higher * p
if cur > d:
total += p
elif cur == d:
total += lower + 1
else:
if higher == 0:
break # a 0 here would be a leading zero
# A 0 needs a non-zero prefix: 1 .. higher - 1, then prefix higher.
total += (higher - 1) * p
total += p if cur > 0 else lower + 1
p *= 10
return total