#2801

Count Stepping Numbers in Range

Hard
StringDynamic ProgrammingBFS/DFS for tree/graph traversalDynamic programming for state-based problems
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of checking every number, we can use a breadth-first search (BFS) or depth-first search (DFS) to generate only the stepping numbers. This drastically reduces the number of checks we need to perform.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use BFS or DFS to generate stepping numbers starting from each digit (1-9).
  2. 2Step 2: For each generated number, check if it lies within the range [low, high].
  3. 3Step 3: Count valid stepping numbers and return the count.
solution.py20 lines
1# Full working Python code
2class Solution:
3    def countSteppingNumbers(self, low: str, high: str) -> int:
4        low, high = int(low), int(high)
5        count = 0
6        for start in range(1, 10):
7            self.bfs(start, low, high, count)
8        return count % (10**9 + 7)
9
10    def bfs(self, start, low, high, count):
11        queue = [start]
12        while queue:
13            num = queue.pop(0)
14            if low <= num <= high:
15                count += 1
16            last_digit = num % 10
17            if last_digit > 0:
18                queue.append(num * 10 + (last_digit - 1))
19            if last_digit < 9:
20                queue.append(num * 10 + (last_digit + 1))

Complexity note: The time complexity is O(n) because we only generate valid stepping numbers rather than checking every number in the range, which is much more efficient.

  • 1Stepping numbers are defined by the absolute difference of adjacent digits being 1.
  • 2Using BFS/DFS allows us to generate only valid stepping numbers, improving efficiency.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.