medium Strobogrammatic Number II
Problem Statement
Given a positive integer n, return all the strobogrammatic numbers which are of length n. Return the answer in any order.
A strobogrammatic number is a number that looks the same when flipped upside down.
Examples
-
Example 1:
- Input:
n = 2 - Expected Output:
["11", "69", "88", "96"] - Justification: When these numbers are rotated 180 degrees, they appear the same as their original form. Other two-digit combinations do not retain the same appearance after being flipped.
- Input:
-
Example 2:
- Input:
n = 1 - Expected Output:
["0", "1", "8"] - Justification: These are the only single-digit numbers that look the same when viewed upside down.
- Input:
-
Example 3:
- Input:
n = 3 - Expected Output:
["101", "609", "808", "906", "111", "619", "818", "916", "181", "689", "888", "986"] - Justification: These numbers are symmetrical and maintain their appearance when flipped 180 degrees. Other three-digit numbers do not meet this criterion.
- Input:
Try it yourself
Try solving this question here:
✅ Solution Strobogrammatic Number II
Problem Statement
Given a positive integer n, return all the strobogrammatic numbers which are of length n. Return the answer in any order.
A strobogrammatic number is a number that looks the same when flipped upside down.
Examples
-
Example 1:
- Input:
n = 2 - Expected Output:
["11", "69", "88", "96"] - Justification: When these numbers are rotated 180 degrees, they appear the same as their original form. Other two-digit combinations do not retain the same appearance after being flipped.
- Input:
-
Example 2:
- Input:
n = 1 - Expected Output:
["0", "1", "8"] - Justification: These are the only single-digit numbers that look the same when viewed upside down.
- Input:
-
Example 3:
- Input:
n = 3 - Expected Output:
["101", "609", "808", "906", "111", "619", "818", "916", "181", "689", "888", "986"] - Justification: These numbers are symmetrical and maintain their appearance when flipped 180 degrees. Other three-digit numbers do not meet this criterion.
- Input:
Solution
To solve this problem, we start by recognizing that strobogrammatic numbers are formed by pairing certain digits: 0 with 0, 1 with 1, 8 with 8, 6 with 9, and 9 with 6. Our approach involves constructing these numbers from the middle outwards, ensuring symmetry and adherence to the strobogrammatic principle. For numbers of even length, we begin with an empty string and progressively add strobogrammatic pairs to both ends. For odd-length numbers, we start with each of the three symmetric strobogrammatic numbers (0, 1, 8) as the center and expand similarly. This strategy is efficient because it directly constructs valid numbers without needing to validate each candidate, significantly reducing the computational overhead compared to brute force methods.
This method is particularly effective because it leverages the recursive nature of strobogrammatic numbers. By building from the center, we ensure that each constructed number is valid by design, eliminating the need for post-construction validation. This recursive approach not only simplifies the problem but also ensures that all possible combinations are explored, guaranteeing the completeness of the solution set.
Step-by-step Algorithm
-
Initialize the Base Cases: Start with two base conditions for recursion:
- If
n == 0, return a list containing an empty string because a number of length 0 is an empty string. - If
n == 1, return a list containing the single-digit strobogrammatic numbers"0","1", and"8".
- If
-
Recursive Construction: For values of
ngreater than 1, recursively build the strobogrammatic numbers by reducingnby 2 in each step. This reduction accounts for adding a pair of digits (one at the beginning and one at the end) to maintain the symmetry required for a number to be strobogrammatic. -
Building from the Middle: Use the results from the recursive call (which gives strobogrammatic numbers of length
n-2) as the "middle part" around which the strobogrammatic pairs are added to form numbers of lengthn.- For
nreduced to 2, start with the middle part as an empty string"", and fornreduced to 1, start with"0","1", and"8".
- For
-
Adding Strobogrammatic Pairs: For each string obtained from the recursion:
- If
nis not equal to the original input (i.e., we are not at the first level of recursion), prepend and append"0"to the string (except at the outermost level to avoid leading zeros). - For all levels of recursion, prepend and append pairs
"1"and"1","6"and"9","8"and"8","9"and"6"to each of the strings obtained from the recursive call. This step ensures the strobogrammatic property is maintained.
- If
-
Collect Results: Combine all these strings to form the list of all possible strobogrammatic numbers of length
n. Return this list as the result.
Algorithm Walkthrough
For n = 3, we aim to construct all possible strobogrammatic numbers of length 3 by building from the middle and expanding outwards, ensuring symmetry. Here's a detailed step-by-step walkthrough:
-
Initial Call: The process begins by calling the method to construct strobogrammatic numbers of length 3.
-
Recursive Construction:
- Since
n = 3is not a base case, we proceed by reducingnby 2 and making a recursive call to construct strobogrammatic numbers of the reduced length (i.e.,n = 1in this step). - For
n = 1, the base case directly returns the list["0", "1", "8"].
- Since
-
Backtracking and Building:
- Starting with the results from the base case (
["0", "1", "8"]), we backtrack and add pairs of digits to these single digits to build strobogrammatic numbers of length 3.
- Starting with the results from the base case (
-
Adding Pairs Around Each Base Case Result:
- For "0" as the middle digit:
- We add strobogrammatic pairs around "0", forming
"101","609","808", and"906". Each pair is added such that the number remains symmetrical and strobogrammatic.
- We add strobogrammatic pairs around "0", forming
- For "1" as the middle digit:
- Similarly, we add pairs around "1", resulting in
"111","619","818", and"916".
- Similarly, we add pairs around "1", resulting in
- For "8" as the middle digit:
- We add pairs around "8", forming
"181","689","888", and"986".
- We add pairs around "8", forming
- For "0" as the middle digit:
-
Combining Results:
- All these newly formed numbers are then combined into a single list, which becomes the final output for
n = 3. - Final Result:
["101", "609", "808", "906", "111", "619", "818", "916", "181", "689", "888", "986"].
- All these newly formed numbers are then combined into a single list, which becomes the final output for
-
Backtracking to Complete:
- Completion: At this point, we have constructed all strobogrammatic numbers of length 3 by effectively using backtracking. For each base case digit, we explored all possible symmetrical pairs that can surround it, ensuring the strobogrammatic property is maintained.
- Return: The list of constructed numbers is returned as the output of the recursive process.
Code
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
// Define a Solution class for finding strobogrammatic numbers
public class Solution {
// Public method to find all strobogrammatic numbers of a given length
public List<String> findStrobogrammatic(int n) {
// Initiate the building process with the given length n
return buildStrobogrammatic(n, n);
}
// Helper method to recursively build the strobogrammatic numbers
private List<String> buildStrobogrammatic(int n, int total) {
// Base case for recursion: if n equals 0, return a list with an empty string
if (n == 0) return new ArrayList<>(Arrays.asList(""));
// Base case for recursion: if n equals 1, return a list of all single-digit strobogrammatic numbers
if (n == 1) return new ArrayList<>(Arrays.asList("0", "1", "8"));
// Recursive call to build the middle part of the strobogrammatic numbers
List<String> prevList = buildStrobogrammatic(n - 2, total);
List<String> resultList = new ArrayList<>();
// Iterate over each string from the previous recursion level
for (String s : prevList) {
// If we're not at the outermost level, add "0" paired with "0" around the string
if (n != total) resultList.add("0" + s + "0");
// Add pairs of strobogrammatic digits around the current string
resultList.add("1" + s + "1");
resultList.add("6" + s + "9");
resultList.add("8" + s + "8");
resultList.add("9" + s + "6");
}
return resultList; // Return the list of strobogrammatic numbers
}
public static void main(String[] args) {
Solution solution = new Solution();
// Test the method with the provided example inputs
System.out.println("n = 2: " + solution.findStrobogrammatic(2));
System.out.println("n = 1: " + solution.findStrobogrammatic(1));
System.out.println("n = 3: " + solution.findStrobogrammatic(3));
}
}
Complexity Analysis
-
Time Complexity: The time complexity is O(5^(n/2)) for generating all strobogrammatic numbers of length
n. This is because, at each step (except the first and last for even and odd lengths, respectively), we have 5 choices (0 with 0, 1 with 1, 8 with 8, 6 with 9, and 9 with 6) for each of then/2positions (considering the symmetry of the numbers). -
Space Complexity: The space complexity is also O(5^(n/2)) due to the storage requirements of the output. Additionally, the recursion stack adds another
for the depth of the recursive calls, but this is overshadowed by the output space in most cases.
🤖 Don't fully get this? Learn it with Claude
Stuck on Strobogrammatic Number II? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Strobogrammatic Number II** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Strobogrammatic Number II** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Strobogrammatic Number II**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Strobogrammatic Number II**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.