Strobogrammatic Number III Problem
Description
LeetCode Problem 248.
Given two strings low and high that represent two integers low and high where low <= high, return the number of strobogrammatic numbers in the range [low, high].
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Example 1:
Input: low = "50", high = "100"
Output: 3
Example 2:
Input: low = "0", high = "0"
Output: 1
Constraints:
1 <= low.length, high.length <= 15lowandhighconsist of only digits.low <= highlowandhighdo not contain any leading zeros except for zero itself.
Solution
Approach: Generate by Length, Then Count
Checking every number between low and high is hopeless when high has 15 digits. But strobogrammatic numbers are rare: there are only about 312,000 of them with at most 15 digits. So we generate them and count the ones in range.
Build them as in Strobogrammatic Number II: a strobogrammatic number of length u is one of length u - 2 wrapped in a matching pair 1...1, 6...9, 8...8, 9...6, or 0...0 (the zero pair is only allowed on inner layers, so the number does not start with 0). The base cases are the empty string for length 0 and "0", "1", "8" for length 1.
A number in [low, high] has between len(low) and len(high) digits, so only those lengths are generated. For each generated string, convert it to an integer and count it if low <= x <= high. With at most 15 digits, the values fit in a 64-bit integer (and exactly in a JavaScript number).
Example 2 is the edge case for zero: "0" is a valid strobogrammatic number of length 1, so the range ["0", "0"] contains one.
Complexity: O(len · 5len/2) time and space, where len is the length of high: there are O(5len/2) candidates of each length, and the longest length dominates.
class Solution:
def strobogrammaticInRange(self, low: str, high: str) -> int:
def build(u: int, n: int) -> List[str]:
"""All strobogrammatic strings of length u inside a number of length n."""
if u == 0:
return [""]
if u == 1:
return ["0", "1", "8"]
ans = []
for inner in build(u - 2, n):
for left, right in ("11", "69", "88", "96"):
ans.append(left + inner + right)
if u != n: # 0...0 only inside: the whole number cannot start with 0
ans.append("0" + inner + "0")
return ans
lo, hi = int(low), int(high)
count = 0
# Only lengths between len(low) and len(high) can be in the range.
for n in range(len(low), len(high) + 1):
for s in build(n, n):
if lo <= int(s) <= hi:
count += 1
return count