You are given a positive integer 'N'. Generate an array 'A' having all integers in range [1, N] exactly once, i.e., array 'A' will be [1, 2, 3, ….., N-1, N]. Your task is to sort array 'A' in lexicographical order.
E.g. If N = 12, array ‘A’ will be [1, 2, 3, ….. 11, 12]. After lexicographical sorting, array ‘A’ becomes [1, 10, 11, 12, 2, 3, 4, 5, 6, 7, 8, 9].
Sort array 'A' into lexicographical order and print the number appearing at K-th position.
The first line contains 'T', denoting the number of tests.
For each Test :
The only line contains two space-separated integers 'N' and 'K'.
Output Format:
For each test, print one integer, denoting the number appearing at K-th position when the array 'A' is sorted in lexicographical order.
Note:
You are not required to print the expected output. It has already been taken care of. Just implement the function.
1 <= 'T' <= 10^3
1 <= 'K' <= 'N' <= 10^9
Time Limit: 1 sec
2
13 2
5 5
10
5
For case 1:
For N = 13, array 'A' is [1, 2, 3, 4, ….., 12, 13]. After lexicographical sorting, array 'A' becomes [1, 10, 11, 12, 13, 2, 3, …. 8, 9] which has number 10 at its second position.
For Case 2:
Before and After sorting, array 'A' remains the same which is [1, 2, 3, 4, 5]. Number 5 appears at 5th position.
2
25 10
17 11
18
3
Do sorting integers and strings are the same?
Approach: Generated array 'A' has all the integers in the range [1….N]. To sort them lexicographically, convert each integer into a string. Applying the sort function on an array of strings will sort the array in lexicographical order. Now, select the string at K-th position, convert it back into an integer, and return it.
Algorithm:
O(N logN), where 'N' is provided in input data and denotes the range of array elements.
Sorting an array of 'N' elements has time complexity O(N logN). Hence overall time complexity becomes O(N logN).
O(N), where 'N' is provided in input data and denotes the range of array elements.
An array of size 'N' is created. Hence overall space complexity becomes O(N).