BackeasyDynamic ProgrammingCapgeminiAmazon

Balanced Tree Span Calculator 3 Solution

Problem Statement

Given two non‑negative integers L and R (0 ≤ L ≤ R ≤ 10^18) and an integer D (0 ≤ D ≤ 9), a number x is called D‑balanced if, when x is written in decimal without leading zeros, the difference between its largest digit and its smallest digit does not exceed D. Your task is to determine how many D‑balanced integers lie in the inclusive interval [L, R]. The answer must be produced as a single integer.

Example 1
Input
1 20 1
Output
12

Explanation: All single‑digit numbers (1‑9) are D‑balanced because max‑min = 0 ≤ 1, giving 9 numbers. For two‑digit numbers between 10 and 20 we check the digit spread: 10 → digits {1,0}, spread = 1 (valid) 11 → {1,1}, spread = 0 (valid) 12 → {1,2}, spread = 1 (valid) 13 → spread = 2 (invalid) and all larger numbers up to 20 have spread ≥2. Hence only 10, 11, 12 are valid. Total = 9 + 3 = 12.

Example 2
Input
100 200 0
Output
1

Explanation: D = 0 forces every digit of a valid number to be identical. Between 100 and 200 the only integer whose three decimal digits are all equal is 111. Therefore the count is 1.

Example 3
Input
0 55 1
Output
24

Explanation: Numbers 0‑9 (10 numbers) are always valid because they consist of a single digit. For two‑digit numbers we need |t‑u| ≤ 1 where t is the tens digit and u the units digit. - Tens = 1 → {10,11,12} (3 numbers) - Tens = 2 → {21,22,23} (3 numbers) - Tens = 3 → {32,33,34} (3 numbers) - Tens = 4 → {43,44,45} (3 numbers) - Tens = 5 → {54,55} (2 numbers, 56 exceeds the upper bound 55) Total two‑digit valid numbers = 3+3+3+3+2 = 14. Adding the 10 single‑digit numbers yields 24.

Constraints

  • 0 ≤ L ≤ R ≤ 10^18
  • 0 ≤ D ≤ 9
  • The program must run in O(number of digits × 10) time, i.e., within a few hundred operations per query.
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Balanced Tree Span Calculator 3 — Problem Statement & Solution Guide

Dynamic ProgrammingEasyDigit DP
TimeO(19·10·10·2) ≈ O(3800) ≈ O(1)
|
SpaceO(19·10·10·2) ≈ O(3800) ≈ O(1)

Problem Description

Given two non‑negative integers L and R (0 ≤ L ≤ R ≤ 10^18) and an integer D (0 ≤ D ≤ 9), a number x is called D‑balanced if, when x is written in decimal without leading zeros, the difference between its largest digit and its smallest digit does not exceed D. Your task is to determine how many D‑balanced integers lie in the inclusive interval [L, R]. The answer must be produced as a single integer.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Balanced Tree Span Calculator 3"

easy

WHY DOES IT MATTER?

Digit‑DP is essential because it transforms a problem with an astronomically large input space into a manageable state machine. It leverages the fact that the property depends only on digits, allowing us to reuse computations across different prefixes. Without it, the problem would be unsolvable within time limits.

OPTIMIZATION CHALLENGE

The critical insight is to encode the minimum and maximum digits seen so far into the DP state. This reduces the problem from exponential in the number of digits to quadratic in the digit range (10×10), turning an impossible enumeration into a constant‑time algorithm.

REAL-WORLD CONNECTION

Think of a distributed system that processes log entries: each log line is parsed into fields (digits), and a global rule (max‑min ≤ D) must be applied. Instead of scanning every log line individually, the system aggregates partial results per field and combines them, analogous to how digit‑DP aggregates partial digit states.

When explaining your solution, emphasize the state compression: position, tight flag, min, max. Show how memoization eliminates redundant work, and practice walking through a small example to demonstrate the DP transitions.

COMPLEXITY AT A GLANCE

⏱ Time:O(19·10·10·2) ≈ O(3800) ≈ O(1)
💾 Space:O(19·10·10·2) ≈ O(3800) ≈ O(1)

Core Theory — Why This Approach?

The problem asks for the number of integers in a huge interval [L,R] (up to 10^18) whose decimal representation satisfies a simple digit‑wise property: the difference between the largest and smallest digit is at most D. A naive enumeration would require iterating over every number in the interval, which is impossible for 10^18 values. The key insight is that the property depends only on the digits of a number, not on its magnitude, so we can solve it with a digit‑dynamic‑programming (digit‑DP) approach.

