Strobogrammatic Number
A strobogrammatic number is one that looks the same when rotated 180 degrees. Given a string num, return whether it is strobogrammatic.
Example 1
Input: "69" → Output: true
Example 2
Input: "962" → Output: false
Solution Approach
Check pairs from outside in. Valid strobogrammatic digit pairs: (0,0),(1,1),(6,9),(8,8),(9,6). Middle digit (if odd length) must be 0, 1, or 8.
- Two pointers lo=0, hi=n-1.
- Check if (num[lo], num[hi]) is a valid strobogrammatic pair.
- Middle element (lo==hi) must be 0, 1, or 8.
Java
import java.util.*;
class Solution {
public boolean isStrobogrammatic(String num) {
Map<Character,Character> map = new HashMap<>();
map.put('0','0'); map.put('1','1'); map.put('6','9'); map.put('8','8'); map.put('9','6');
int lo=0, hi=num.length()-1;
while (lo <= hi) {
char c = num.charAt(lo);
if (!map.containsKey(c) || map.get(c) != num.charAt(hi)) return false;
lo++; hi--;
}
return true;
}
}
- Time Complexity: O(N)
- Space Complexity: O(1)