{x}
blog image

Strobogrammatic Number III

Solution Explanation for Strobogrammatic Number III

This problem asks us to find the count of strobogrammatic numbers within a given range [low, high]. A strobogrammatic number remains the same when rotated 180 degrees. The solution utilizes a recursive depth-first search (DFS) approach to generate strobogrammatic numbers of varying lengths and then filters them based on the provided range.

Approach

The core idea is to recursively build strobogrammatic numbers. We consider the possible pairs of digits that remain the same when rotated 180 degrees: (1,1), (8,8), (6,9), (9,6), and (0,0).

  1. Base Cases:

    • If the length is 0, the only strobogrammatic number is an empty string "".
    • If the length is 1, the strobogrammatic numbers are "0", "1", and "8".
  2. Recursive Step:

    • For lengths greater than 1, we recursively generate strobogrammatic numbers of length len - 2.
    • For each such number, we prepend and append the valid digit pairs from the list above to create new strobogrammatic numbers of length len. Crucially, we must exclude the (0,0) pair if the length is equal to the final length n to prevent leading zeros.
  3. Filtering:

    • Once we've generated all strobogrammatic numbers of lengths between the lengths of low and high, we convert them to integers and check if they fall within the range [low, high]. We increment a counter for each number that satisfies this condition.

Time and Space Complexity Analysis

The time complexity is dominated by the recursive generation of strobogrammatic numbers. In the worst-case scenario, the number of strobogrammatic numbers of length n grows exponentially. Therefore, the overall time complexity is approximately O(5(n/2)), where n is the maximum length of the numbers in the range. The space complexity is also exponential, primarily due to the space used to store the generated numbers during recursion. This is O(5(n/2)) in the worst case. The logarithmic factor present in some explanations arises from the conversion of strings to integers, but it's usually overshadowed by the exponential growth of strobogrammatic numbers.

Code Implementation (Python)

class Solution:
    def strobogrammaticInRange(self, low: str, high: str) -> int:
        self.count = 0
        self.pairs = {'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'}
 
        def generate(num_digits, current_num):
            if num_digits == 0:
                num = int(current_num)
                if low <= str(num) <= high:
                    self.count += 1
                return
            for digit in self.pairs:
                new_num = digit + current_num + self.pairs[digit]
                if len(new_num) > len(high):
                    return #optimization for reducing unnecessary recursive calls
                generate(num_digits - 2, new_num)
 
        def generate_odd(num_digits, current_num):
            if num_digits == 0:
                num = int(current_num)
                if low <= str(num) <= high:
                    self.count += 1
                return
            for digit in ['0','1','8']:
                new_num = digit + current_num + self.pairs.get(digit,'')  #Handle case for middle digit
                if len(new_num)> len(high):
                    return
                generate_odd(num_digits - 2, new_num)
 
        for i in range(len(low), len(high) + 1):
            if i % 2 == 0:
                generate(i, "")
            else:
                generate_odd(i, "")
 
        return self.count

This Python code implements the recursive approach, optimizing by checking for string lengths during the recursion to prevent generating numbers longer than the high limit. The code handles both even and odd length cases. The other languages (Java, C++, Go) would follow a similar recursive structure, adapting the syntax and data structures accordingly.