Magicsheet logo

Strobogrammatic Number II

Medium
12.5%
Updated 8/1/2025

Strobogrammatic Number II

What is this problem about?

Building on the concept of strobogrammatic numbers, Strobogrammatic Number II asks you to find all strobogrammatic numbers of a specific length n. A strobogrammatic number is one that looks the same when rotated 180 degrees. For example, if n=2, the valid numbers are "11", "69", "88", and "96". Note that "00" is not a valid 2-digit number because it has leading zeros. This problem requires generating all possible combinations that satisfy the strobogrammatic property for a given length.

Why is this asked in interviews?

This question is a favorite at Uber and Google because it tests recursion and backtracking skills. Unlike the first version of the problem which was a simple validation, this version requires construction. It assesses how a candidate handles recursive branching and how they manage edge cases like leading zeros. It's a great example of how a simple concept can be extended into a more complex combinatorial problem.

Algorithmic pattern used

The primary pattern for this problem is Recursion or Backtracking. To generate a number of length n, you can start by generating all strobogrammatic numbers of length n-2 and then wrapping them with valid strobogrammatic pairs (00, 11, 88, 69, 96). The base cases are n=0 (an empty string) and n=1 ("0", "1", "8"). You recursively build up the strings until you reach the target length, ensuring that "00" is not added at the outermost layer to avoid leading zeros.

Example explanation (use your own example)

To find all strobogrammatic numbers of length n=2:

  1. Start with the base case for n=0: [""].
  2. For n=2, we take the result of n=0 and wrap it with pairs.
  3. Pairs are: (1,1), (8,8), (6,9), (9,6), and (0,0).
  4. Wrapping "" with these gives: "11", "88", "69", "96", and "00".
  5. Since n=2 is the outermost layer, we discard "00". Result: ["11", "88", "69", "96"].

Common mistakes candidates make

A common error is including "0" as a leading digit for numbers where n > 1. Another mistake is failing to handle the base cases for both n=0 and n=1 correctly, which are needed to build even and odd-length numbers respectively. Some candidates try to use an iterative approach with many nested loops, which becomes very difficult to manage compared to a clean recursive solution.

Interview preparation tip

When tackling the Strobogrammatic Number II interview question, think of it as "building from the inside out." This perspective makes the recursion much easier to visualize. Also, pay close attention to the leading zero constraint—it's the most common reason for failing test cases. Be ready to explain the time complexity, which is related to the number of valid strobogrammatic digits (roughly 5^(n/2)).

Similar Questions