Numbers With Same Consecutive Differences - Problem

Given two integers n and k, return an array of all the integers of length n where the difference between every two consecutive digits is k.

You may return the answer in any order.

Note: The integers should not have leading zeros. Integers as 02 and 043 are not allowed.

Input & Output

Example 1 — Basic Case
$ Input: n = 3, k = 7
Output: [181,292,707,818,929]
💡 Note: For 3-digit numbers with consecutive difference 7: 181 (|8-1|=7, |1-8|=7), 292 (|9-2|=7, |2-9|=7), etc.
Example 2 — Single Digit
$ Input: n = 1, k = 3
Output: [0,1,2,3,4,5,6,7,8,9]
💡 Note: For single digits, all digits 0-9 are valid since there are no consecutive pairs to check.
Example 3 — 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: 2-digit numbers where consecutive digits differ by 1: 10 (|1-0|=1), 12 (|1-2|=1), etc.

Constraints

  • 1 ≤ n ≤ 8
  • 0 ≤ k ≤ 9

Visualization

Tap to expand
Numbers With Same Consecutive Differences (n=3, k=7)Inputn = 3Lengthk = 7DifferenceProcess181|8-1|=7 ✓|1-8|=7 ✓292|9-2|=7 ✓|2-9|=7 ✓Output[181, 292, 707, 818, 929]All valid 3-digitnumbers🎯 Key Insight: Each digit has at most 2 valid next digits (±k)
Understanding the Visualization
1
Input
Given n=3 (length) and k=7 (difference)
2
Process
Build numbers where |digit[i+1] - digit[i]| = k
3
Output
All valid n-digit numbers
Key Takeaway
🎯 Key Insight: Each digit constrains the next digit to exactly two possibilities: current ± k
Asked in
Google 15 Facebook 12 Amazon 8 Microsoft 6
35.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen