Count Numbers with Non-Decreasing Digits - Problem

You are given two integers, l and r, represented as strings, and an integer b. Return the count of integers in the inclusive range [l, r] whose digits are in non-decreasing order when represented in base b.

An integer is considered to have non-decreasing digits if, when read from left to right (from the most significant digit to the least significant digit), each digit is greater than or equal to the previous one.

Since the answer may be too large, return it modulo 10⁹ + 7.

Input & Output

Example 1 — Basic Range in Base 10
$ Input: l = "12", r = "15", b = 10
Output: 4
💡 Note: Numbers 12, 13, 14, 15 all have non-decreasing digits. 12→[1,2], 13→[1,3], 14→[1,4], 15→[1,5].
Example 2 — Small Range in Base 2
$ Input: l = "1", r = "5", b = 2
Output: 2
💡 Note: In base 2: 1→[1], 2→[1,0], 3→[1,1], 4→[1,0,0], 5→[1,0,1]. Valid: 1 and 3 (count = 2)
Example 3 — Single Number
$ Input: l = "123", r = "123", b = 10
Output: 1
💡 Note: Only number 123 in range, digits 1≤2≤3 so it's valid

Constraints

  • 1 ≤ l ≤ r ≤ 1018
  • 2 ≤ b ≤ 10
  • l and r are given as strings

Visualization

Tap to expand
Count Numbers with Non-Decreasing Digits INPUT Range [l, r] in base b 12 15 Numbers: 12, 13, 14, 15 l "12" r "15" b 10 Non-decreasing check: 12: 1 <= 2 OK 13: 1 <= 3 OK 14: 1 <= 4 OK 15: 1 <= 5 OK ALGORITHM (DP) 1 Define DP State dp[pos][prev][tight][started] 2 Digit DP Recursion Try digits 0 to b-1 3 Check Constraint digit >= prev digit 4 Count f(r) - f(l-1) Range counting technique DP Transition Table pos prev tight cnt 0 0 T 1 1 1 T 4 1 1 F 9 f(15)=13, f(11)=10 FINAL RESULT f(r) - f(l-1) = f(15) - f(11) f(15) 13 - f(11) 10 = Answer 3 Valid Numbers: 12 13 14 All have non-decreasing digits 15: 1<=5 (also valid, included) Result mod 10^9+7 = 3 Key Insight: Digit DP allows counting valid numbers without iterating through the entire range. We track the previous digit and only place digits >= previous to maintain non-decreasing property. Use f(r) - f(l-1) for range counting. Time complexity: O(log(r) * b * b) where b is the base. Works efficiently for very large numbers as strings. TutorialsPoint - Count Numbers with Non-Decreasing Digits | DP Approach
Asked in
Google 15 Microsoft 12 Amazon 8
28.0K Views
Medium Frequency
~35 min Avg. Time
850 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