


The first and only line of input contains a single integer N.
The only line of output contains N single space-separated integers i.e integers from 1 to N in lexicographical order.
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= N <=10^6
Time Limit: 1 sec
In this approach, we will use recursion to generate all integers from 1 to N in a lexicographically ascending order. We will first initialize an empty list to store the integers. Now we will first fix the first digit of the numbers and then call recursion to generate the next possible digits. So, we will call our recursive function nine times for i = 1 to 9(possible digits for the leftmost most digit in any of the integers from 1 to N. The recursive algorithm is explained below.
N denotes the given integer.
CUR denotes the current number generated till now using recursion.
The list denotes the output list to return which will contain the integers from 1 to N in lexicographically sorted order.
void function(N, CUR, LIST):
Let N = 23, the recursion calls for this example are shown below:-
Similarly, we will call 3, 4, .. and 9 and generate all possible numbers.
Let, N = 22, initialize CURRENT with 1, CURRENT = 1 and add it to the list, A= [1]
Keep adding trailing zeros to current until CURRENT <= N
CURRENT = 10, A = [1, 10]
CURRENT = 100, we won’t add this to array A as it is greater than N. Going back to the previous current element i.e CURRENT= CURRENT/10. CURRENT =10
Note: The lexicographically sorted numbers that will follow 10 will be all the numbers greater than 10 having the same prefix i.e we need to change only the last digit. For example:
CURRENT = 11 (10+1), A= [1, 10, 11]
CURRENT = 12, A= [1, 10, 11, 12]
Similarly, adding 13, 14, 15, .. 19 and A= [1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Now, CURRENT(19) + 1 =20 but the next lexicographically greater number after 19 is 2 rather than 20. It must be noted that earlier the prefix was ‘1’ and all the numbers with prefix ‘1’ that were less than N+1 have been added to A. The new prefix will be existing CURRENT without trailing zeroes.
For example:
Now, CURRENT = 2, A= [1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2]
Adding trailing zeroes and repeating steps as done for 1.
CURRENT = 20, A= [1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20]
Adding all numbers with prefix 2 but less than 23 one by one will give
A= [1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 22]