

Input: N = 2, K = 6
We need to return all two-digit numbers where the absolute difference between each consecutive digit is ‘6’. Note that ‘06’ is not a valid two-digit number. So, the answer is:
Output: [17, 28, 39, 60, 71, 82, 93]
1. Every number in the answer should not contain leading zeroes. E.g., the number ‘09’ is invalid.
2. You can return the answer in any order.
The first line of input contains an integer ‘T’ which denotes the number of test cases. Then, the ‘T’ test cases follow.
The first and only line of each test case contains two space-separated integers, ‘N’ and ‘K’, denoting the number of digits and the absolute difference between each consecutive digit.
For every test case, return an array of integers where each integer has ‘N’ digits, and the absolute difference between each digit is ‘K’. You may return output in any order, but the printed output will be in sorted order.
You do not need to print anything; it has already been taken care of. Just implement the function.
1 <= T <= 100
2 <= N <= 9
0 <= K <= 9
Time limit: 1 sec
Let’s first try to find the numbers having ‘4’ as the most significant digit (MSD). We create a tree where each node stores an integer ‘N-i’ and the least significant digit (LSD) of ‘N-i’. Initially, the tree contains a single node, i.e., the root node with an integer ‘4’ and its LSD ‘4’. We append a new digit to the previous level until we reach 'N' levels. There are two ways to add a new digit to a child node,i.e., ‘LSD of parent node + K’ and ‘LSD of parent node - K’ (Note: For ‘K = 0’ both these values are the same, so there can only be one child). If the LSD of the new node is not between [0, 9], mark this node invalid to produce any child nodes. Following is a partial tree for ‘4’:

Similarly, solve for numbers having MSD as [1 to 9]. We can do a Breadth-first search (BFS) traversal of the tree to get the leaf nodes. Following are the steps for BFS:
We can do a Depth-first search (DFS) traversal of the tree created in the previous approach. A recursive implementation of DFS will require a stack size equal to the tree’s height,i.e., ‘N’. Thus, requiring less memory compared to BFS. Following are the steps for DFS:
Function ‘DFS(integer N, integer K, integer NUM, array RESULT)’ for recursive tree traversal:
Sorted Doubly Linked List to Balanced BST
Longest Substring with K-Repeating Characters
Expression Add Operators
Gray Code Transformation
Count of Subsequences with Given Sum