Skip to main content

Stepping Numbers - Solution & Explanation

MediumPremiumFree on FleetCodeMathBacktrackingBreadth-First Search9 min readAsked at: Epic Systems
Practice this problem

Problem Statement

A stepping number is an integer such that all of its adjacent digits have an absolute difference of exactly 1.

  • For example, 321 is a stepping number while 421 is not.

Given two integers low and high, return a sorted list of all the stepping numbers in the inclusive range [low, high].

 

Example 1:

Input: low = 0, high = 21
Output: [0,1,2,3,4,5,6,7,8,9,10,12,21]

Example 2:

Input: low = 10, high = 15
Output: [10,12]

 

Constraints:

  • 0 <= low <= high <= 2 * 109

Approach Overview

Problem Overview: A stepping number is an integer where the absolute difference between every pair of adjacent digits is exactly 1. Given a range [low, high], return all numbers in that interval that satisfy this property. The challenge is generating valid numbers efficiently without checking every integer in the range.

Approach 1: Brute Force Digit Check (O(n * d) time, O(1) space)

The most direct method iterates through every number from low to high. For each number, convert it to digits and check whether the absolute difference between adjacent digits equals 1. This requires scanning up to d digits per number, giving O(n * d) time where n is the range size. The approach is simple but inefficient when the range is large because most numbers will fail the stepping condition.

Approach 2: Backtracking / DFS Generation (O(k) time, O(k) space)

Instead of checking every number, generate only valid stepping numbers using depth‑first search. Start with digits 1 through 9. For each number, append the next digit as lastDigit ± 1. This guarantees the stepping property while constructing the number. Stop recursion once the number exceeds high. The algorithm produces only valid candidates, so the time complexity becomes proportional to the number of generated stepping numbers k. DFS is a natural fit when you think of the problem as exploring a digit tree with two possible branches per node.

Approach 3: Breadth‑First Search (O(k) time, O(k) space)

The optimal and most common solution uses Breadth‑First Search. Initialize a queue with digits 1 through 9. Repeatedly pop a number, add it to the result if it lies in [low, high], and expand it by appending digits derived from lastDigit ± 1. Because BFS grows numbers level by level, it naturally generates stepping numbers in increasing order. This avoids scanning invalid numbers and keeps the complexity proportional to the number of valid results k. The idea is similar to exploring a graph where each node represents a number and edges connect numbers whose last digits differ by one.

The problem mixes digit manipulation with graph traversal concepts. Many candidates recognize the pattern once they think about generating numbers rather than validating them. Related ideas often appear in problems involving digit construction with constraints, which combine backtracking and math reasoning.

Recommended for interviews: BFS generation. It avoids unnecessary checks and demonstrates that you can model the problem as state expansion instead of brute‑force iteration. Mentioning the brute‑force check first shows you understand the definition of stepping numbers, but switching to BFS highlights stronger algorithmic thinking and leads to an efficient O(k) solution.

Solution

First, if low is 0, we need to add 0 to the answer.

Next, we create a queue q and add 1 \sim 9 to the queue. Then, we repeatedly take out elements from the queue. Let the current element be v. If v is greater than high, we stop searching. If v is in the range [low, high], we add v to the answer. Then, we need to record the last digit of v as x. If x \gt 0, we add v times 10 + x - 1 to the queue. If x \lt 9, we add v times 10 + x + 1 to the queue. Repeat the above steps until the queue is empty.

The time complexity is O(10 times 2^{log M}), and the space complexity is O(2^{log M}), where M is the number of digits in high.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Digit CheckO(n * d)O(1)Simple implementation when the range size is very small
Backtracking / DFS GenerationO(k)O(k)When you prefer recursive exploration of digit combinations
Breadth-First Search (BFS)O(k)O(k)Best general solution; generates stepping numbers directly in increasing order

Video Solution

Stepping Numbers | InterviewBit | Geeksforgeeks | HindiLeetforces6,315 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Stepping Numbers easy or hard?
Stepping Numbers is generally considered a medium difficulty problem. The definition is simple, but the efficient solution requires recognizing that you should generate valid numbers with BFS or DFS rather than checking every integer in the range.
Stepping Numbers Python/Java solution
Most implementations follow the same BFS pattern across languages. Initialize a queue with digits 1–9, pop numbers, add them to the result if they fall within the range, and push new numbers formed by lastDigit ± 1. The logic remains identical in Python, Java, C++, Go, and TypeScript.
How to solve Stepping Numbers in O(n)?
Instead of checking every number in the interval, generate stepping numbers directly. Use BFS starting from digits 1–9 and append digits equal to lastDigit ± 1. Stop expanding when the number exceeds the upper bound. The algorithm effectively runs in O(k) time, proportional to the number of valid results.
What is the best approach for Stepping Numbers?
Breadth‑First Search (BFS) is the most practical approach. Start with digits 1–9 in a queue and repeatedly append lastDigit ± 1 to build new numbers. This generates only valid stepping numbers and avoids scanning the entire range. The complexity is O(k), where k is the number of stepping numbers produced.
Is Stepping Numbers asked at Google/Amazon/Meta?
Digit‑generation problems like Stepping Numbers appear in interviews at large tech companies because they test BFS/DFS thinking and number manipulation. Variants involving digit constraints or graph-style number generation have been reported in Amazon and Google interview preparation sets.
What data structure is used in Stepping Numbers?
A queue is used for the BFS solution. Each queue element represents a partially built stepping number. By expanding the last digit with ±1 transitions, the queue acts like a graph traversal over valid digit states.
What is the time complexity of Stepping Numbers?
The optimal BFS or DFS generation approach runs in O(k) time, where k is the number of valid stepping numbers within the range. Each generated number is processed once and expanded into at most two new candidates. Space complexity is also O(k) due to the queue or recursion stack.

Ready to solve this problem?

Practice Stepping Numbers with our built-in code editor and test cases.

Practice on FleetCode