Strobogrammatic Number III — LeetCode 248 Python Solution
- Problem
- #248
- Pattern
- Hash Map
- Reading time
- 4 min
- Source
- leetcode.com
The problem
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
- Input
- low = "50", high = "100"
- Output
- 3
Python solution
class Solution:
def strobogrammaticInRange(self, low: str, high: str) -> int:
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
a, b = len(low), len(high)
low, high = int(low), int(high)
ans = 0
for n in range(a, b + 1):
for s in dfs(n):
if low <= int(s) <= high:
ans += 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(2^{n+2} \times \log n) |
| 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 248. Strobogrammatic Number III 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 248. Strobogrammatic Number III?
- LeetCode 248. Strobogrammatic Number III is rated Hard on LeetCode.
- What topics does LeetCode 248. Strobogrammatic Number III cover?
- LeetCode 248. Strobogrammatic Number III is tagged Recursion, Array and String on LeetCode.
- Is LeetCode 248. Strobogrammatic Number III a premium problem?
- Yes. LeetCode 248. Strobogrammatic Number III is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.