Problem Description
Given two integers n and k, return an array of all n-digit integers such that the absolute difference between every two consecutive digits equals k. Note that integers with leading zeros are not allowed.
Key Insights
- Start constructing numbers from digits 1 through 9 to avoid leading zeros.
- Use backtracking (or BFS) to add one digit at a time, ensuring the difference between consecutive digits equals k.
- At each step, explore the two possible next digits: current_digit + k and current_digit - k (if within bounds 0 to 9).
- Handle the edge case when k is 0, as it does not produce two distinct possibilities.
Space and Time Complexity
Time Complexity: O(2^(n)) in the worst case, as each number can branch into up to 2 choices for each new digit. Space Complexity: O(n) due to recursion depth (or queue depth in a BFS approach) along with the space needed for the output.
Solution
We solve the problem using a backtracking approach. The idea is to build each valid n-digit number digit by digit, starting from a non-zero digit. At each step, we look at the last digit and calculate the possible next digits using the rule: next_digit = last_digit ± k. We add the new digit if it is within the range [0, 9] and continue until the number reaches length n. If k equals 0, then both options yield the same digit so we only need to add one. The built number is then added to the results once the required length is reached.