In digit‑DP we process the decimal digits from most significant to least significant, maintaining a state that captures the constraints imposed so far. For this problem the state consists of the current position, a tight flag indicating whether the prefix equals the prefix of the bound, and the current minimum and maximum digits seen. At each step we try all possible next digits (0–9, respecting the tight flag) and update the min/max. When we reach the end of the number, we check whether max‑min ≤ D; if so, the path contributes one valid number. Memoization over the state space (position, tight, min, max) yields a polynomial‑time solution.

The DP runs in O(19·10·10·2) time and space because the maximum number of digits is 19 (for 10^18) and the min/max digits each range from 0 to 9. This is effectively constant time for the problem constraints. The final answer is obtained by computing f(R) – f(L‑1), where f(X) counts valid numbers in [0,X].

Interview Questions on This Problem

Q1How would you modify the digit‑DP solution if the condition changed to "the sum of digits is divisible by 7"?

You would add an extra state variable representing the current sum modulo 7. The transition would update this modulo value with each chosen digit. The DP would then count numbers where the final modulo is 0. The complexity increases by a factor of 7, but remains manageable.

Q2A fintech company asks: "Can you explain why digit‑DP is preferable over brute force for this problem, and what would happen if we tried a BFS over all numbers?"

Digit‑DP exploits the independence of digit positions and uses memoization to avoid exploring the same subproblem multiple times. A BFS over all numbers would still need to generate up to 10^18 nodes, which is infeasible. Even if we pruned based on the property, the branching factor remains high, leading to exponential blow‑up. Digit‑DP reduces the search to a small state space of size O(19·10·10·2).

Q3During an interview, you’re asked to implement the solution in Java. What are the key pitfalls to watch for regarding recursion depth and integer overflow?

Java’s recursion depth is limited; for 19 digits it’s safe, but you should still use iterative DP or increase the stack size if needed. For integer overflow, the count of valid numbers can be up to 10^18, so use long (64‑bit) for all counters and intermediate results. Avoid using int for DP indices or counts.

Examples

Example 1

Input

1 20 1

Output

12

Explanation: All single‑digit numbers (1‑9) are D‑balanced because max‑min = 0 ≤ 1, giving 9 numbers. For two‑digit numbers between 10 and 20 we check the digit spread: 10 → digits {1,0}, spread = 1 (valid) 11 → {1,1}, spread = 0 (valid) 12 → {1,2}, spread = 1 (valid) 13 → spread = 2 (invalid) and all larger numbers up to 20 have spread ≥2. Hence only 10, 11, 12 are valid. Total = 9 + 3 = 12.

Example 2

Input

100 200 0

Output

1

Explanation: D = 0 forces every digit of a valid number to be identical. Between 100 and 200 the only integer whose three decimal digits are all equal is 111. Therefore the count is 1.

Example 3

Input

0 55 1

Output

24

Explanation: Numbers 0‑9 (10 numbers) are always valid because they consist of a single digit. For two‑digit numbers we need |t‑u| ≤ 1 where t is the tens digit and u the units digit. - Tens = 1 → {10,11,12} (3 numbers) - Tens = 2 → {21,22,23} (3 numbers) - Tens = 3 → {32,33,34} (3 numbers) - Tens = 4 → {43,44,45} (3 numbers) - Tens = 5 → {54,55} (2 numbers, 56 exceeds the upper bound 55) Total two‑digit valid numbers = 3+3+3+3+2 = 14. Adding the 10 single‑digit numbers yields 24.

Constraints

  • 0 ≤ L ≤ R ≤ 10^18
  • 0 ≤ D ≤ 9
  • The program must run in O(number of digits × 10) time, i.e., within a few hundred operations per query.

Optimal Approach & Strategy

Use digit‑DP: compute the count of valid numbers up to a bound X in O(19·10·10·2) time by memoizing states (position, tight, min, max). The final answer is f(R) – f(L‑1).

Brute Force Approach

Check every integer from L to R, convert it to a string, find its max and min digits, and count if the difference is ≤ D. This takes O((R-L+1)·log10(R)) time, which is infeasible for large ranges.

Verified Code Solutions

JavaScript Solution
Time: O(19·10·10·2) ≈ O(3800) ≈ O(1)
function solution(nums) {
   let sum = 0;
   for (let num of nums) {
       sum += num;
   }
   let digits = [];
   while (sum > 0) {
       digits.push(sum % 10);
       sum = Math.floor(sum / 10);
   }
   let dp = new Array(digits.length).fill(0).map(() => new Array(digits.length).fill(0));
   for (let i = 0; i < digits.length; i++) {
       dp[i][i] = digits[i];
   }
   for (let length = 2; length <= digits.length; length++) {
       for (let i = 0; i <= digits.length - length; i++) {
           let j = i + length - 1;
           dp[i][j] = Math.max(dp[i][j - 1], dp[i + 1][j]);
       }
   }
   return dp[0][digits.length - 1];
}

Asked in Top Tech Interviews

CapgeminiAmazon

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.