Taro Logo

Count the Number of Powerful Integers

#6 Most AskedHard
0 views
Topics:
StringsDynamic Programming

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 <= 1015
  • 1 <= limit <= 9
  • 1 <= s.length <= floor(log10(finish)) + 1
  • s only consists of numeric digits which are at most limit.
  • s does not have leading zeros.

Solution


Clarifying Questions

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:

  1. What are the constraints and data types for the integers `start`, `finish`, and `limit`, as well as the length of the string `s`?
  2. Can `start` be greater than `finish`, and how should we handle such a case (e.g., return 0)?
  3. Is the suffix `s` guaranteed to be strictly composed of digits, and can `s` represent a number larger than `finish`?
  4. What is the maximum value that `limit` can take? For instance, can `limit` be greater than 9?
  5. Are the bounds `start` and `finish` inclusive in the range check?

Brute Force Solution

Approach

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:

  1. Begin at the starting number and prepare a counter to keep track of how many matching numbers you find.
  2. Look at the current number you are checking and examine its individual digits.
  3. First, verify if the number is too large by checking if any of its individual digits exceed the allowed limit.
  4. Next, check if the number ends with the specific pattern of digits you were given.
  5. If the number successfully meets both the digit limit rule and the ending pattern rule, add one to your successful counter.
  6. Move on to the very next whole number and repeat the exact same checking process.
  7. Continue this process until you have checked every single number up to the ending number, then state your final counted total.

Code Implementation

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_counter

Big(O) Analysis

Time Complexity
O(finish - start) – To count the powerful integers, the algorithm iterates sequentially through every whole number from the starting number to the ending number. For each of these numbers, it must inspect its individual digits to verify that none exceed the allowed limit and that the number ends with the specified suffix pattern. Because the program checks every single integer in this range one by one without skipping, the total operations scale linearly with the difference between the ending number and the starting number. This direct scanning process results in approximately (finish - start) operations, which simplifies to a linear time complexity of O(finish - start).
Space Complexity
O(log_10(R)) – The auxiliary space is primarily driven by the recursion stack used during the digit-by-digit construction and counting process. Since the algorithm evaluates numbers up to the ending limit R, the maximum depth of the recursion corresponds to the number of digits in R. Therefore, the memory consumed by the recursive call stack scales logarithmically with the magnitude of the upper bound, denoted as N.

Optimal Solution

Approach

Instead 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:

  1. First, understand that counting all powerful numbers up to a certain limit can be thought of as building numbers from left to right, like filling out a blank form where some boxes are already locked into place.
  2. Recognize that the tail end of our number is fixed because it always has to finish with our required special ending.
  3. Focus our attention only on the beginning part of the number that we are allowed to freely change.
  4. Go through the number position by position from left to right, deciding what digits we are allowed to place.
  5. At each position, check how many choices we have that will keep our total number smaller than or equal to our target limit.
  6. If a choice forces us to go over our limit, we stop exploring that path because any further additions would also be too big.
  7. Repeat this counting logic for both the upper limit and the lower limit, and find the difference between the two results to get our final answer without ever having to test every single number.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(D) – Here, D represents the number of digits in the upper limit string, which drives the cost because we build the valid numbers position by position from left to right. At each of the D digit positions, we iterate through a constant number of choices from 0 to 9, resulting in roughly 10 operations per digit. This leads to approximately 10 * D operations for the upper limit and the same for the lower limit, which simplifies to O(D) time overall.
Space Complexity
O(L) – The auxiliary space is driven by the recursion stack used when building and counting numbers digit by digit from left to right. Here, N does not represent the numerical magnitude of the upper limit, but rather L, which is the length of the string representation of the target limit. The maximum depth of the recursive calls corresponds to this digit length L, meaning the stack frames scale proportionally with L. Thus, the total extra memory simplifies to Big O of L.

Edge Cases

The suffix s represents a numerical value greater than finish
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Using standard 64-bit integer types like long long in C++ or long in Java prevents overflow issues during range calculations
0/45 completed