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:
0rotates to01rotates to16rotates to98rotates to89rotates to6
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
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
โ Linear Growth
Space Complexity
O(5^n)
Store all generated combinations and results
โก 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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code