Skip to main content

Strobogrammatic Number

Description​

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:​

Example 1:

Input:  "69"
Output: true

Example 2:

Input:  "88"
Output: true

Example 3:

Input:  "962"
Output: false

Solution​

Approach​

  1. Create a dictionary to map each digit to its strobogrammatic counterpart.
  2. Iterate over the number from both ends towards the center.
  3. For each pair of digits, check if they are valid strobogrammatic pairs using the dictionary.
  4. Return true if all pairs are valid, otherwise return false.

Codes in Different Languages​

Written by @sivaprasath
function isStrobogrammatic(num) {
const strobogrammaticMap = {
'0': '0',
'1': '1',
'6': '9',
'8': '8',
'9': '6'
};
let left = 0, right = num.length - 1;
while (left <= right) {
if (!(num[left] in strobogrammaticMap) || strobogrammaticMap[num[left]] !== num[right]) {
return false;
}
left++;
right--;
}
return true;
}

// Example usage:
console.log(isStrobogrammatic("69")); // Output: true
console.log(isStrobogrammatic("88")); // Output: true
console.log(isStrobogrammatic("962")); // Output: false

Explanation:​

  1. The strobogrammaticMap defines the valid strobogrammatic pairs.
  2. Two pointers, left and right, traverse the string from both ends towards the center.
  3. For each pair of digits, we check if they exist in the map and match the required strobogrammatic counterpart.
  4. If any pair is invalid, return false; if all pairs are valid, return true.

Complexity:​

  1. Time complexity: O(n)O(n), where nn is the length of the input string, as we only iterate through the string once.
  2. Space complexity: O(1)O(1), as we use a fixed amount of extra space for the map and pointers.
  3. This makes the approach efficient and suitable for checking strobogrammatic properties in linear time.

References​

Author:

Loading...