Strobogrammatic Number III — LeetCode 248 Python Solution

HardLeetCode PremiumRecursionArrayString
Problem
#248
Pattern
Hash Map
Reading time
4 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO(2^{n+2} \times \log n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview