LeetCode #3519 — HARD

Count Numbers with Non-Decreasing Digits

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

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 109 + 7.

Example 1:

Input: l = "23", r = "28", b = 8

Output: 3

Explanation:

  • The numbers from 23 to 28 in base 8 are: 27, 30, 31, 32, 33, and 34.
  • Out of these, 27, 33, and 34 have non-decreasing digits. Hence, the output is 3.

Example 2:

Input: l = "2", r = "7", b = 2

Output: 2

Explanation:

  • The numbers from 2 to 7 in base 2 are: 10, 11, 100, 101, 110, and 111.
  • Out of these, 11 and 111 have non-decreasing digits. Hence, the output is 2.

Constraints:

  • 1 <= l.length <= r.length <= 100
  • 2 <= b <= 10
  • l and r consist only of digits.
  • The value represented by l is less than or equal to the value represented by r.
  • l and r do not contain leading zeros.
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: 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 109 + 7.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Math · Dynamic Programming

Example 1

"23"
"28"
8

Example 2

"2"
"7"
2

Related Problems

  • Count of Integers (count-of-integers)
  • Number of Beautiful Integers in the Range (number-of-beautiful-integers-in-the-range)
Step 02

Core Insight

What unlocks the optimal approach

  • Use digit dynamic programming.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3519: Count Numbers with Non-Decreasing Digits 
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3519: Count Numbers with Non-Decreasing Digits 
// package main
// 
// import (
// 	"fmt"
// 	"math/big"
// 	"strings"
// )
// 
// // https://space.bilibili.com/206214
// const mod = 1_000_000_007
// const maxN = 333 // 进制转换后的最大长度
// const maxB = 10
// 
// var comb [maxN + maxB][maxB]int
// 
// func init() {
// 	// 预处理组合数
// 	for i := 0; i < len(comb); i++ {
// 		comb[i][0] = 1
// 		for j := 1; j < min(i+1, maxB); j++ {
// 			// 注意本题组合数较小,无需取模
// 			comb[i][j] = comb[i-1][j-1] + comb[i-1][j]
// 		}
// 	}
// }
// 
// func trans(s string, b int, inc bool) string {
// 	x := &big.Int{}
// 	fmt.Fscan(strings.NewReader(s), x)
// 	if inc {
// 		x.Add(x, big.NewInt(1))
// 	}
// 	return x.Text(b) // 转成 b 进制
// }
// 
// func calc(s string, b int, inc bool) (res int) {
// 	s = trans(s, b, inc)
// 	// 计算小于 s 的合法数字个数
// 	// 为什么是小于?注意下面的代码,我们没有统计每个数位都填 s[i] 的情况
// 	pre := 0
// 	for i, d := range s {
// 		hi := int(d - '0')
// 		if hi < pre {
// 			break
// 		}
// 		m := len(s) - 1 - i
// 		res += comb[m+b-pre][b-1-pre] - comb[m+b-hi][b-1-hi]
// 		pre = hi
// 	}
// 	return
// }
// 
// func countNumbers(l, r string, b int) int {
// 	// 小于 r+1 的合法数字个数 - 小于 l 的合法数字个数
// 	return (calc(r, b, true) - calc(l, b, false)) % mod
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n × m)
Space
O(n × m)

Approach Breakdown

RECURSIVE
O(2ⁿ) time
O(n) space

Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.

DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space

Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.

Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Overflow in intermediate arithmetic

Wrong move: Temporary multiplications exceed integer bounds.

Usually fails on: Large inputs wrap around unexpectedly.

Fix: Use wider types, modular arithmetic, or rearranged operations.

State misses one required dimension

Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.

Usually fails on: Correctness breaks on cases that differ only in hidden state.

Fix: Define state so each unique subproblem maps to one DP cell.