Numbers With Same Consecutive Differences

MediumBacktrackingbacktracking

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given integers n and k, find every n-digit non-negative integer in which the absolute difference between each pair of adjacent digits is exactly k. Numbers must not have leading zeros (so every result has exactly n digits and is at least 10^(n-1)). Return the numbers sorted in **ascending** order, with no duplicates.

Examples

Input: n = 3, k = 7
Output: [181,292,707,818,929]
Each adjacent pair differs by 7; numbers like 070 are excluded because of the leading zero.
Input: n = 2, k = 1
Output: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]
All two-digit numbers whose digits differ by exactly 1.

Constraints

  • `2 <= n <= 9`
  • `0 <= k <= 9`

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More backtracking problems