LeetCode #3791 — HARD

Number of Balanced Integers in a Range

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 low and high.

An integer is called balanced if it satisfies both of the following conditions:

  • It contains at least two digits.
  • The sum of digits at even positions is equal to the sum of digits at odd positions (the leftmost digit has position 1).

Return an integer representing the number of balanced integers in the range [low, high] (both inclusive).

Example 1:

Input: low = 1, high = 100

Output: 9

Explanation:

The 9 balanced numbers between 1 and 100 are 11, 22, 33, 44, 55, 66, 77, 88, and 99.

Example 2:

Input: low = 120, high = 129

Output: 1

Explanation:

Only 121 is balanced because the sum of digits at even and odd positions are both 2.

Example 3:

Input: low = 1234, high = 1234

Output: 0

Explanation:

1234 is not balanced because the sum of digits at odd positions (1 + 3 = 4) does not equal the sum at even positions (2 + 4 = 6).

Constraints:

  • 1 <= low <= high <= 1015
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 low and high. An integer is called balanced if it satisfies both of the following conditions: It contains at least two digits. The sum of digits at even positions is equal to the sum of digits at odd positions (the leftmost digit has position 1). Return an integer representing the number of balanced integers in the range [low, high] (both inclusive).

Baseline thinking

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

Pattern signal: Dynamic Programming

Example 1

1
100

Example 2

120
129

Example 3

1234
1234
Step 02

Core Insight

What unlocks the optimal approach

  • Use digit dynamic programming.
  • Let <code>f(x)</code> be the number of balanced integers in <code>[1, x]</code>; the answer is <code>f(high) - f(low - 1)</code>.
  • Track the difference <code>sum(odd positions) - sum(even positions)</code> while building from the most significant digit, and require it to be zero at the end.
  • Ignore leading zeros during transitions.
  • Enforce the length constraint by counting only when at least two digits have been placed.
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 #3791: Number of Balanced Integers in a Range
class Solution {
    private char[] num;
    private Long[][] f;
    private final int base = 90;

    public long countBalanced(long low, long high) {
        if (high < 11) {
            return 0;
        }
        low = Math.max(low, 11);
        num = String.valueOf(low - 1).toCharArray();
        f = new Long[num.length][base << 1 | 1];
        long a = dfs(0, 0, true);
        num = String.valueOf(high).toCharArray();
        f = new Long[num.length][base << 1 | 1];
        long b = dfs(0, 0, true);
        return b - a;
    }

    private long dfs(int pos, int diff, boolean lim) {
        if (pos >= num.length) {
            return diff == 0 ? 1 : 0;
        }
        if (!lim && f[pos][diff + base] != null) {
            return f[pos][diff + base];
        }
        int up = lim ? num[pos] - '0' : 9;
        long res = 0;
        for (int i = 0; i <= up; ++i) {
            res += dfs(pos + 1, diff + i * (pos % 2 == 0 ? 1 : -1), lim && i == up);
        }
        if (!lim) {
            f[pos][diff + base] = res;
        }
        return res;
    }
}
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(log^2 M × D^2)
Space
O(log^2 M × D)

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.

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.