Given a row-wise and column-wise sorted square matrix and a positive integer k, find the kth smallest number in the matrix.

For example,

Input:
mat = [
    [-3, 1, 3],
    [-2, 2, 4],
    [1, 3, 5]
]
k = 6
Output: 3
Explanation: The elements of the matrix in increasing order, are [-3, -2, 1, 1, 2, 3, 3, 4, 5]. The sixth smallest element is 3.
 
Input:
mat = [
    [1, 3],
    [2, 4]
]
k = 5
Output: None
Explanation: k is more than the number of elements in the matrix.

1. Using Min Heap

The idea is to build a min-heap from all the elements of the first row. Then, start a loop where, in each iteration, we remove the root from the min-heap and replace it with the next element from the same column of the matrix. After k pop operations have been done on the min-heap, the last popped element contains the kth smallest element.

 
The algorithm can be implemented as follows in C++, Java, and Python. Note that we can also build the min-heap from elements of the first column and replace the root with the next element from the same row of the matrix. The remaining logic remains the same.

C++


Download  Run Code

Output:

3

Java


Download  Run Code

Output:

3

Python


Download  Run Code

Output:

3

The time complexity of the above solution is O(N2) for an N × N matrix and requires O(k) extra space for heap data structure.

2. Using Binary Search

We can avoid using the extra space by using the binary search algorithm. The binary search typically works with a linear data structure that is sorted, we can modify it to work with a matrix that is sorted both row-wise and column-wise. We start with the search space [low, high] where low and high initially point to the top-left and bottom-right corners of the matrix, respectively. Then, at each iteration of the binary search loop, we determine the mid-value and count the elements in the matrix that are less than or equal to the mid-element. We narrow the search space to [mid+1…high] if the count is less than k; otherwise, we narrow it to [low…mid-1]. The loop terminates as soon as low surpasses high, and low stores the kth smallest value in the matrix.

 
Following is the C++, Java, and Python implementation based on the idea:

C++


Download  Run Code

Output:

3

Java


Download  Run Code

Output:

3

Python


Download  Run Code

Output:

3

The time complexity of the above solution is O(N.log(N2)) for an N × N matrix and doesn’t require any extra space.