Numbers with consecutive difference 1
Filed under Amazon
Free read 1 of 3Confirm if single-digit numbers are included (they are, as they have no adjacent digits to violate the rule).
The question
Given a range [m, n], find all integers where the absolute difference between every pair of adjacent digits is exactly 1.
Constraints
- 1 <= m <= n <= 10^9
- Numbers must be positive integers
Examples
- Input
- m=10, n=20
- Output
- [10, 12, 21]
- Why
- 10: |1-0|=1; 12: |1-2|=1; 21: |2-1|=1.
Approach
Confirm if single-digit numbers are included (they are, as they have no adjacent digits to violate the rule).
Iterate from m to n, convert each to string, and check adjacent digit differences.
Use DFS to generate valid numbers by appending digits (d-1 or d+1) to the current digit until the number exceeds n.
Handle single-digit numbers and numbers containing zero correctly.
Tips
- What they are testing: Tests edge cases like single-digit numbers (always valid) and large ranges.
- Common mistake: Using string conversion for every number in the range, which is inefficient for large n.
Related Amazon questions
Collected from public candidate posts and coding forums. Updated Nov 2026.