Strobogrammatic Number
Check whether a numeric string looks the same when rotated 180°.
Problem#
A strobogrammatic number reads the same when rotated 180°. Return true iff the input numeric string is strobogrammatic.
The valid rotations are: 0↔0, 1↔1, 8↔8, 6↔9, 9↔6. All other digits are invalid.
Examples#
"69"→true"88"→true"962"→false"1"→true
Constraints#
1 <= num.length <= 50, digits only, no leading zeros (except"0"itself).
Hints#
Hint 1
Approach#
Static lookup table mapping each valid digit to its 180° partner. Two pointers walk inward; each pair must satisfy partner[left] == right. Anything outside the table is automatically invalid.
Solution#
class Solution {public: bool isStrobogrammatic(string num) { unordered_map<char,char> rot = {{'0','0'},{'1','1'},{'8','8'},{'6','9'},{'9','6'}}; int l = 0, r = num.size() - 1; while (l <= r) { auto it = rot.find(num[l]); if (it == rot.end() || it->second != num[r]) return false; ++l; --r; } return true; }};func isStrobogrammatic(num string) bool { rot := map[byte]byte{'0': '0', '1': '1', '8': '8', '6': '9', '9': '6'} l, r := 0, len(num)-1 for l <= r { p, ok := rot[num[l]] if !ok || p != num[r] { return false } l++ r-- } return true}class Solution: def isStrobogrammatic(self, num: str) -> bool: rot = {'0': '0', '1': '1', '8': '8', '6': '9', '9': '6'} l, r = 0, len(num) - 1 while l <= r: if num[l] not in rot or rot[num[l]] != num[r]: return False l += 1 r -= 1 return Truefunction isStrobogrammatic(num) { const rot = { '0': '0', '1': '1', '8': '8', '6': '9', '9': '6' }; let l = 0, r = num.length - 1; while (l <= r) { if (!(num[l] in rot) || rot[num[l]] !== num[r]) return false; l++; r--; } return true;}class Solution { public boolean isStrobogrammatic(String num) { Map<Character, Character> rot = new HashMap<>(); rot.put('0', '0'); rot.put('1', '1'); rot.put('8', '8'); rot.put('6', '9'); rot.put('9', '6'); int l = 0, r = num.length() - 1; while (l <= r) { Character p = rot.get(num.charAt(l)); if (p == null || p != num.charAt(r)) return false; l++; r--; } return true; }}function isStrobogrammatic(num: string): boolean { const rot: Record<string, string> = { '0': '0', '1': '1', '8': '8', '6': '9', '9': '6' }; let l = 0, r = num.length - 1; while (l <= r) { if (!(num[l] in rot) || rot[num[l]] !== num[r]) return false; l++; r--; } return true;}Editorial#
The lookup table makes the algorithm declarative: anything not in the table fails the first lookup, and any mismatched pair fails the comparison. The l <= r (not <) condition handles odd-length strings — the middle digit must rotate to itself, which only 0, 1, and 8 do; the table correctly enforces that.
Complexity#
- Time: O(n).
- Space: O(1) (table is constant size).
Concept revision#
Related#