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
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
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;
}
}
// Accepted solution for LeetCode #3791: Number of Balanced Integers in a Range
func countBalanced(low int64, high int64) int64 {
if high < 11 {
return 0
}
if low < 11 {
low = 11
}
const base = 90
var num []byte
var f [20][181]int64
var dfs func(pos int, diff int, lim bool) int64
dfs = func(pos int, diff int, lim bool) int64 {
if pos >= len(num) {
if diff == 0 {
return 1
}
return 0
}
if !lim && f[pos][diff+base] != -1 {
return f[pos][diff+base]
}
up := 9
if lim {
up = int(num[pos] - '0')
}
var res int64 = 0
for i := 0; i <= up; i++ {
if pos%2 == 0 {
res += dfs(pos+1, diff+i, lim && i == up)
} else {
res += dfs(pos+1, diff-i, lim && i == up)
}
}
if !lim {
f[pos][diff+base] = res
}
return res
}
num = []byte(fmt.Sprint(low - 1))
for i := range f {
for j := range f[i] {
f[i][j] = -1
}
}
a := dfs(0, 0, true)
num = []byte(fmt.Sprint(high))
for i := range f {
for j := range f[i] {
f[i][j] = -1
}
}
b := dfs(0, 0, true)
return b - a
}
# Accepted solution for LeetCode #3791: Number of Balanced Integers in a Range
class Solution:
def countBalanced(self, low: int, high: int) -> int:
@cache
def dfs(pos: int, diff: int, lim: int) -> int:
if pos >= len(num):
return 1 if diff == 0 else 0
res = 0
up = int(num[pos]) if lim else 9
for i in range(up + 1):
res += dfs(
pos + 1, diff + i * (1 if pos % 2 == 0 else -1), lim and i == up
)
return res
if high < 11:
return 0
low = max(low, 11)
num = str(low - 1)
a = dfs(0, 0, True)
dfs.cache_clear()
num = str(high)
b = dfs(0, 0, True)
return b - a
// Accepted solution for LeetCode #3791: Number of Balanced Integers in a Range
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // 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;
// }
// }
// Accepted solution for LeetCode #3791: Number of Balanced Integers in a Range
function countBalanced(low: number, high: number): number {
if (high < 11) {
return 0;
}
if (low < 11) {
low = 11;
}
const base = 90;
let num: string;
let f: number[][];
function dfs(pos: number, diff: number, lim: boolean): number {
if (pos >= num.length) {
return diff === 0 ? 1 : 0;
}
if (!lim && f[pos][diff + base] !== -1) {
return f[pos][diff + base];
}
const up = lim ? num.charCodeAt(pos) - 48 : 9;
let res = 0;
for (let 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;
}
num = String(low - 1);
f = Array.from({ length: num.length }, () => Array((base << 1) | 1).fill(-1));
const a = dfs(0, 0, true);
num = String(high);
f = Array.from({ length: num.length }, () => Array((base << 1) | 1).fill(-1));
const b = dfs(0, 0, true);
return b - a;
}
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.