Strobogrammatic Number

Check whether a number still reads the same after you turn it upside down.

Some numbers read the same after you turn them upside down, that is, rotate them by 180 degrees. Such a number is called strobogrammatic. Given a number as a string num, return true if it is strobogrammatic and false if it is not.

Example 1
Input: num = "69"
Output: true
Example 2
Input: num = "88"
Output: true
Example 3
Input: num = "962"
Output: false
Solution

The Idea

Write 69 on a sticky note and turn the note upside down. The 6 becomes a 9 and the 9 becomes a 6, and they also swap places. The 9 that sat on the right is now on the left, as a 6, so the note still reads 69. A note with 88 reads 88 again. With 962, the 2 at the end turns into a shape that is no digit at all.

So turning a number does two things at once: every digit changes into its upside-down form, and the order of the digits is reversed. Which digits have an upside-down form? The top of the picture, labelled "each digit turned upside down", shows them.

Upside down, 0, 1 and 8 stay the same, 6 becomes 9 and 9 becomes 6, while 2, 3, 4, 5 and 7 are no digit. In 69 the left digit 6 turns into 9, which matches the right digit. In 962 the left digit 9 turns into 6, but the right digit is 2.

The blue boxes show that 0, 1 and 8 stay the same, 6 becomes 9 and 9 becomes 6. The five boxes on the right, with the grey digits 2, 3, 4, 5 and 7, are marked "no digit upside down". A number that contains any of them can never be strobogrammatic.

Now the reversed order. After the turn, the first place shows the last digit, upside down, and that must equal the first digit we started with. The second place shows the second-to-last digit, upside down, and so on. Do we have to build the turned number to check this?

No. Because 6 and 9 swap and the other three stay put, we can just as well turn the left digit and compare it with the right one. Look at the row labelled "69": the left digit (lo) is 6, upside down it is 9, and the right digit (hi) is 9, a match. In the row labelled "962", the left digit 9 turns into 6, but the right digit is 2, so 962 is not strobogrammatic.

So a number is strobogrammatic when its digits pair up from the outside in: the first with the last, the second with the second-to-last, and in each pair the left digit turned upside down is the right digit.

Solution Approach

Four decisions remain: how to look up a digit's upside-down form, how to walk the pairs, what to do with a middle digit that has no partner, and whether to treat the input as a number at all.

Looking up a digit upside down

Where does the code keep the blue boxes from the top of the picture? Two short strings, lined up position by position, are enough: "01689" holds the digits that turn, and "01986" holds what each one becomes. The 6 sits at position 2 of the first string, and position 2 of the second string holds 9.

Finding a digit's position with indexOf also catches the grey digits. A 2, 3, 4, 5 or 7 is not in "01689", so indexOf returns -1, and so does any other character, such as a minus sign.

Walking the pairs from both ends

How do we visit the pairs? Keep two positions, lo at the first digit and hi at the last, as in the picture. Check the pair, then move lo one place right and hi one place left. The first pair that fails ends the search with false.

Is it enough to check that every digit is one of 0, 1, 6, 8 and 9? No. Upside down, 66 reads 99 and 16 reads 91, so each digit has to be compared with the digit opposite it, not only checked on its own.

A simpler way also works: walk the string from the last digit to the first, write down each digit's upside-down form, and compare the new string with num. It is correct, but it always builds a second string as long as num, even when the first pair already fails. The walk from both ends needs no second string.

The middle digit

What happens in "818", which has an odd number of digits? The outer 8s pair up, and then lo and hi both land on the 1 in position 1. That digit sits opposite itself, so it must look the same upside down: 0, 1 or 8. A 6 in the middle turns into 9 and fails.

The loop runs while lo <= hi, so it still checks the position where the two meet. With an even number of digits, as in "69", they cross without meeting and no digit is left over.

Keeping the input a string

Should the code turn num into a long and work on its digits with % 10? The largest long, 9,223,372,036,854,775,807, has 19 digits, so a longer string would not fit. Reading characters with charAt works for a string of any length, and no arithmetic is done, so nothing can overflow.

Java Solution

The method isStrobogrammatic works in these steps:

  1. Before the method, two constants hold the lookup: TURNS = "01689", the digits that turn, and BECOMES = "01986", what each becomes, at the same positions.
  2. Start lo at 0 and hi at num.length() - 1, the two ends of the string.
  3. While lo <= hi, find the digit at lo in TURNS with indexOf and keep its position in k. If k is -1, the digit has no upside-down form, so return false.
  4. Compare BECOMES.charAt(k), the left digit upside down, with the digit at hi. If they differ, return false. Otherwise move lo right and hi left.
  5. If the loop ends without a failed pair, every pair matched, so return true.

The main method runs the three examples, then "818" and "609" with a middle digit, the single digits 8, 6 and 0, the pairs "16" and "66", a minus sign, and a 20-digit number.

Java
public class StrobogrammaticNumber {

    private static final String TURNS = "01689";      // digits that stay digits upside down
    private static final String BECOMES = "01986";    // what each one turns into

    public static boolean isStrobogrammatic(String num) {
        int lo = 0;
        int hi = num.length() - 1;
        while (lo <= hi) {
            int k = TURNS.indexOf(num.charAt(lo));
            if (k < 0) {
                return false;                         // not 0, 1, 6, 8 or 9: no digit upside down
            }
            if (BECOMES.charAt(k) != num.charAt(hi)) {
                return false;                         // the digit opposite is not its partner
            }
            lo++;
            hi--;
        }
        return true;
    }

    public static void main(String[] args) {
        String longNum = "6" + "0".repeat(18) + "9";  // 20 digits, too long for a long
        String[] tests = {"69", "88", "962", "818", "8", "6", "16", "66", "609", "0", "-69",
            longNum};
        for (String num : tests) {
            System.out.println(num + " -> " + isStrobogrammatic(num));
        }
    }
}

Running it prints:

Output
69 -> true
88 -> true
962 -> false
818 -> true
8 -> true
6 -> false
16 -> false
66 -> false
609 -> true
0 -> true
-69 -> false
60000000000000000009 -> true

The three examples come out as expected: 69 and 88 are true, and 962 is false on its first pair, where the 9 turns into 6 but the digit opposite is 2. In 818 -> true and 609 -> true, the middle digits 1 and 0 pass the check against themselves. The single 6 is false, because upside down it reads 9.

That middle check depends on lo <= hi. With lo < hi instead, the loop never looks at a lone middle digit, and "6", "868" and "828" all come out true, even though 2 has no upside-down form.

Look at 16 -> false and 66 -> false: every digit in them can turn, yet the pairs do not match. The minus sign in "-69" is not in TURNS, so it fails at once. The last line is a 20-digit number that Long.parseLong rejects with a NumberFormatException, and the method still answers true, since it only reads characters.

Complexity

The method checks each pair of opposite digits at most once and keeps only a few positions.

  • Time: O(n), because lo and hi meet after about n / 2 steps along the n digits of num, and each step is one indexOf in the five-character TURNS.
  • Space: O(1), because the method keeps only lo, hi and k, and the two lookup strings stay five characters long whatever the length of num.

Checking a number from both ends toward the middle also decides Palindrome Number, where each digit must equal the one opposite it.