Strobogrammatic Number — LeetCode 246 Python Solution

EasyLeetCode PremiumHash TableTwo PointersString
Problem
#246
Reading time
2 min

The problem

Given a string num which represents an integer, return true if num is a strobogrammatic number. A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).

Example

Input
num = "69"
Output
true

Python solution

Python
class Solution:
    def isStrobogrammatic(self, num: str) -> bool:
        d = [0, 1, -1, -1, -1, -1, 9, -1, 8, 6]
        i, j = 0, len(num) - 1
        while i <= j:
            a, b = int(num[i]), int(num[j])
            if d[a] != b:
                return False
            i, j = i + 1, j - 1
        return True

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 246. Strobogrammatic Number is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 246. Strobogrammatic Number?
LeetCode 246. Strobogrammatic Number is rated Easy on LeetCode.
What is the time complexity of LeetCode 246. Strobogrammatic Number?
The Python solution on this page runs in O(n), where n is the length of the string.
What is the space complexity of LeetCode 246. Strobogrammatic Number?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 246. Strobogrammatic Number cover?
LeetCode 246. Strobogrammatic Number is tagged Hash Table, Two Pointers and String on LeetCode.
Is LeetCode 246. Strobogrammatic Number a premium problem?
Yes. LeetCode 246. Strobogrammatic Number 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