Similar Problems

Similar Problems not available

Strobogrammatic Number - Leetcode Solution

Companies:

LeetCode:  Strobogrammatic Number Leetcode Solution

Difficulty: Easy

Topics: string hash-table two-pointers  

Problem Statement: 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.

Example 1: Input: num = "69" Output: true

Example 2: Input: num = "88" Output: true

Example 3: Input: num = "962" Output: false

Example 4: Input: num = "1" Output: true

Approach: The problem is quite simple if we observe the strobogrammatic numbers. Strobogrammatic numbers contain only the following digits: 0, 1, 6, 8, 9 and when we look at the number upside down, these digits can be rotated and they will still look the same i.e., 0, 1, 9, 8, 6.

So, our approach is quite simple, we will create a dictionary/map and store the corresponding upside-down number for each digit. Then we will traverse the given number and check if the corresponding upside-down digit is present in the dictionary, and if it is present, we will append it to a new string. Finally, we will check if the new string is equal to the given number, that means it is a strobogrammatic number, else it is not.

Solution: Initially, we will define a dictionary containing the mapping of each digit to its upside-down digit.

strobos = {
    '0': '0',
    '1': '1',
    '6': '9',
    '8': '8',
    '9': '6'
}

Then, we will create a new string by iterating through the given number and finding its corresponding upside-down digit from the dictionary.

new_str = ""
for c in num:
    if c not in strobos:
        return False
    new_str += strobos[c]

Then, we will check if the new string is equal to the given number, if it is, return True, else False.

return num == new_str

Code:

def isStrobogrammatic(num: str) -> bool:
    strobos = {
        '0': '0',
        '1': '1',
        '6': '9',
        '8': '8',
        '9': '6'
    }
    new_str = ""
    for c in num:
        if c not in strobos:
            return False
        new_str += strobos[c]
        
    return num == new_str

Time Complexity: O(n) where n is the length of the string.

Space Complexity: O(1) as we are using a fixed-sized dictionary.

Strobogrammatic Number Solution Code

1