Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
You must find a solution with a memory complexity better than O(n2).
Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
Output: 13
Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13
Input: matrix = [[-5]], k = 1
Output: -5
Follow up:
O(1) memory complexity)?O(n) time complexity? The solution may be too advanced for an interview but you may find reading this paper fun.The simplest approach to solve this problem is by extracting all the elements from the matrix and placing them into a list. Once we have a list, we can sort it and then directly access the kth smallest element from this sorted list.
To improve upon the brute force sorting solution, we can make use of a min-heap. The idea is to store each element in a min-heap so that we can extract the smallest element efficiently. Since the matrix rows (and columns) are sorted, we start placing elements into the heap one row at a time.
We maintain the heap for at most the size of the matrix's row by column, extract the smallest element from the heap k times, which will give us the kth smallest element.
The row and column sorted property of the matrix allows us to use binary search. We search within the range of the smallest and largest element of the matrix. For each midpoint value, count how many elements are less than or equal to it. Adjust the search range based on this count relative to k.
left to the smallest element and right to the largest element in the matrix.left and right.left up; otherwise, move right down.left contains the kth smallest element.