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 INPUT n = 3 (digits) k = 7 (diff) BFS Starting Queue 1 2 3 4 5 6 7 8 9 No leading zeros! Start with 1-9 only Consecutive digit diff = k |digit[i] - digit[i+1]| = 7 Valid pairs: (1,8), (2,9), (7,0), (8,1), (9,2) ALGORITHM (BFS) 1 Initialize Queue Add digits 1-9 to queue 2 Process Level Pop number from queue 3 Extend Number Add digit with diff k 4 Check Length If len=n, add to result BFS Tree Example (digit 1): 1 18 1+7=8 181 8-7=1 OK - Length 3! FINAL RESULT All valid 3-digit numbers: 181 292 707 818 929 Digit Difference Verification: 181: |1-8|=7, |8-1|=7 292: |2-9|=7, |9-2|=7 707: |7-0|=7, |0-7|=7 818: |8-1|=7, |1-8|=7 929: |9-2|=7, |2-9|=7 [181,292,707,818,929] OK - 5 valid numbers found Key Insight: BFS explores numbers level-by-level, where each level adds one digit. Starting from single digits 1-9, we extend each number by appending a digit that differs by exactly k from the last digit. For each last digit d, valid next digits are d+k and d-k (if within 0-9). When length reaches n, add to result. TutorialsPoint - Numbers With Same Consecutive Differences | BFS Approach
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