Problem Description
Given a string num representing an integer, determine whether it is a strobogrammatic number. A strobogrammatic number is one that appears the same when rotated 180 degrees. For example, the number "69" becomes "96", which matches when reversed with proper mapping.
Key Insights
- Use a mapping that defines the valid rotated counterparts for digits (e.g., '6' maps to '9').
- Apply two pointers (one at the start and one at the end) to check corresponding digits.
- Special cases include checking for digits that do not have a valid rotated counterpart.
- Stop the iteration when the pointers meet or cross.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the input string. Space Complexity: O(1) since only a few constant-space variables are used.
Solution
We solve the problem by using a two-pointer approach combined with a hash table (dictionary) for the valid rotated digit mappings. The algorithm works by initializing two pointers, one at the beginning and one at the end of the string. At each step, we check if the left digit is in our mapping and if its mapped value matches the right digit. If they don't match, the number is not strobogrammatic and we return false immediately. If all corresponding digits match, we return true. This approach efficiently checks symmetry with respect to 180 degree rotation using constant space and linear time.