Digit DP Counter - Problem

Given a positive integer N, count how many numbers from 1 to N (inclusive) satisfy a specific digit property.

For this problem, we need to count numbers where no two adjacent digits are the same.

For example:

  • 123 is valid (all adjacent digits are different)
  • 112 is invalid (digits 1 and 1 are adjacent and same)
  • 5 is valid (single digit numbers are always valid)

Constraints:

  • 1 ≤ N ≤ 10^18

Input & Output

Example 1 — Small Range
$ Input: n = 25
Output: 22
💡 Note: Valid numbers: 1,2,3,4,5,6,7,8,9,10,12,13,14,15,16,17,18,19,20,21,23,24,25. Invalid: 11,22 (adjacent same digits). Total: 22 valid numbers.
Example 2 — Single Digit
$ Input: n = 9
Output: 9
💡 Note: All single digit numbers 1,2,3,4,5,6,7,8,9 are valid (no adjacent digits to compare). Count: 9
Example 3 — Larger Range
$ Input: n = 100
Output: 90
💡 Note: All single digits (1-9): 9 valid. Two-digit numbers: 10,12,13...98 excluding 11,22,33,44,55,66,77,88,99. Count: 9 + 81 = 90

Constraints

  • 1 ≤ n ≤ 1018

Visualization

Tap to expand
INPUTALGORITHMRESULTN = 25Numbers 1 to 25:1,2,3,4,5,6,7,8,9,10✓ Valid: no adjacent same11,12,13,14,15,16,17,18,19,2011: 1=1 ✗21,22,23,24,2522: 2=2 ✗Need to count efficiently!1Build digit by digit2Track: pos, prev_digit, tight3Choose valid digits ≠ previous4Memoize to avoid recomputationDigit DP: O(log N)Count: 22Valid numbers found:All except 11, 22✓ Efficient countingKey Insight:Use digit DP to count valid digit sequences without generating every number.Build numbers position by position with memoization for efficiency.TutorialsPoint - Digit DP Counter | Digit DP with Memoization
Asked in
Google 25 Microsoft 18 Amazon 15
28.0K Views
Medium Frequency
~35 min Avg. Time
890 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