Strobogrammatic Number II - Problem

A strobogrammatic number is a fascinating mathematical concept where a number looks identical when rotated 180 degrees (or viewed upside down). Think of it like looking at a digital clock in a mirror!

Given an integer n, your task is to return all strobogrammatic numbers that have exactly n digits. You may return the answer in any order.

Key insight: Only the digits 0, 1, 6, 8, 9 can be part of a strobogrammatic number because:

  • 0 rotates to 0
  • 1 rotates to 1
  • 6 rotates to 9
  • 8 rotates to 8
  • 9 rotates to 6

Example: For n = 2, valid strobogrammatic numbers are ["11", "69", "88", "96"]

Input & Output

example_1.py โ€” Basic Case
$ Input: n = 2
โ€บ Output: ["11", "69", "88", "96"]
๐Ÿ’ก Note: For 2-digit numbers, we need pairs that look the same when rotated: 11 (1โ†”1), 69 (6โ†”9), 88 (8โ†”8), and 96 (9โ†”6).
example_2.py โ€” Single Digit
$ Input: n = 1
โ€บ Output: ["0", "1", "8"]
๐Ÿ’ก Note: Only digits 0, 1, and 8 look the same when rotated 180 degrees by themselves.
example_3.py โ€” Larger Case
$ Input: n = 3
โ€บ Output: ["101", "111", "181", "609", "619", "689", "808", "818", "888", "906", "916", "986"]
๐Ÿ’ก Note: For 3-digit numbers, the middle digit must be 0, 1, or 8, and the outer digits must form valid pairs without leading zeros.

Visualization

Tap to expand
"8"1"8"1"181"6"181"9"61819"Recursive ConstructionEach layer adds symmetric pairs
Understanding the Visualization
1
Start from Center
Begin with base cases: empty string or single valid digits
2
Add Symmetric Layers
Wrap each result with valid strobogrammatic pairs
3
Avoid Leading Zeros
Filter out invalid numbers starting with 0
4
Complete Construction
Return all valid n-digit strobogrammatic numbers
Key Takeaway
๐ŸŽฏ Key Insight: Use recursion to build from inside-out, placing symmetric digit pairs at each step to guarantee all generated numbers are strobogrammatic!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(5^n)

We generate 5^n combinations and check each one

n
2n
โœ“ Linear Growth
Space Complexity
O(5^n)

Store all generated combinations and results

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค n โ‰ค 14
  • The answer will fit in a 32-bit integer array
  • No leading zeros except for single digit "0" when n = 1
Asked in
Google 45 Meta 32 Amazon 28 Microsoft 15
32.0K Views
Medium Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen