Strobogrammatic Number
Problem
A strobogrammatic number looks the same when rotated 180°. Given a string num, return true if it is strobogrammatic.
num = "69"truedef is_strobogrammatic(num):
pairs = {"0":"0","1":"1","6":"9","8":"8","9":"6"}
l, r = 0, len(num) - 1
while l <= r:
if num[l] not in pairs or pairs[num[l]] != num[r]:
return False
l += 1; r -= 1
return True
function isStrobogrammatic(num) {
const pairs = { "0":"0", "1":"1", "6":"9", "8":"8", "9":"6" };
let l = 0, r = num.length - 1;
while (l <= r) {
if (!(num[l] in pairs) || pairs[num[l]] !== num[r]) return false;
l++; r--;
}
return true;
}
class Solution {
public boolean isStrobogrammatic(String num) {
Map p = Map.of('0','0','1','1','6','9','8','8','9','6');
int l = 0, r = num.length() - 1;
while (l <= r) {
if (!p.containsKey(num.charAt(l)) || p.get(num.charAt(l)) != num.charAt(r)) return false;
l++; r--;
}
return true;
}
}
bool isStrobogrammatic(string num) {
unordered_map p = {{'0','0'},{'1','1'},{'6','9'},{'8','8'},{'9','6'}};
int l = 0, r = (int)num.size() - 1;
while (l <= r) {
if (!p.count(num[l]) || p[num[l]] != num[r]) return false;
l++; r--;
}
return true;
}
Explanation
A number is strobogrammatic if it reads the same after a 180° spin. Only a few digits even survive that spin, so the whole check comes down to comparing the outside-in pairs against a tiny lookup table.
We build a map pairs of what each digit becomes when flipped: 0→0, 1→1, 6→9, 8→8, 9→6. Any digit not in this map (like 2 or 3) instantly fails.
Then two pointers, l at the start and r at the end, walk toward the middle. For each step we check that pairs[num[l]] equals num[r]. This works because when you rotate the whole number, the leftmost digit lands on the right, so the left digit's flipped form must match the right digit.
If any pair fails we return false right away; if the pointers cross with no problems, the number is strobogrammatic.
Example: "69". Left is 6, which flips to 9, and the right is 9 — they match. The pointers cross, so the answer is true.