


‘X’ = { 00, 01, 02, 10, 11, 12, 20, 21, 22 }.
If there are more than one possible such strings, then you can output any of them.
The first line contains an integer 'T' which denotes the number of test cases or queries to be run.
The first line of each test case contains two space-separated integers ‘N’ and ‘K’ representing the number of digits in a number and upper range of possible digits respectively.
For each test case, the output will be 1 if you have returned the correct string, else 0.
The output of each test case will be printed in a separate line.
You do not need to input or print anything, and it has already been taken care of. Just implement the given function.
1 <= T <= 5
1 <= N <= 4
0 <= K <= 9
Where ‘T’ is the total number of test cases, ‘N’ and ‘K’ are the given integers.
Time Limit: 1 sec
We need to find a ‘S’ string that contains all possible permutations of length ‘N’ and allowed characters ‘0’ to ‘K’. So there can be total ‘(K + 1) ^ N’ possible permutations, For example if ‘N’ is 2 and ‘K’ is 1 then total possible permutations are { 00, 01, 10, 11} i.e 2 ^ 2 = 4 total possible. We can simply concatenate each one to find such ‘S’ i.e ‘S’ = “00011011”, but in order to minimise the length of ‘S we need to make sure that every permutation occurs exactly once in the ‘S’. Such strings are made from De Bruijn sequence. We can visualise the given Problem as a directed graph structure where each node represents distinct possible permutations of length ‘N’ and a edge from ‘node1’ to ‘node2’ represents that we can add a digit in range [0, k] to the suffix of length ‘N - 1’ of ‘node1’ to make ‘node2’.
For example for ‘N’ = 2 and ‘K’ = 2, the graph structure will look like below.

Now we just need to find a Hamiltonian Path in the above graph and add the character of edges in the path to the starting string. For example, let's start with ‘00’ and initialize our answer with ‘00’.
We can run a dfs with a backtrack to find such a path.
This is a boolean function that returns true if we find a valid path by traversing an edge, else return false.
The function will take four-parameter:
‘N’: The given length of numbers
‘K’: allowed range of digits
‘answer’: global answer string
‘visited’: A hashmap to keep track of visited nodes.
As we see in the previous approach, the required string can be obtained from the De Bruijn sequence. The idea is to start with ‘N’ 0’s as an initial answer and greedily add digits until we get all the possible permutations. But in order to prevent stuck situations as we see in the example of the previous approach, we need to add digits in a post-order way. i.e starting from ‘K’ to ‘0’. For example ‘N’ = 2 and ‘K’ is 1, and if the previous permutation is ‘01’ then we will first add ‘1’ to get ‘11’ and then add ‘0’.