Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2999: Count the Number of Powerful Integers

In this guide, we solve Leetcode #2999 Count the Number of Powerful Integers in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

You are given three integers start, finish, and limit. You are also given a 0-indexed string s representing a positive integer.

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Math, String, Dynamic Programming

Intuition

The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.

A carefully chosen DP state captures exactly what we need to build the final answer.

Approach

Define the DP state and recurrence, then compute states in the correct order.

Optionally compress space once the recurrence is clear.

Steps:

  • Choose a DP state definition.
  • Write the recurrence and base cases.
  • Compute states in the correct order.

Example

Input: start = 1, finish = 6000, limit = 4, s = "124" Output: 5 Explanation: The powerful integers in the range [1..6000] are 124, 1124, 2124, 3124, and, 4124. All these integers have each digit <= 4, and "124" as a suffix. Note that 5124 is not a powerful integer because the first digit is 5 which is greater than 4. It can be shown that there are only 5 powerful integers in this range.

Python Solution

class Solution: def numberOfPowerfulInt(self, start: int, finish: int, limit: int, s: str) -> int: @cache def dfs(pos: int, lim: int) -> int: if len(t) < n: return 0 if len(t) - pos == n: return int(s <= t[pos:]) if lim else 1 up = min(int(t[pos]) if lim else 9, limit) ans = 0 for i in range(up + 1): ans += dfs(pos + 1, lim and i == int(t[pos])) return ans n = len(s) t = str(start - 1) a = dfs(0, True) dfs.cache_clear() t = str(finish) b = dfs(0, True) return b - a

Complexity

The time complexity is O(n·m) (typical). The space complexity is O(n·m) or optimized.

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy