Problem title
Difficulty
Avg time to solve

Distribution of Money
Easy
15 mins
Letter Case Permutation
Moderate
15 mins
Product of the Last K Numbers
Easy
15 mins
Kevin And The Number On A Dice
Easy
10 mins
Digit Count In Range
Moderate
25 mins
Maximum Distinct Blocks
Easy
10 mins
Flatten 2D array
Easy
20 mins
Nearest Pallindrome
Moderate
30 mins
Find a Corresponding Node of a Binary Tree in a Clone of That Tree
Easy
20 mins
MaxFrequencyStack
Hard
45 mins

Kth Smallest Element

Difficulty: MEDIUM
Contributed By

Problem Statement

You are given a square matrix ‘NxN’ rows and columns. The matrix is sorted, meaning all rows and columns of the matrix are sorted in ascending order. You are also given an integer ‘K’, and your task is to find the ‘K’th smallest element in the sorted order.

For example:
You are given ‘mat’ = [[1, 2, 2,], [3, 3, 4], [5, 6 ,7]]] and ‘K’ = 5, the elements of the matrix are [1, 2, 2, 3, 3, 4, 5, 6, 7], the 5th smallest element in the matrix is 3. Hence the answer is 3.
Input Format:
The first line of input contains a single integer ‘T’ representing the number of test cases.

The first line of each test case contains two space-separated integers, ‘N’ and ‘K’, representing the order of the square matrix given and the integer given.

The following ‘N’ lines contain ‘N’ space-separated integers representing a row of the matrix.
Output Format:
For each test case, print a single integer representing the ‘K’ the smallest element in the sorted matrix.
Constraints:
1 <= T <= 10
1 <= N <= 10^3
1 <= |mat[i][j]| <= 10^4

Time Limit: 1 sec
Note :
You do not need to print anything. It has already been taken care of. Just implement the given function. 
Sample Input 1:
2
3 5
1 2 2
3 3 4
5 6 7
2 2
1 2
3 4
Sample Output 2:
3
2
Explanation:
For the first test case, ‘mat’ = [[1, 2, 2,], [3, 3, 4], [5, 6 ,7]]] and ‘K’ = 5, the elements of the matrix are [1, 2, 2, 3, 3, 4, 5, 6, 7], the 5th smallest element in the matrix is 3. Hence the answer is 3.

For the second test case,  ‘mat’ = [[1, 2], [3, 4]] and ‘K’ = 2, the elements of the matrix are [1, 2, 3, 4], the 2nd smallest element in the matrix is 2. Hence the answer is 2.
Sample Input 2:
2
1 1
1 
3 3
1 2 5
1 2 11
12 13 14
Sample Output 2:
1
2
Reset Code
Full screen
copy-code
Console