You are given an array/list ‘ARR’ consisting of ‘N’ non - negative integers and an integer ‘K’. Your task is to return the K-th smallest element of the array.
For example :-
Given an array/list ‘ARR' = [ 3, 2, 4, 5, 6 ] and 'K' = 3. The 3rd smallest element is "4" because the order of numbers is [ 2, 3, 4, 5, 6 ].
The first line of input contains an integer ‘T’ denoting the number of test cases. The next ‘T’ lines represent the ‘T’ test cases.
The first line of input contains two space-separated integers ‘N’ and ‘K’.
The second line of input contains the ‘N’ space-separated integer which denotes the element of array ‘ARR’.
Output Format:
For every test case, print the ‘K-th’ smallest element in the array 'ARR'.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
Constraint :
1 <= T <= 100
1 <= K <= N <= 5000
-10^9 <= ARR[i] <= 10^9
Where ‘T’ represents the number of test cases, ‘N’ is the number of elements in array ‘ARR’ , ‘K’ denotes an integer. ‘ARR[i]’ represents the value of the number at ‘i’ position in ‘ARR’.
Time Limit: 1 sec
2
5 2
4 5 3 7 6
6 3
5 2 1 4 3 6
4
3
In the first test case, ‘ARR' = [ 4, 5, 3, 7, 6 ] and ‘K' = 2. Then 2nd smallest element is ‘4’ because the order of numbers is [ 3, 4, 5, 6, 7].
In the second test case, ‘ARR’ = [ 5, 2, 1, 4, 3, 6 ] and ‘K’ = 3. Then 3rd smallest element is ‘3’ because the order of numbers is [ 1, 2, 3, 4, 5, 6 ].
2
3 2
-1 -2 6
4 4
4 5 2 1
-1
5
In the first test case, ‘ARR' = [ -1, -2, 6 ] and ‘K' = 2. Then the 2nd smallest element is ‘-1’ because the order of numbers is [ -2, -1, 6].
In the second test case, ‘ARR’ = [ 4, 5, 2, 1] and ‘K’ = 4. Then the 4th smallest element is ‘5’ because the order of numbers is [ 1, 2, 4, 5 ].
Can we use sorting to solve this problem?
Approach: The key idea is to sort the whole array in ascending order. The smallest element will be at index ‘0’ and the second smallest element at index ‘1’ and likewise, the ‘K’th smallest element will be at the ‘K - 1’th index.
The algorithm will be-
O(N*log(N)), Where ‘N’ is the number of elements in array ‘ARR’.
The time complexity due to sorting will be O(N * log(N)).
O(1), We are using constant space.