LeetCode #3490 — HARD

Count Beautiful Numbers

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

Constraints:

  • 1 <= l <= r < 109
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 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

  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 #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.