Strobogrammatic Number

easy string two pointers hash map

Problem

A strobogrammatic number looks the same when rotated 180°. Given a string num, return true if it is strobogrammatic.

Inputnum = "69"
Outputtrue
6 rotated maps to 9 and 9 rotates to 6 — together they read 69 again.

def 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;
}
Time: O(n) Space: O(1)