NeetCode #193LC-246EasyTwo Pointers
← Back to All Problems#193 · #246 · Strobogrammatic Number(中心对称数)
📌 Problem Statement & Constraints
A strobogrammatic number is one that looks the same when rotated 180 degrees. The valid digit pairs are 0-0, 1-1, 6-9 and 8-8. Given a string
num representing an integer, return whether it is strobogrammatic. Constraints: 1 <= num.length <= 50; num consists of digits only.💡 Core Algorithmic Approaches
- Two pointers from the ends: each character must map to its rotation partner.
- The mapping is
{'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'}; any other digit makes the number invalid. - Compare
num[i]with the rotation ofnum[j]; on a mismatch, return false. - The middle character (for odd lengths) must map to itself, which the general comparison handles.
💻 Benchmark Python3 Implementation
class Solution:
def isStrobogrammatic(self, num: str) -> bool:
rot = {"0": "0", "1": "1", "6": "9", "8": "8", "9": "6"}
i, j = 0, len(num) - 1
while i <= j:
if num[i] not in rot or num[j] not in rot:
return False
if rot[num[i]] != num[j]: # rotation partner must match
return False
i += 1
j -= 1
return True⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): each character is examined once.
💾 Space Complexity
O(1): the mapping table is fixed.
⚠️ Interview Pitfalls & Follow-ups
- Assuming the rotation is just a reversal: 180-degree rotation reverses the order and maps each digit, so both steps are needed.
- Forgetting that 2, 3, 4, 5, 7 are invalid: their presence makes the answer false.
- Using
i < jas the loop condition: for odd lengths the middle character must still be checked, so the condition isi <= j. - Checking
num[i] == rot[num[j]]: equivalent here because the mapping is an involution, but the formrot[num[i]] == num[j]reads more naturally.