Strobogrammatic Number II - Problem

Given an integer n, return all the strobogrammatic numbers that are of length n. You may return the answer in any order.

A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).

The valid strobogrammatic digits are: 0, 1, 6, 8, 9 where:

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

Input & Output

Example 1 — Small Case
$ Input: n = 2
Output: ["11","69","88","96"]
💡 Note: All 2-digit strobogrammatic numbers: 11 (1↔1), 69 (6↔9), 88 (8↔8), 96 (9↔6)
Example 2 — Single Digit
$ Input: n = 1
Output: ["0","1","8"]
💡 Note: Single digits that look the same upside down: 0, 1, and 8
Example 3 — Larger Case
$ Input: n = 4
Output: ["1001","1111","1691","1881","1961","6009","6119","6699","6889","6969","8008","8118","8698","8888","8968","9006","9116","9696","9886","9966"]
💡 Note: 4-digit numbers built by adding valid pairs around 2-digit strobogrammatic numbers, excluding those with leading zeros

Constraints

  • 0 ≤ n ≤ 14

Visualization

Tap to expand
Strobogrammatic Number II INPUT n = 2 (length of number) Valid Digits: 0 --> 0 1 --> 1 8 --> 8 6 --> 9 9 --> 6 180° rotation symmetry 69 rotated = 69 96 rotated = 96 ALGORITHM STEPS 1 Base Case n=0: [""], n=1: ["0","1","8"] 2 Recursion Build from middle outward 3 Add Pairs Wrap with (0,0)(1,1)(6,9)(8,8)(9,6) 4 Skip Leading Zeros No "00" for n=2 (outermost) Building n=2: Start: [""] 1 + "" + 1 = "11" 6 + "" + 9 = "69" 8 + "" + 8 = "88" 9 + "" + 6 = "96" FINAL RESULT Strobogrammatic Numbers (n=2) "11" OK "69" OK "88" OK "96" OK Output: ["11","69","88","96"] Rotation Verification: 69 rotated --> 69 96 rotated --> 96 11 rotated --> 11 Key Insight: Build strobogrammatic numbers recursively from inside-out by wrapping valid pairs around smaller solutions. Pairs (0,0), (1,1), (8,8) are self-symmetric; (6,9) and (9,6) swap when rotated. Time: O(5^(n/2)), Space: O(n) - Each level adds 5 choices, depth is n/2 TutorialsPoint - Strobogrammatic Number II | Optimal Recursive Solution
Asked in
Google 30 Facebook 25 Amazon 20
28.0K Views
Medium Frequency
~25 min Avg. Time
850 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