Numbers With Same Consecutive Differences - Problem
Find All Numbers with Equal Consecutive Digit Differences
Given two integers n and k, your task is to generate all possible integers of exactly n digits where the absolute difference between every two consecutive digits equals k.
For example, if n = 3 and k = 2, then 121 is valid because |1-2| = 1 and |2-1| = 1... wait, that's not right! We need |1-2| = 2, so 131 would be valid instead.
Important constraints:
- No leading zeros allowed (except for single digit numbers when n=1)
- The result can be returned in any order
- Each consecutive pair of digits must have an absolute difference of exactly
k
Examples: If n=2, k=1, valid numbers include: 10, 12, 21, 23, 32, 34, 43, 45, 54, 56, 65, 67, 76, 78, 87, 89, 98
Input & Output
example_1.py โ Basic Case
$
Input:
n = 3, k = 7
โบ
Output:
[181, 292, 707, 818, 929]
๐ก Note:
For n=3 digits with k=7 difference: 181 (|1-8|=7, |8-1|=7), 292 (|2-9|=7, |9-2|=7), etc. Each consecutive pair has exactly difference 7.
example_2.py โ Small Difference
$
Input:
n = 2, k = 1
โบ
Output:
[10, 12, 21, 23, 32, 34, 43, 45, 54, 56, 65, 67, 76, 78, 87, 89, 98]
๐ก Note:
All 2-digit numbers where consecutive digits differ by 1. Like 10 (|1-0|=1), 12 (|1-2|=1), etc.
example_3.py โ Single Digit Edge Case
$
Input:
n = 1, k = 0
โบ
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
๐ก Note:
When n=1, we return all single digits 0-9 regardless of k value, since there are no consecutive digits to compare.
Constraints
- 2 โค n โค 9
- 0 โค k โค 9
- No leading zeros allowed except for single digits when n = 1
Visualization
Tap to expand
Understanding the Visualization
1
Choose Starting Floor
Pick any starting digit from 1-9 (no leading zeros allowed)
2
Calculate Next Steps
From current digit d, you can only go to d+k or d-k (if they're valid digits 0-9)
3
Build Complete Staircase
Continue until you have exactly n steps (digits), then save the complete number
Key Takeaway
๐ฏ Key Insight: At each digit position, we have at most 2 valid choices (current ยฑ k), making backtracking much more efficient than brute force enumeration.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code