Problem
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Write a function to determine if a number is strobogrammatic. The number is represented as a string.
Examples
Example 1:
| |
Example 2:
| |
Example 3:
| |
Solution
Sure! Let’s create a program to find all strobogrammatic numbers with N digits. Strobogrammatic numbers are numbers that look the same when rotated 180 degrees. The pairs of digits that make up strobogrammatic numbers are:
0and01and16and98and89and6
Method 1 - Using Two Pointers and Map
We can create the map of pairs we discussed above. Now, this problem can be considered a special type of palindrome detection or can be solved using double pointers.
- If the first and last numbers are the same, they must be either 0, 1, or 8.
- If they differ, then one must be 6 and the other 9, or vice versa.
- Any other cases will return false.
Code
| |
Complexity
- ⏰ Time complexity:
O(n) - 🧺 Space complexity:
O(1)
Method 1 - Using Two Pointers but no Map
Code
| |
Complexity
- ⏰ Time complexity:
O(n) - 🧺 Space complexity:
O(1)