You are given two positive integers, l and r. A positive integer is called beautiful if the product of its digits is divisible by the sum of its digits.
Return the count of beautiful numbers between l and r, inclusive.
Example 1:
Input:l = 10, r = 20
Output:2
Explanation:
The beautiful numbers in the range are 10 and 20.
Example 2:
Input:l = 1, r = 15
Output:10
Explanation:
The beautiful numbers in the range are 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10.
Problem summary: You are given two positive integers, l and r. A positive integer is called beautiful if the product of its digits is divisible by the sum of its digits. Return the count of beautiful numbers between l and r, inclusive.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming
Example 1
10
20
Example 2
1
15
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
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 #3490: Count Beautiful Numbers
class Solution {
public int beautifulNumbers(int l, int r) {
return count(String.valueOf(r), 0, /*tight=*/true, /*isLeadingZero=*/true,
/*hasZero=*/false, /*sum=*/0, /*prod=*/1, new HashMap<>()) -
count(String.valueOf(l - 1), 0, /*tight=*/true, /*isLeadingZero=*/true,
/*hasZero=*/false, /*sum=*/0, /*prod=*/1, new HashMap<>());
}
private int count(final String s, int i, boolean tight, boolean isLeadingZero, boolean hasZero,
int sum, int prod, Map<String, Integer> mem) {
if (i == s.length()) {
if (isLeadingZero)
return 0;
return (hasZero || prod % sum == 0) ? 1 : 0;
}
final String key = hash(i, tight, isLeadingZero, hasZero, sum, prod);
if (!isLeadingZero && hasZero && !tight) {
final int val = (int) Math.pow(10, s.length() - i);
mem.put(key, val);
return val;
}
if (mem.containsKey(key))
return mem.get(key);
int res = 0;
final int maxDigit = tight ? s.charAt(i) - '0' : 9;
for (int d = 0; d <= maxDigit; ++d) {
final boolean nextTight = tight && (d == maxDigit);
final boolean nextIsLeadingZero = isLeadingZero && d == 0;
final boolean nextHasZero = !nextIsLeadingZero && d == 0;
final int nextProd = nextIsLeadingZero ? 1 : prod * d;
res += count(s, i + 1, nextTight, nextIsLeadingZero, nextHasZero, sum + d, nextProd, mem);
}
mem.put(key, res);
return res;
}
private String hash(int i, boolean tight, boolean isLeadingZero, boolean hasZero, int sum,
int prod) {
return i + "_" + (tight ? "1" : "0") + "_" + (isLeadingZero ? "1" : "0") + "_" +
(hasZero ? "1" : "0") + "_" + sum + "_" + prod;
}
}
// Accepted solution for LeetCode #3490: Count Beautiful Numbers
package main
import (
"slices"
"strconv"
)
// https://space.bilibili.com/206214
type tuple struct{ i, m, s int }
var memo = map[tuple]int{}
var high []byte
func dfs(i, m, s int, isLimit, isNum bool) (res int) {
if i < 0 {
if s == 0 || m%s > 0 {
return 0
}
return 1
}
if !isLimit && isNum {
t := tuple{i, m, s}
if v, ok := memo[t]; ok {
return v
}
defer func() { memo[t] = res }()
}
hi := 9
if isLimit {
hi = int(high[i] - '0')
}
d := 0
if !isNum {
res = dfs(i-1, m, s, false, false) // 什么也不填
d = 1
}
// 枚举填数字 d
for ; d <= hi; d++ {
res += dfs(i-1, m*d, s+d, isLimit && d == hi, true)
}
return
}
func calc(r int) int {
high = []byte(strconv.Itoa(r))
slices.Reverse(high)
return dfs(len(high)-1, 1, 0, true, false)
}
func beautifulNumbers(l, r int) int {
return calc(r) - calc(l-1)
}
# Accepted solution for LeetCode #3490: Count Beautiful Numbers
class Solution:
def beautifulNumbers(self, l: int, r: int) -> int:
@functools.lru_cache(None)
def dp(
s: str,
i: int,
tight: bool,
isLeadingZero: bool,
hasZero: bool,
sum: int,
prod: int,
) -> int:
if i == len(s):
if isLeadingZero:
return 0
return 1 if hasZero or prod % sum == 0 else 0
if not isLeadingZero and hasZero and not tight:
return 10 ** (len(s) - i)
res = 0
maxDigit = int(s[i]) if tight else 9
for d in range(maxDigit + 1):
nextTight = tight and (d == maxDigit)
nextIsLeadingZero = isLeadingZero and d == 0
nextHasZero = not nextIsLeadingZero and d == 0
nextProd = 1 if nextIsLeadingZero else prod * d
res += dp(s, i + 1, nextTight, nextIsLeadingZero,
nextHasZero, sum + d, nextProd)
return res
return (dp(str(r), 0, tight=True, isLeadingZero=True, hasZero=False, sum=0, prod=1) -
dp(str(l - 1), 0, tight=True, isLeadingZero=True, hasZero=False, sum=0, prod=1))
// Accepted solution for LeetCode #3490: Count Beautiful Numbers
// 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 #3490: Count Beautiful Numbers
// class Solution {
// public int beautifulNumbers(int l, int r) {
// return count(String.valueOf(r), 0, /*tight=*/true, /*isLeadingZero=*/true,
// /*hasZero=*/false, /*sum=*/0, /*prod=*/1, new HashMap<>()) -
// count(String.valueOf(l - 1), 0, /*tight=*/true, /*isLeadingZero=*/true,
// /*hasZero=*/false, /*sum=*/0, /*prod=*/1, new HashMap<>());
// }
//
// private int count(final String s, int i, boolean tight, boolean isLeadingZero, boolean hasZero,
// int sum, int prod, Map<String, Integer> mem) {
// if (i == s.length()) {
// if (isLeadingZero)
// return 0;
// return (hasZero || prod % sum == 0) ? 1 : 0;
// }
// final String key = hash(i, tight, isLeadingZero, hasZero, sum, prod);
// if (!isLeadingZero && hasZero && !tight) {
// final int val = (int) Math.pow(10, s.length() - i);
// mem.put(key, val);
// return val;
// }
// if (mem.containsKey(key))
// return mem.get(key);
//
// int res = 0;
// final int maxDigit = tight ? s.charAt(i) - '0' : 9;
//
// for (int d = 0; d <= maxDigit; ++d) {
// final boolean nextTight = tight && (d == maxDigit);
// final boolean nextIsLeadingZero = isLeadingZero && d == 0;
// final boolean nextHasZero = !nextIsLeadingZero && d == 0;
// final int nextProd = nextIsLeadingZero ? 1 : prod * d;
// res += count(s, i + 1, nextTight, nextIsLeadingZero, nextHasZero, sum + d, nextProd, mem);
// }
//
// mem.put(key, res);
// return res;
// }
//
// private String hash(int i, boolean tight, boolean isLeadingZero, boolean hasZero, int sum,
// int prod) {
// return i + "_" + (tight ? "1" : "0") + "_" + (isLeadingZero ? "1" : "0") + "_" +
// (hasZero ? "1" : "0") + "_" + sum + "_" + prod;
// }
// }
// Accepted solution for LeetCode #3490: Count Beautiful Numbers
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #3490: Count Beautiful Numbers
// class Solution {
// public int beautifulNumbers(int l, int r) {
// return count(String.valueOf(r), 0, /*tight=*/true, /*isLeadingZero=*/true,
// /*hasZero=*/false, /*sum=*/0, /*prod=*/1, new HashMap<>()) -
// count(String.valueOf(l - 1), 0, /*tight=*/true, /*isLeadingZero=*/true,
// /*hasZero=*/false, /*sum=*/0, /*prod=*/1, new HashMap<>());
// }
//
// private int count(final String s, int i, boolean tight, boolean isLeadingZero, boolean hasZero,
// int sum, int prod, Map<String, Integer> mem) {
// if (i == s.length()) {
// if (isLeadingZero)
// return 0;
// return (hasZero || prod % sum == 0) ? 1 : 0;
// }
// final String key = hash(i, tight, isLeadingZero, hasZero, sum, prod);
// if (!isLeadingZero && hasZero && !tight) {
// final int val = (int) Math.pow(10, s.length() - i);
// mem.put(key, val);
// return val;
// }
// if (mem.containsKey(key))
// return mem.get(key);
//
// int res = 0;
// final int maxDigit = tight ? s.charAt(i) - '0' : 9;
//
// for (int d = 0; d <= maxDigit; ++d) {
// final boolean nextTight = tight && (d == maxDigit);
// final boolean nextIsLeadingZero = isLeadingZero && d == 0;
// final boolean nextHasZero = !nextIsLeadingZero && d == 0;
// final int nextProd = nextIsLeadingZero ? 1 : prod * d;
// res += count(s, i + 1, nextTight, nextIsLeadingZero, nextHasZero, sum + d, nextProd, mem);
// }
//
// mem.put(key, res);
// return res;
// }
//
// private String hash(int i, boolean tight, boolean isLeadingZero, boolean hasZero, int sum,
// int prod) {
// return i + "_" + (tight ? "1" : "0") + "_" + (isLeadingZero ? "1" : "0") + "_" +
// (hasZero ? "1" : "0") + "_" + sum + "_" + prod;
// }
// }
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.
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.