#2827

Number of Beautiful Integers in the Range

Hard
MathDynamic ProgrammingDynamic ProgrammingDigit Counting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * d)
Space
O(1)
O(n * d)
💡

Intuition

Time O(n * d)Space O(n * d)

The optimal solution leverages dynamic programming and digit counting to efficiently calculate the number of beautiful integers without checking each number individually. This reduces the time complexity significantly.

⚙️

Algorithm

5 steps
  1. 1Step 1: Define a recursive function that counts beautiful numbers up to a given number n.
  2. 2Step 2: Use memoization to store results for previously computed states to avoid redundant calculations.
  3. 3Step 3: Count the number of even and odd digits dynamically as we build the number.
  4. 4Step 4: Check divisibility by k at each valid number formation.
  5. 5Step 5: Use the helper function to compute f(high) - f(low - 1) to get the final result.
solution.py23 lines
1# Full working Python code
2
3def count_beautiful_integers(low, high, k):
4    def dp(pos, even_count, odd_count, tight, num_str):
5        if pos == len(num_str):
6            return 1 if even_count == odd_count and int(''.join(num_str)) % k == 0 else 0
7        if (pos, even_count, odd_count, tight) in memo:
8            return memo[(pos, even_count, odd_count, tight)]
9        limit = int(num_str[pos]) if tight else 9
10        count = 0
11        for digit in range(0, limit + 1):
12            num_str[pos] = str(digit)
13            count += dp(pos + 1, even_count + (digit % 2 == 0), odd_count + (digit % 2 != 0), tight and (digit == limit), num_str)
14        memo[(pos, even_count, odd_count, tight)] = count
15        return count
16
17    memo = {}
18    num_str_high = list(str(high))
19    num_str_low = list(str(low - 1))
20    return dp(0, 0, 0, True, num_str_high) - dp(0, 0, 0, True, num_str_low)
21
22# Example usage
23print(count_beautiful_integers(10, 20, 3))

Complexity note: The time complexity is O(n * d) where d is the number of digits in the number, as we are exploring all digit combinations. The space complexity is O(n * d) due to memoization.

  • 1Beautiful integers require both even and odd digit counts to be equal.
  • 2Divisibility by k is a crucial constraint that must be checked for each candidate.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.