#2999

Count the Number of Powerful Integers

Hard
MathStringDynamic ProgrammingDigit Dynamic ProgrammingBacktracking
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n * m)
O(d^2)
Space
O(1)
O(d)
💡

Intuition

Time O(d^2)Space O(d)

The optimal solution uses a digit dynamic programming (DP) approach to efficiently count the powerful integers without checking each one individually. This method leverages the properties of numbers and their digits to reduce the search space.

⚙️

Algorithm

3 steps
  1. 1Step 1: Define a DP function that counts valid integers up to a given number x.
  2. 2Step 2: Use recursion with memoization to explore digit placements while ensuring they meet the suffix and digit limit conditions.
  3. 3Step 3: Calculate the count of powerful integers in the range [1, finish] and subtract those in [1, start-1].
solution.py11 lines
1def countPowerfulIntegers(start, finish, limit, s):
2    def dp(pos, is_tight, has_suffix):
3        if pos == len(s):
4            return 1 if has_suffix else 0
5        count = 0
6        limit_digit = int(s[pos]) if is_tight else limit
7        for digit in range(0, limit_digit + 1):
8            count += dp(pos + 1, is_tight and (digit == limit_digit), has_suffix or (pos == len(s) - 1 and digit == int(s[-1])))
9        return count
10    return dp(0, True, False)
11    total_count = countPowerfulIntegers(finish) - countPowerfulIntegers(start - 1)

Complexity note: The time complexity is O(d^2) where d is the number of digits in the number being processed. This is efficient compared to the brute force method.

  • 1Powerful integers must end with the specified suffix.
  • 2Each digit must be within the specified limit.

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