Strobogrammatic Number II — LeetCode 247 Python Solution
MediumLeetCode PremiumRecursionArrayString
- Problem
- #247
- Pattern
- Hash Map
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given an integer n, return all the strobogrammatic numbers that are of length n. You may return the answer in any order.
Example
- Input
- n = 2
- Output
- ["11","69","88","96"]
Python solution
Python
class Solution:
def findStrobogrammatic(self, n: int) -> List[str]:
def dfs(u):
if u == 0:
return ['']
if u == 1:
return ['0', '1', '8']
ans = []
for v in dfs(u - 2):
for l, r in ('11', '88', '69', '96'):
ans.append(l + v + r)
if u != n:
ans.append('0' + v + '0')
return ans
return dfs(n)Complexity
| Measure | Complexity |
|---|---|
| Time | O(2^{n+2}) |
| Space | O(1) to O(n) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 247. Strobogrammatic Number II is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 247. Strobogrammatic Number II?
- LeetCode 247. Strobogrammatic Number II is rated Medium on LeetCode.
- What topics does LeetCode 247. Strobogrammatic Number II cover?
- LeetCode 247. Strobogrammatic Number II is tagged Recursion, Array and String on LeetCode.
- Is LeetCode 247. Strobogrammatic Number II a premium problem?
- Yes. LeetCode 247. Strobogrammatic Number II is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.