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: Count digit 1 in [1, 13]Numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13Digit 1 appears in: 1, 10, 11, 11, 12, 131 → count +110 → count +111 → count +212 → count +113 → count +1Total Count: 6
Understanding the Visualization
1
Input
Digit d=1, range [1,13]
2
Process
Count digit 1 in each number
3
Output
Total count = 6
Key Takeaway
🎯 Key Insight: Use mathematical digit DP to avoid iterating through every number in the range
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