Strobogrammatic Number II

Updated on 26 June, 2025
Strobogrammatic Number II header image

Problem Statement

Strobogrammatic numbers have a unique property where they appear the same when viewed right-side up or upside down. These numbers become an interesting topic for generating specific sequences. Given an integer n, you are tasked with identifying all sequence digits that form strobogrammatic numbers of that specific length n. The function needs to cater to numbers where n can be any value from 1 to 14, and the sequence of numbers returned can be in any order. The complexity lies in not only generating combinations of digits but ensuring that each combination holds true to the inherent property of being visually symmetrical when flipped.

Examples

Example 1

Input:

n = 2

Output:

["11","69","88","96"]

Example 2

Input:

n = 1

Output:

["0","1","8"]

Constraints

  • 1 <= n <= 14

Approach and Intuition

Creating a list of all strobogrammatic numbers of a specific length n can be intriguing due to their rotational symmetry characteristics. Here’s the intuition and step-by-step approach to generating these numbers:

  1. Understand Strobogrammatic Pairs: Before generating numbers, it is crucial to grasp which number pairs hold the property of looking the same upside down. The valid pairs are (0, 0), (1, 1), (6, 9), (9, 6), and (8, 8).

  2. Recursive Generation Using Base Cases:

    • For n = 1, directly return the basic single-digit strobogrammatic numbers: ["0", "1", "8"].
    • For n = 2, consider pairs excluding the (0, 0) at the start to avoid leading zeros: ["11", "69", "88", "96"].
  3. Building Greater Lengths: For any n > 2, we need to recursively sandwich strobogrammatic pairs around strobogrammatic numbers of length n-2. This builds from inside out:

    • Take each number generated for length n-2, and wrap it with each of the strobogrammatic pairs. For example, using core sequences from n-2 = ["0","1","8"], you can generate sequences of n = 4 by adding each of the pairs around these:
      • Add ("1", "1") around each to generate ["11011", "1001", "18081"] and so forth.
  4. Edge Consideration:

    • Avoid leading zeros, i.e., don't use (0, 0) around numbers for the outermost layer unless n specifically equals 2. This restriction ensures that the generated numbers are actual integers without formatting issues.

By following this approach, one can accurately generate all potential strobogrammatic numbers for any given length up to 14, as specified.

Solutions

  • C++
  • Java
  • JavaScript
  • Python
cpp
class Solution {
public:
    vector<vector<char>> symmetricPairs = {
        {'0', '0'}, {'1', '1'}, 
        {'6', '9'}, {'8', '8'}, {'9', '6'}
    };
    
    vector<string> generateStrobogrammatic(int n) {
        queue<string> numQueue;
        int currentLength;
        
        if (n % 2 == 0) {
            currentLength = 0;
            numQueue.push("");
        } else {
            currentLength = 1;
            numQueue.push("0");
            numQueue.push("1");
            numQueue.push("8");
        }
        
        while (currentLength < n) {
            currentLength += 2;
            int size = numQueue.size();
            for (int i = size; i > 0; --i) {
                string temp = numQueue.front();
                numQueue.pop();
                
                for (vector<char>& pair : symmetricPairs) {
                    if (currentLength != n || pair[0] != '0') {
                        numQueue.push(pair[0] + temp + pair[1]);
                    }
                }
            }
        }
        
        vector<string> resultStrobogrammatic;
        while (!numQueue.empty()) {
            resultStrobogrammatic.push_back(numQueue.front());
            numQueue.pop();
        }
        
        return resultStrobogrammatic;
    }
};

The provided C++ solution is crafted to generate all strobogrammatic numbers of a given length n. A strobogrammatic number is a number that appears the same when rotated 180 degrees, such as 69, 88, and 818.

  • The class solution includes a member variable that contains pairs of characters that can be symmetrically placed to maintain the strobogrammatic property. These pairs are stored in a vector symmetricPairs.

  • A public member function generateStrobogrammatic takes an integer n as an argument and returns a vector of strings, each representing a strobogrammatic number of length n.

  • The function implements a breadth-first search (BFS) approach using a queue named numQueue to hold intermediate strings during the generation process.

  • Depending on whether n is odd or even, the function initializes numQueue with either empty strings or single-digit strobogrammatic numbers ('0', '1', '8'). The variable currentLength tracks the length of numbers in the queue.

  • Within a while loop, the function incrementally builds two more digits around the current set of numbers from the queue, using valid symmetric pairs from the symmetricPairs vector. Care is taken to ensure the first digit is not '0' unless it's the only digit, which avoids numbers with leading zeros.

  • Once numQueue contains complete numbers of the desired length n, they are transferred to a vector resultStrobogrammatic and returned.

This approach is efficient for generating strobogrammatic numbers, leveraging the symmetric property and using queue-based BFS to systematically construct number by number.

java
class Solution {
    public char[][] mirrorPairs = {
        {'0', '0'}, {'1', '1'},
        {'6', '9'}, {'8', '8'}, {'9', '6'}
    };

    public List<String> generateStrobogrammatic(int len) {
        Queue<String> queue = new LinkedList<>();
        int lengthCurrent;
        
        if (len % 2 == 0) {
            lengthCurrent = 0;
            queue.add("");
        } else {
            lengthCurrent = 1;
            queue.add("0");
            queue.add("1");
            queue.add("8");
        }
        
        while (lengthCurrent < len) {
            lengthCurrent += 2;
            for (int i = queue.size(); i > 0; --i) {
                String base = queue.poll();
                
                for (char[] pair : mirrorPairs) {
                    if (lengthCurrent != len || pair[0] != '0') {
                        queue.add(pair[0] + base + pair[1]);
                    }
                }
            }
        }
        
        List<String> results = new ArrayList<>();
        while (!queue.isEmpty()) {
            results.add(queue.poll());
        }
        
        return results;
    }
}

