Strobogrammatic Number

Check whether a numeric string looks the same when rotated 180°.

Easy
Time O(n) Space O(1)
LeetCode
3 min read
two-pointers string

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
Two pointers converging — at each step, the left digit must rotate to match the right.

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#

Strobogrammatic Number
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;
}
};

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#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.