A strobogrammatic number is a number that appears the same when viewed upside down, that is when rotated by 180 degrees. For example, the numbers 0, 1, and 8 remain the same when rotated, while the number 6 becomes 9 and number 9 becomes 6. These numbers are significant in fields like digital displays and cryptography due to their unique symmetrical properties. This property is useful in designing systems where readability from different orientations is crucial.
Given a string, number
, that represents an integer, return TRUE if the number
is a strobogrammatic number
Constraints
number
consists solely of digits.
number
does not have leading zeros unless it is zero itself.
Let’s take a look at a few examples to get a better understanding of the strobogrammatic number LeetCode problem:
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem.
Which number is NOT strobogrammatic?
918
619
689
906
To tackle this coding problem effectively, we will explore two potential solutions, each offering unique approaches and advantages.
The first step involves creating a dictionary that defines valid strobogrammatic pairs, such as (0, 0), (1, 1), (8, 8), (6, 9), and (9, 6). Then, two pointers are initialized—one at the beginning of the string and the other at the end. These pointers move toward each other, checking whether the characters they point to form a valid strobogrammatic pair, according to the dictionary. If at any point the characters do not match a valid pair, the string is deemed not strobogrammatic, and the algorithm returns False
. However, if the pointers meet (or cross for an odd-length string) without encountering invalid pairs, the string is confirmed to be strobogrammatic, and the algorithm returns True
. The steps of the algorithm are given below:
Initialize a dictionary pairs
mapping valid strobogrammatic pairs like {‘0’: ‘0’, ‘1’: ‘1’, ‘8’: ‘8’, ‘6’: ‘9’, ‘9’: ‘6’}.
Set two pointers, left
at the start and right
at the end of number
.
Iterate while left
is less than or equal to right
.
Check if the characters at left
and right
form a valid strobogrammatic pair according to pairs
. If not, return False
.
If the iteration completes without finding invalid pairs, return True
, indicating number
is strobogrammatic.
Let’s look at the illustrations below to better understand the solution.
Let’s look at the code for this solution below.
def is_strobogrammatic(number):# Create a dictionary of valid strobogrammatic pairspairs = {'0': '0', '1': '1', '8': '8', '6': '9', '9': '6'}# Initialize two pointersleft, right = 0, len(number) - 1# Move pointers towards each otherwhile left <= right:left_char, right_char = number[left], number[right]# Check if the characters form a valid pairif left_char not in pairs or pairs[left_char] != right_char:return False # Not a strobogrammatic number# Move pointersleft += 1right -= 1# If pointers meet (or cross for odd-length string), it's strobogrammaticreturn Truedef main():test_cases = ["69", "818", "123", "88", "690"]i = 1for number in test_cases:print(i, ".\tnumber: ", number, sep ="")print("\n\tIs strobogrammatic?", is_strobogrammatic(number))print("-"*100)i+=1main();
Now that we have explored one of the solutions for this LeetCode problem, let’s analyze its time and space complexity to understand how efficiently it scales with larger inputs.
The time complexity of the above solution is number
. This is because the function checks each pair of characters from the start and end of the string toward the center.
The space complexity of the above solution is
The algorithm constructs a rotated version of number
by iterating through its characters in reverse order, replacing ‘6’ with ‘9’ and vice versa, and keeping ‘0’, ‘1’, and ‘8’ unchanged. If the resulting rotated string matches the original number
, the algorithm returns True
; otherwise, it returns False
, indicating that the number
is not strobogrammatic. The steps of the algorithm are given below.
Create an empty list called rotated_string_builder
to store the characters of the rotated string.
Iterate through each character c
in the input string number
, starting from the last character and moving backward.
If c
is ‘0’, ‘1’, or ‘8’, append c
to rotated_string_builder
.
If c
is ‘6’, append ‘9’ to rotated_string_builder
.
If c
is ‘9’, append ‘6’ to rotated_string_builder
.
If c
is none of the above, return False
immediately as it’s an invalid digit for a strobogrammatic number.
Join the characters in rotated_string_builder
to create the rotated string rotated_string
.
Compare rotated_string
with the original string number
. If they are equal, return True
(indicating number
is strobogrammatic). Otherwise, return False
.
Let’s look at the illustrations below to better understand the solution.
Let’s look at the code for this solution below.
def is_strobogrammatic(number):rotated_string_builder = []# Loop backwards through the stringfor c in number[::-1]:if c in ('0', '1', '8'):rotated_string_builder.append(c)elif c == '6':rotated_string_builder.append('9')elif c == '9':rotated_string_builder.append('6')else: # Invalid digitreturn Falserotated_string = ''.join(rotated_string_builder)return number == rotated_stringdef main():test_cases = ["69", "818", "123", "88", "690"]i = 1for number in test_cases:print(i, ".\tnumber: ", number, sep ="")print("\n\tIs strobogrammatic?", is_strobogrammatic(number))print("-"*100)i+=1main();
Let’s analyze the time and space complexity of this solution.
The time complexity of the above solution is also number
because we are traversing the string in the reverse direction once.
The space complexity of the above solution is number
. This is due to the storage of the rotated_string_builder
list.
This is only a single coding problem. If you want to explore more coding challenges that can help prepare you for interviews at major tech companies, consider exploring the following blogs by Educative:
Free Resources