KatInterview

247. Strobogrammatic Number II

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

A strobogrammatic number is a number that appears the same when rotated 180 degrees. This property comes from specific digits that look like other digits (or themselves) when rotated. The valid pairs are:

Solution

Strobogrammatic Number II in Python

class Solution:
    def findStrobogrammatic(self, n: int) -> list[str]:
        # Start the recursion with the target length n.
        return self.helper(n, n)

    def helper(self, m: int, n: int) -> list[str]:
        # m: current length to generate, n: final total length

        # Base case: for building even-length numbers. An empty string in the middle.
        if m == 0:
            return [""]
        # Base case: for building odd-length numbers. A single strobogrammatic digit in the middle.
        if m == 1:
            return ["0", "1", "8"]

        # Recursively find the strobogrammatic numbers for the inner part (length m-2).
        prev = self.helper(m - 2, n)
        result = []

        # Construct numbers of length m by wrapping the smaller numbers.
        for s in prev:
            # The pair '00' can only be used if it's not for the outermost digits
            # to avoid leading zeros (e.g., "010"), unless n=1.
            # m == n indicates we are at the outermost layer.
            if m != n:
                result.append("0" + s + "0")
            result.append("1" + s + "1")
            result.append("6" + s + "9")
            result.append("8" + s + "8")
            result.append("9" + s + "6")

        return result

Strobogrammatic Number II in Java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
    public List<String> findStrobogrammatic(int n) {
        // Start the recursion with the target length n.
        return helper(n, n);
    }

    // m: current length to generate, n: final total length
    private List<String> helper(int m, int n) {
        // Base case: for building even-length numbers. An empty string in the middle.
        if (m == 0) {
            return new ArrayList<>(Arrays.asList(""));
        }
        // Base case: for building odd-length numbers. A single strobogrammatic digit in the middle.
        if (m == 1) {
            return new ArrayList<>(Arrays.asList("0", "1", "8"));
        }

        // Recursively find the strobogrammatic numbers for the inner part (length m-2).
        List<String> prev = helper(m - 2, n);
        List<String> result = new ArrayList<>();

        // Construct numbers of length m by wrapping the smaller numbers.
        for (String s : prev) {
            // The pair '00' can only be used if it's not for the outermost digits
            // to avoid leading zeros (e.g., "010"), unless n=1.
            // m == n indicates we are at the outermost layer.
            if (m != n) {
                result.add("0" + s + "0");
            }
            result.add("1" + s + "1");
            result.add("6" + s + "9");
            result.add("8" + s + "8");
            result.add("9" + s + "6");
        }

        return result;
    }
}

Strobogrammatic Number II in C++

class Solution {
public:
    vector<string> findStrobogrammatic(int n) {
        // Start the recursion with the target length n.
        return helper(n, n);
    }

private:
    // m: current length to generate, n: final total length
    vector<string> helper(int m, int n) {
        // Base case: for building even-length numbers. An empty string in the middle.
        if (m == 0) {
            return {""};
        }
        // Base case: for building odd-length numbers. A single strobogrammatic digit in the middle.
        if (m == 1) {
            return {"0", "1", "8"};
        }

        // Recursively find the strobogrammatic numbers for the inner part (length m-2).
        vector<string> prev = helper(m - 2, n);
        vector<string> result;

        // Construct numbers of length m by wrapping the smaller numbers.
        for (const string& s : prev) {
            // The pair '00' can only be used if it's not for the outermost digits
            // to avoid leading zeros (e.g., "010"), unless n=1.
            // m == n indicates we are at the outermost layer.
            if (m != n) {
                result.push_back("0" + s + "0");
            }
            result.push_back("1" + s + "1");
            result.push_back("6" + s + "9");
            result.push_back("8" + s + "8");
            result.push_back("9" + s + "6");
        }

        return result;
    }
};

Strobogrammatic Number II in TypeScript

function findStrobogrammatic(n: number): string[] {
    // Helper function for recursion
    // m: current length to generate, n: final total length
    const helper = (m: number, n: number): string[] => {
        // Base case: for building even-length numbers. An empty string in the middle.
        if (m === 0) {
            return [""];
        }
        // Base case: for building odd-length numbers. A single strobogrammatic digit in the middle.
        if (m === 1) {
            return ["0", "1", "8"];
        }

        // Recursively find the strobogrammatic numbers for the inner part (length m-2).
        const prev = helper(m - 2, n);
        const result: string[] = [];

        // Construct numbers of length m by wrapping the smaller numbers.
        for (const s of prev) {
            // The pair '00' can only be used if it's not for the outermost digits
            // to avoid leading zeros (e.g., "010"), unless n=1.
            // m === n indicates we are at the outermost layer.
            if (m !== n) {
                result.push("0" + s + "0");
            }
            result.push("1" + s + "1");
            result.push("6" + s + "9");
            result.push("8" + s + "8");
            result.push("9" + s + "6");
        }

        return result;
    };

    // Start the recursion with the target length n.
    return helper(n, n);
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.