The Java solution presented defines a method to generate all strobogrammatic numbers of a given length. A strobogrammatic number is a number that looks the same when rotated 180 degrees (upside down).

  • The mirrorPairs array contains pairs of digits that maintain their visual representation when flipped, which are fundamental in constructing strobogrammatic numbers.
  • generateStrobogrammatic is a method accepting an integer len as the target length for generating numbers.
    • A Queue<String> is used to store intermediate results dynamically.
    • The method differentiates between even and odd lengths to initialize the queue correctly; for even lengths, it starts with an empty string, and for odd lengths, it starts with "0", "1", and "8" as these are self-mirror numbers.
    • The loop continues to expand each number in the queue by sandwiching the current number between all possible mirrorPairs until the desired length len is achieved.
    • The condition inside the loop ensures no numbers start with the digit '0' unless the target length is 1.
  • After constructing the number to the required length, items are dequeed from queue to results list, which is then returned.

This implementation ensures that all strobogrammatic numbers of a specified length are efficiently generated using a breadth-first approach to progressively build valid numbers from smaller to larger lengths.

js
let flipPairs = [
    ['0', '0'], ['1', '1'], 
    ['6', '9'], ['8', '8'], ['9', '6']
];

let generateStrobogrammatic = function(length) {
    let numDigits;
    let processQueue = [];
    
    if (length % 2 == 0) {
        numDigits = 0;
        processQueue = [""];
    } else {
        numDigits = 1;
        processQueue = ["0", "1", "8"];
    }
    
    while (numDigits < length) {
        numDigits += 2;
        let nextQueue = []
        
        processQueue.forEach((element) => {
            flipPairs.forEach((mirrored) => {
                if (numDigits != length || mirrored[0] != '0') {
                    nextQueue.push(mirrored[0] + element + mirrored[1]);
                }
            });
        });
        
        processQueue = nextQueue;
    }
    
    return processQueue;
};

The given JavaScript code focuses on generating all possible strobogrammatic numbers of a specified length. A strobogrammatic number is a number that appears the same when rotated 180 degrees.

Here is a breakdown of how the solution is structured:

  • First, an array called flipPairs defines pairs of digits that look similar when flipped, such as '0' with '0', '1' with '1', '6' with '9', '8' with '8', and '9' with '6'.

  • The function generateStrobogrammatic takes an integer length which specifies the length of numbers to generate.

  • Inside the function, the initial setup depends on whether the length is odd or even:

    • If even, start with a base number as an empty string "" and initialize processQueue with this base.
    • If odd, start with a base number as '0', '1', or '8', since these are symmetric on their own.
  • The function then enters a loop that incrementally builds strobogrammatic numbers until the requested length is met. For each iteration:

    • Increase the number of digits by 2 since digits are added in mirrored pairs.
    • Create a nextQueue to store new numbers formed in the current iteration.
  • For each number from the current queue, add all possible flipPairs to it, ensuring no leading zero is introduced (except for the single-digit case).

  • Continue this process until the numDigits matches the desired length, thereby filling processQueue with full-length strobogrammatic numbers.

  • Once the loop completes, processQueue will contain all possible strobogrammatic numbers of the specified length.

The result is a let-effective way to build and explore the concept of strobogrammatic numbers using a breadth-first search approach, leveraging the symmetry property inherent to such numbers.

python
class Solution:
    def generateStrobogrammatic(self, length: int) -> List[str]:
        strobogrammatic_pairs = [
            ['0', '0'], ['1', '1'],
            ['6', '9'], ['8', '8'], ['9', '6']
        ]

        initial_list_length = length % 2

        result = ["0", "1", "8"] if initial_list_length == 1 else [""]

        while initial_list_length < length:
            initial_list_length += 2
            new_level = []

            for num in result:
                for pair in strobogrammatic_pairs:
                    if initial_list_length != length or pair[0] != '0':
                        new_level.append(pair[0] + num + pair[1])
            result = new_level

        return result

The given Python3 script defines a method named generateStrobogrammatic within a class Solution to generate all strobogrammatic numbers of a specified length. A strobogrammatic number appears the same when viewed upside-down, resembling numbers composed of digits "0," "1," "6," "8," and "9."

  • The core mechanism uses a list called strobogrammatic_pairs defining valid mirrored digit connections: "0" with "0," "1" with "1," "6" with "9," "8" with "8," and "9" with "6."
  • It begins by determining if the required length of the strobogrammatic number is odd or even. The initial list of numbers or starting point (result) is defined based on this. For odd lengths, the starting middle digits are ["0", "1", "8"], and for even lengths, an empty string.
  • The code proceeds in a loop, expanding each number by wrapping it between each mirrored pair, ensuring that no number starts with "0" unless it's the only digit, aligning with the property of valid numerical representations.
  • The iteration increases in steps of two to account for placing pairs until the desired length is reached.

Finally, the function returns a full list of strings, each representing a strobogrammatic number of the desired length. This versatile approach, through incremental construction, efficiently handles the limitations imposed by digit symmetry effectively.

Comments

No comments yet.