Skip to main content

246. Strobogrammatic Number

easy

Decide whether a number reads the same after being rotated 180 degrees. A two-pointer scan with a tiny lookup map — clean and elegant.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given a string num which represents an integer, return true if num is a strobogrammatic number. A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).

Constraints

  • 1 <= num.length <= 50
  • num consists of only digits.
  • num does not contain any leading zeros except for zero itself.

Examples

Example 1

Input
num = "69"
Output
true

Example 2

Input
num = "88"
Output
true

Example 3

Input
num = "962"
Output
false

Example 4

Input
num = "1"
Output
true

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Hints

Progressive — try the first before opening the next.

Hint 1

Only 5 digits are valid when rotated 180 degrees: 0 -> 0, 1 -> 1, 6 -> 9, 8 -> 8, 9 -> 6. Everything else fails.

Hint 2

Walk two pointers from the ends inward. The left digit must rotate to the right digit.

Hint 3

If at any pair num[left] doesn't rotate to num[right], return false.

Hint 4

For odd-length strings, the middle digit rotates to itself — so it must be 0, 1, or 8.

Solution approach

Reveal approach

Lookup map: {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'}. Two pointers left = 0, right = n - 1. While left <= right: if num[left] not in the map, return false; if map[num[left]] != num[right], return false. Then left++, right--. Return true. The left <= right (rather than <) condition handles odd-length strings: when left == right (middle digit), the digit must rotate to itself — only 0, 1, 8 satisfy that, and the map check enforces it. O(n) time, O(1) space (the map is constant size).

Complexity

Time
O(n)
Space
O(1)

Related patterns

  • math
  • two-pointers
  • hash-map

Related problems

Asked at

Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).

  • Google
  • Microsoft

Practice these live with InterviewChamp.AI

Drill Strobogrammatic Number and Math problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →