Count the Number of Powerful Integers - Problem

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

A positive integer x is called powerful if it ends with s (in other words, s is a suffix of x) and each digit in x is at most limit.

Return the total number of powerful integers in the range [start, finish].

A string x is a suffix of a string y if and only if x is a substring of y that starts from some index (including 0) in y and extends to the index y.length - 1. For example, 25 is a suffix of 5125 whereas 512 is not.

Input & Output

Example 1 — Basic Case
$ Input: start = 1, finish = 15, limit = 2, s = "2"
Output: 2
💡 Note: The powerful integers are 2 and 12. Both end with "2" and have all digits ≤ 2. Numbers like 22 are > 15, and 32 has digit 3 > 2.
Example 2 — No Valid Numbers
$ Input: start = 1, finish = 15, limit = 1, s = "2"
Output: 0
💡 Note: No numbers ending with "2" can have all digits ≤ 1, since "2" itself contains digit 2 > 1.
Example 3 — Larger Suffix
$ Input: start = 1000, finish = 2000, limit = 4, s = "124"
Output: 1
💡 Note: Only 1124 is in range [1000,2000], ends with "124", and has all digits ≤ 4.

Constraints

  • 1 ≤ start ≤ finish ≤ 1015
  • 1 ≤ limit ≤ 9
  • 1 ≤ s.length ≤ floor(log10(finish)) + 1
  • s only contains digits, and doesn't have leading zeros

Visualization

Tap to expand
Count the Number of Powerful Integers INPUT Range [start, finish] 1 15 Numbers in range: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 start = 1 finish = 15 limit = 2 s = "2" Green = Powerful integers (ends with "2", digits <= 2) ALGORITHM STEPS (DP) 1 Define Powerful x ends with s="2" all digits <= limit=2 2 Count Function count(n) = powerful nums in range [1, n] 3 Digit DP Build nums digit by digit Track tight bound state 4 Calculate Result count(15) - count(0) Checking Process: 2: ends with "2", digit=2 OK 12: ends with "2", 1<=2 OK 22: ends with "2", but 22>15 Result: {2, 12} = 2 nums FINAL RESULT Powerful Integers Found: 2 12 Verification: 2: suffix="2" OK, digit 2<=2 OK 12: suffix="2" OK, 1,2<=2 OK OUTPUT 2 Total powerful integers: 2 OK - Answer verified! Key Insight: Digit DP allows us to count numbers with specific digit constraints efficiently. We iterate through each digit position, ensuring the suffix matches s="2" and all digits are <= limit=2. The formula count(finish) - count(start-1) gives us the count in range [start, finish]. Time: O(n * limit) TutorialsPoint - Count the Number of Powerful Integers | DP Approach
Asked in
Google 25 Meta 18 Amazon 15
12.5K Views
Medium Frequency
~35 min Avg. Time
340 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen