Problem solution · Python

Strobogrammatic Number III

Strobogrammatic Number III: a Python solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Depth-first search
Source
walkccc LeetCode Solutions
Length
29 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Depth-first search

For Strobogrammatic Number III, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. Combine child results or undo the choice when the branch finishes.

Code notes

  • 29 lines of Python from the credited upstream file 248.py.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected, together with recursive traversal.

Complexity

Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeStrobogrammatic Number III · PythonPython
Use this to learn the idea, then write your own version.
class Solution:  def strobogrammaticInRange(self, low: str, high: str) -> int:    pairs = [['0', '0'], ['1', '1'], ['6', '9'], ['8', '8'], ['9', '6']]    ans = 0     def dfs(s: list[str], l: int, r: int) -> None:      nonlocal ans      if l > r:        if len(s) == len(low) and ''.join(s) < low:          return        if len(s) == len(high) and ''.join(s) > high:          return        ans += 1        return       for leftDigit, rightDigit in pairs:        if l == r and leftDigit != rightDigit:          continue        s[l] = leftDigit        s[r] = rightDigit        if len(s) > 1 and s[0] == '0':          continue        dfs(s, l + 1, r - 1)     for n in range(len(low), len(high) + 1):      dfs([' '] * n, 0, n - 1)     return ans 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