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
Number Staircase: n=4, k=21Start31+253+275+2+2+2+2Result: 13571-2Invalid!< 03-2Valid!= 1At each step: try current ยฑ k (if valid)
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.
Asked in
Meta 42 Google 35 Amazon 28 Microsoft 21
67.4K Views
Medium-High Frequency
~15 min Avg. Time
1.9K 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