Strobogrammatic Number II Problem
Description
LeetCode Problem 247.
Given an integer n, return all the strobogrammatic numbers that are of length n. You may return the answer in any order.
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Example 1:
Input: n = 2
Output: ["11","69","88","96"]
Example 2:
Input: n = 1
Output: ["0","1","8"]
Constraints:
1 <= n <= 14
Solution
Approach: Build From the Middle Out
A strobogrammatic number of length u is a strobogrammatic number of length u - 2 with a matching pair of digits around it: 1...1, 6...9, 8...8, 9...6 or 0...0. So we can build all of them from the inside:
- Length
0: just the empty string. - Length
1:"0","1"and"8". - Length
u >= 2: for each string of lengthu - 2, wrap it in each of the pairs.
The catch is the pair 0...0. A number cannot start with 0, so the outermost pair (when u == n) must not be 0...0. Inner layers can use it, which is how we get numbers like "1001" and "609". The only number that may be "0" itself is the length-1 case.
Recursion on u - 2 reaches length 0 for even n and length 1 for odd n, so both base cases are needed.
Complexity: O(n · 5n/2) time and space: there are O(5n/2) results, each of length n.
class Solution:
def findStrobogrammatic(self, n: int) -> List[str]:
def build(u: int) -> List[str]:
"""All strobogrammatic strings of length u (inner ones may start with 0)."""
if u == 0:
return [""]
if u == 1:
return ["0", "1", "8"]
ans = []
for inner in build(u - 2):
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
return build(n)