Digit Count in Range

Asked atAmazon
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

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].

Input: d = 2, low = 2, high = 25 Output: 9 Explanation: The digit d = 2 occurs 9 times in 2,20,12,21, 22, 23, 24,25.

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.

Input: d = 1, low = 1, high = 13

  • 0 <= d <= 9
  • 1 <= low <= high <= 2 * 108

cpp

class Solution {
    public:
    int digitsCount(int d, int low, int high) {
        //User code goes here
        
    }
};

java

class Solution {
    public int digitsCount(int d, int low, int high) {
        // User code goes here
    }
}

python

class Solution:
    def digitsCount(self, d: int, low: int, high: int) -> int:
        # User code goes here

javascript

class Solution {
    digitsCount(d, low, high) {
        // User Code goes here
    }
}

csharp

public class Solution
{
    public int DigitsCount(int d, int low, int high)
    {
        // User code goes here
    }
}

go

func digitsCount(d int, low int, high int) int {
	// User code goes here
}
Stuck? Show a way to structure it+
  1. 01Compute occurrences in `[1,n]` and subtract `count(low-1)`.
  2. 02For each decimal factor, split n into higher, current, and lower parts.
  3. 03Use the standard three-case formula for nonzero digit d.
  4. 04Handle d=0 separately to avoid counting leading zeroes.

Reference answer

Then expect these follow-ups

  • How would you count all digits 0 through 9 at once?

    Tests: digit counting

  • How would a digit-DP solution handle arbitrary bounds?

    Tests: digit DP

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question