Digit Count in Range - 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].

For example, if d = 1, low = 1, and high = 13, then we need to count how many times the digit 1 appears in numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13. The digit 1 appears in: 1 (once), 10 (once), 11 (twice), 12 (once), 13 (once), for a total of 6 occurrences.

Note: Each digit position in a multi-digit number is counted separately. For instance, the number 11 contains the digit 1 twice.

Input & Output

Example 1 — Basic Case
$ Input: d = 1, low = 1, high = 13
Output: 6
💡 Note: Count digit 1 in range [1,13]: appears in 1 (1 time), 10 (1 time), 11 (2 times), 12 (1 time), 13 (1 time). Total = 6.
Example 2 — Digit Zero
$ Input: d = 0, low = 10, high = 20
Output: 2
💡 Note: Count digit 0 in range [10,20]: appears in 10 (1 time), 20 (1 time). Total = 2.
Example 3 — Single Number
$ Input: d = 3, low = 3, high = 3
Output: 1
💡 Note: Only number 3 in range, digit 3 appears once.

Constraints

  • 0 ≤ d ≤ 9
  • 1 ≤ low ≤ high ≤ 2 × 108

Visualization

Tap to expand
Digit Count in Range - DP Approach INPUT Range [low, high] 1 2 3 4 ... 12 13 Finding digit d = 1 1 10 11 12 13 Input Values d = 1 low = 1 high = 13 ALGORITHM STEPS 1 Define DP State count(n) = count of d in [0,n] 2 Digit DP Recursion Process each digit position 3 Count at Each Pos Track tight bound constraint 4 Final Calculation count(high) - count(low-1) Counting '1' in each number: 1 --> 1 occurrence 2-9 --> 0 occurrences 10 --> 1 occurrence 11 --> 2 occurrences 12,13 --> 1 each FINAL RESULT Count Breakdown Number 1: 1 one Number 10: 1 one Number 11: 2 ones Number 12: 1 one Number 13: 1 one Total: 1+1+2+1+1 = 6 (2-9 have 0 ones) OUTPUT 6 OK - Result verified Key Insight: Digit DP breaks the problem into counting digits position by position. For each position, we track whether we're at the upper bound (tight constraint). The formula count(high) - count(low-1) gives us the count in range [low, high]. This avoids iterating through each number individually. TutorialsPoint - Digit Count in Range | Dynamic Programming (Digit DP)
Asked in
Google 15 Facebook 12 Amazon 8
28.0K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen