Strobogrammatic Number Problem
Description
LeetCode Problem 246.
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).
Example 1:
Input: num = "69"
Output: true
Example 2:
Input: num = "88"
Output: true
Example 3:
Input: num = "962"
Output: false
Constraints:
1 <= num.length <= 50numconsists of only digits.numdoes not contain any leading zeros except for zero itself.
Solution
Approach: Two Pointers
Turning a number upside down does two things: it reverses the order of the digits, and it rotates each digit. Only five digits survive a rotation: 0, 1 and 8 stay the same, and 6 and 9 turn into each other. 2, 3, 4, 5 and 7 are not digits any more.
So the number is strobogrammatic if, for every pair of positions i and j = len - 1 - i, the digit at i rotated equals the digit at j. Store the rotation as a table rotated, with -1 for the digits that cannot be rotated, and move two pointers inward from both ends.
Let the loop run while i <= j, so that the middle digit of an odd-length number is checked against itself. That is why "818" is strobogrammatic but "6" alone is not: 6 rotated is 9.
Complexity: O(n) time, where n is the number of digits. O(1) extra space.
class Solution:
def isStrobogrammatic(self, num: str) -> bool:
# rotated[d] is digit d turned upside down, or -1 if it is not a digit any more
rotated = [0, 1, -1, -1, -1, -1, 9, -1, 8, 6]
i, j = 0, len(num) - 1
while i <= j: # i == j is the middle digit, which must map to itself
if rotated[int(num[i])] != int(num[j]):
return False
i, j = i + 1, j - 1
return True