Strobogrammatic Number III - Problem

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

Given two strings low and high that represent two integers where low <= high, return the number of strobogrammatic numbers in the range [low, high].

The digits that remain the same when rotated 180 degrees are: 0, 1, 6, 8, 9 where:

  • 0 → 0
  • 1 → 1
  • 6 → 9
  • 8 → 8
  • 9 → 6

Input & Output

Example 1 — Small Range
$ Input: low = "50", high = "100"
Output: 3
💡 Note: Strobogrammatic numbers in range [50,100] are: 69, 88, 96. Each looks the same when rotated 180°.
Example 2 — Single Digit Range
$ Input: low = "0", high = "9"
Output: 3
💡 Note: Single digit strobogrammatic numbers are: 0, 1, 8. Numbers 2,3,4,5,6,7,9 don't look the same when rotated.
Example 3 — No Valid Numbers
$ Input: low = "20", high = "30"
Output: 0
💡 Note: No strobogrammatic numbers exist between 20 and 30.

Constraints

  • 1 ≤ low.length, high.length ≤ 15
  • low and high consist of only digits
  • low ≤ high
  • low and high do not contain any leading zeros except for zero itself

Visualization

Tap to expand
Strobogrammatic Number III INPUT Valid Strobogrammatic Digits: 0 0 1 1 6 9 8 8 9 6 (digit --> rotated 180) Search Range: 50 low 100 high Input Values: low = "50", high = "100" Find count of strobogrammatic numbers in range [50, 100] ALGORITHM STEPS 1 Generate by Length Build from center outward len=2: [11, 69, 88, 96] len=3: [101, 111, 181, ...] 2 Recursive Build Add pairs: (0,0)(1,1)(6,9)(8,8)(9,6) "" --> "11" --> "1111" "" --> "69" --> "6969" 3 Filter by Range Check: low <= num <= high 69: 50 <= 69 <= 100 [OK] 88: 50 <= 88 <= 100 [OK] 96: 50 <= 96 <= 100 [OK] 4 Count Valid Numbers Handle leading zeros edge case Valid: 69, 88, 96 = 3 nums FINAL RESULT Strobogrammatic Numbers Found: 69 rotates to 69 88 rotates to 88 96 rotates to 69 Rotation Example (180 deg): 69 --> 69 Output: 3 3 strobogrammatic numbers Key Insight: Build strobogrammatic numbers recursively from inside-out. For even length, start with empty string; for odd length, start with single digits (0, 1, 8). Add valid pairs (0,0), (1,1), (6,9), (8,8), (9,6) to both ends. Skip leading zeros except for "0" itself. Time: O(5^(n/2)) where n is max digit length. TutorialsPoint - Strobogrammatic Number III | Optimal Solution (Recursive Generation)
Asked in
Google 15 Facebook 12
28.0K Views
Medium Frequency
~35 min Avg. Time
847 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