Problem Description
Given two strings low and high representing the lower and upper bounds (inclusive) of an integer range, count the number of strobogrammatic numbers within that range. A strobogrammatic number appears the same when rotated 180 degrees.
Key Insights
- Use recursion/backtracking to generate potential strobogrammatic numbers for each target length.
- Only the pairs ('0','0'), ('1','1'), ('6','9'), ('8','8'), and ('9','6') can form valid strobogrammatic numbers.
- Handle edge cases: for multi-digit numbers, a number cannot start with '0'.
- Use string comparison to efficiently check whether a generated number falls within the bounds provided.
- Process lengths from the length of low to the length of high.
Space and Time Complexity
Time Complexity: O(5^(N/2)) in the worst-case per length, where N is the target length, summed across all relevant lengths. Space Complexity: O(N) due to the recursion depth and auxiliary storage for each candidate number.
Solution
We apply a recursive DFS/backtracking approach to build numbers from the outside in, ensuring that pairs of digits are strobogrammatic. For even lengths, we fill the number symmetrically, while for odd lengths we choose one of '0', '1', or '8' for the middle digit. Each candidate number is then validated against the input range using string comparison (after ensuring it does not have an invalid leading zero). We sum the counts of valid candidates across all lengths from len(low) to len(high).