Strobogrammatic number LeetCode
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.
Problem statement
Given a string, number, that represents an integer, return TRUE if the number is a strobogrammatic number
Constraints
numberconsists solely of digits.numberdoes 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:
Knowledge test
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
Solution
To tackle this coding problem effectively, we will explore two potential solutions, each offering unique approaches and advantages.
Algorithm 1: Using a dictionary
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
pairsmapping valid strobogrammatic pairs like {‘0’: ‘0’, ‘1’: ‘1’, ‘8’: ‘8’, ‘6’: ‘9’, ‘9’: ‘6’}.Set two pointers,
leftat the start andrightat the end ofnumber.Iterate while
leftis less than or equal toright.Check if the characters at
leftandrightform a valid strobogrammatic pair according topairs. If not, returnFalse.If the iteration completes without finding invalid pairs, return
True, indicatingnumberis 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.
Time complexity
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.
Space complexity
The space complexity of the above solution is
Algorithm 2: Create a rotated version
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_builderto store the characters of the rotated string.Iterate through each character
cin the input stringnumber, starting from the last character and moving backward.If
cis ‘0’, ‘1’, or ‘8’, appendctorotated_string_builder.If
cis ‘6’, append ‘9’ torotated_string_builder.If
cis ‘9’, append ‘6’ torotated_string_builder.If
cis none of the above, returnFalseimmediately as it’s an invalid digit for a strobogrammatic number.
Join the characters in
rotated_string_builderto create the rotated stringrotated_string.Compare
rotated_stringwith the original stringnumber. If they are equal, returnTrue(indicatingnumberis strobogrammatic). Otherwise, returnFalse.
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.
Time complexity
The time complexity of the above solution is also number because we are traversing the string in the reverse direction once.
Space complexity
The space complexity of the above solution is number. This is due to the storage of the rotated_string_builder list.
Continue learning with Educative
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