![]() |
VOOZH | about |
Given an n à n matrix mat[][] where each row and column is sorted in non-decreasing order, find the kth smallest element, where k lies in the range [1, n²].
Example:
Input: mat[][] = [[10, 20, 30, 40], k = 3
[15, 25, 35, 45],
[24, 29, 37, 48],
[32, 33, 39, 50]]
Output: 20
Explanation: The sorted order is [10, 15, 20, ...]; the 3rd element is 20.Input: mat[][] = [[10, 20, 30, 40], k = 7
[15, 25, 35, 45],
[24, 29, 37, 48],
[32, 33, 39, 50]]
Output: 30
Explanation: The sorted order is [10, 15, 20, 24, 25, 29, 30, ...]; the 7th element is 30.
Table of Content
Initialize a 1-dimensional array of size n*n to store all the elements of the mat[][] , we will get our kth minimum element by sorting the 1-dimensional array in non-decreasing order.
20
The idea is to use a max-heap to store and maintain the track of k smallest elements in the heap. If the size of the heap exceeds more than k while inserting the elements , we will pop the top element from max-heap so as to maintain the size of k elements. After successful traversal in mat[][], the top element of the max-heap will be the kth minimum element.
20
This approach uses binary search to iterate over possible solutions. As answer lies in the range from mat[0][0] to mat[n-1][n-1], So we do a binary search on this range and in each iteration determine the no of elements smaller than or equal to our current middle element.
Step by Step Implementation:
20
Time Complexity: O(n Ć log(max(mat) ā min(mat))), Binary search is applied over the value range of the matrix, which takes log(max(mat) ā min(mat)) steps. Each step calls a counting function that runs in O(n) time by scanning from top-right to bottom-left.
Auxiliary Space: O(1), The algorithm uses only fixed variables and no extra data structures, so space usage is constant.