Generate N-Digit Codes Whose Adjacent Digits Differ by K
Last updated: November 29, 2026
Quick Overview
Generate every n-digit number with no leading zero in which every pair of adjacent digits differs by exactly k. Return them in ascending order.
0
0
0 solved
Generate every n-digit number with no leading zero in which every pair of adjacent digits differs by exactly k. Return them in ascending order.
A short Google online assessment problem. The grader checks a simple digit-by-digit DFS, correct handling of k = 0 (to avoid duplicates), and no leading zeros.
What the Interviewer Expects
- Builds numbers digit by digit from a non-zero first digit
- Branches to last + k and last - k when they are valid digits
- Avoids generating duplicates when k = 0
- States the output bound of at most 9 * 2^(n-1)
- Returns results sorted
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you count these codes for n = 50 without listing them?
- How would you allow the first digit to be zero for PIN codes?
- Write the BFS version that extends all numbers one digit per level.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input: n (2 to 9) and k (0 to 9).
- Output: all n-digit integers with no leading zero and |d[i] - d[i+1]| = k for every adjacent pair, sorted ascending.
- Example: n = 3, k = 7 gives 181, 292, 707, ...
High-Level Design
Start from each first digit 1..9. From the last digit d, the next digit can be d + k or d - k, if it lies in 0..9. When k = 0 both options are the same digit, so use a set of next digits to avoi...