
The first line of input contains an integer ‘T’ denoting the number of test cases. Then each test case follows.
The first line of each test case contains two single space-separated integers ‘N’ and ‘K’ where ‘N’ represents the size (number of rows or columns) of Square City and 'K' denotes the Kth building with minimum floors, respectively.
The next ‘N’ lines of each test case contain ‘N’ single space-separated integers denoting the number of floors in each building.
For each test case, print the number of floors in the ‘K’th’ building with minimum floors.
Print the output of each test case in a separate line.
You are not required to print the expected output; it has already been taken care of. Just implement the function.
1 <= T <= 100
1 <= N <= 100
1 <= K <= N
1 <= Square City[i][j] <= 10^6
where 'Square City[i][j]' denotes the number of floors in a row and column wise sorted matrix 'Square City'.
Time limit: 1 sec
This problem can be solved by storing all the elements in an array of size ‘N * N’ and sort the array and return Kth minimum element
We will store all the elements in an array of size ‘N * N’ and then sort the array. Then we return the Kth element from starting.
The kMinFloor function will return the floors in the building having K’th minimum number of floors.
The algorithm for kMinFloor function will be as follows:
This problem can be solved by storing all the elements in min-heap and removing top ‘K-1’ elements from the heap. Now, the top element in the heap is our required answer.
The main idea behind this approach is that since the ‘Square City’ is sorted in two directions, we can use binary search to find the ‘Kth’ building with minimum floors. As we are searching for the required building, the searching space should be ranging from the smallest to the biggest number in the ‘Square City’. It must be noted that the index here cannot be used to form the searching space since it's not linear to the numbers in the matrix, whose order lies in two directions unlike the index from 0 to the size of array/list in binary search on an array.
Here is the complete Algorithm: