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.
Example 1:
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.
Example 2:
Input: start = 15, finish = 215, limit = 6, s = "10" Output: 2 Explanation: The powerful integers in the range [15..215] are 110 and 210. All these integers have each digit <= 6, and "10" as a suffix. It can be shown that there are only 2 powerful integers in this range.
Example 3:
Input: start = 1000, finish = 2000, limit = 4, s = "3000" Output: 0 Explanation: All integers in the range [1000..2000] are smaller than 3000, hence "3000" cannot be a suffix of any integer in this range.
Constraints:
1 <= start <= finish <= 10151 <= limit <= 91 <= s.length <= floor(log10(finish)) + 1s only consists of numeric digits which are at most limit.s does not have leading zeros.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you are given a starting number, an ending number, a special ending pattern of digits, and a limit for the digits. The brute force strategy involves checking every single whole number from the starting number all the way up to the ending number to see which ones qualify.
Here's how the algorithm would work step-by-step:
def count_powerful_integers(start_number, finish_number, ending_pattern, digit_limit):
matching_counter = 0
# Iterate through every integer from the start up to the finish to evaluate it
for current_number in range(start_number, finish_number + 1):
string_representation = str(current_number)
digit_exceeded = False
for digit_character in string_representation:
if int(digit_character) > digit_limit:
digit_exceeded = True
break
# Skip numbers with digits over the limit to adhere to problem constraints
if digit_exceeded:
continue
# Verify if the string ends with the required pattern before counting it
if string_representation.endswith(ending_pattern):
matching_counter += 1
return matching_counterInstead of checking every single number one by one, the optimal approach uses a clever counting technique similar to building numbers digit by digit. It calculates how many valid numbers exist up to the upper limit and subtracts the invalid ones by checking how many valid numbers exist up to the lower limit.
Here's how the algorithm would work step-by-step:
class Solution:
def numberOfPowerfulInt(self, start_limit: int, finish_limit: int, maximum_digit: int, target_suffix: str) -> int:
def count_powerful_up_to(target_limit: str) -> int:
if len(target_limit) < len(target_suffix):
return 0
# We compute valid numbers recursively using digit DP, matching the prefix length.
memoization_cache = {}
def depth_first_search(index_position: int, is_tight: bool) -> int:
if index_position == len(target_limit):
return 1
state_tuple = (index_position, is_tight)
if state_tuple in memoization_cache:
return memoization_cache[state_tuple]
limit_character = target_limit[index_position]
upper_bound = int(limit_character) if is_tight else maximum_digit
total_valid_counts = 0
prefix_length = len(target_limit) - len(target_suffix)
if index_position >= prefix_length:
required_digit = int(target_suffix[index_position - prefix_length])
if required_digit <= upper_bound:
next_tight = is_tight and (required_digit == int(limit_character))
total_valid_counts += depth_first_search(index_position + 1, next_tight)
else:
# We iterate through all allowed digits to build valid prefixes branch by branch.
for current_digit in range(min(maximum_digit, upper_bound) + 1):
next_tight = is_tight and (current_digit == int(limit_character))
total_valid_counts += depth_first_search(index_position + 1, next_tight)
memoization_cache[state_tuple] = total_valid_counts
return total_valid_counts
return depth_first_search(0, True)
upper_count = count_powerful_up_to(str(finish_limit))
# Subtracting valid numbers below start limit isolates the exact range requested.
lower_count = count_powerful_up_to(str(start_limit - 1))
return upper_count - lower_count| Case | How to Handle |
|---|---|
| The suffix s represents a numerical value greater than finish | The algorithm should immediately return zero because no integer in the range can end with a suffix larger than the upper bound |
| The suffix s has a length greater than the string representation of finish | The digit DP or mathematical bound check will naturally evaluate to zero since a number cannot be smaller than its suffix length |
| The limit is zero | All prefix digits must be strictly zero, meaning only the suffix itself potentially combined with leading zeros can form valid powerful integers |
| The limit is nine | Any digit from zero through nine is valid in the prefix, transforming the problem into simply counting numbers ending with suffix s up to finish |
| Start and finish are identical and form a powerful integer | The range counting logic via count up to finish minus count up to start minus one correctly evaluates to a count of one |
| Maximum possible values for finish up to 10 to the 15th power | Using digit dynamic programming with memoization ensures the solution runs well within time limits without incurring exponential time complexity |
| Prefix digits can be constrained such that no numbers meet the limit criteria | The recursive digit builder will return zero when constrained by the limit, preventing invalid combinations from being counted |
| Inputs involve very large numbers requiring 64-bit integer types | Using standard 64-bit integer types like long long in C++ or long in Java prevents overflow issues during range calculations |