Given an n x n matrix, where every row and column is sorted in non-decreasing order. Find the kth smallest element in the given 2D array.
Input:k = 3 and array = 10, 20, 30, 40 15, 25, 35, 45 24, 29, 37, 48 32, 33, 39, 50 Ouput: 20 Explanation: The 3rd smallest element is 20 Input:k = 7 and array = 10, 20, 30, 40 15, 25, 35, 45 24, 29, 37, 48 32, 33, 39, 50 Ouput: 30 Explanation: The 7th smallest element is 30
Approach: So the idea is to find the kth minimum element. Each row and each column is sorted. So it can be thought as C sorted lists and the lists have to be merged into a single list, the kth element of the list has to be found out. So the approach is similar, the only difference is when the kth element is found the loop ends.
- The idea is to use min heap. Create a Min-Heap to store the elements
- Traverse the first row from start to end and build a min heap of elements from first row. A heap entry also stores row number and column number.
- Now Run a loop k times to extract min element from heap in each iteration
- Get minimum element (or root) from Min-Heap.
- Find row number and column number of the minimum element.
- Replace root with the next element from same column and min-heapify the root.
- Print the last extracted element, which is the kth minimum element
7th smallest element is 30
- Time Complexity: The above solution involves following steps.
- Building a min-heap which takes O(n) time
- Heapify k times which takes O(k Logn) time.
Therefore, overall time complexity is O(n + kLogn).
- Space Complexity: O(R), where R is the length of a row, as the Min-Heap stores one row at a time.
The above code can be optimized to build a heap of size k when k is smaller than n. In that case, the kth smallest element must be in first k rows and k columns.
We will soon be publishing more efficient algorithms for finding the kth smallest element.
This article is compiled by Ravi Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Last duplicate element in a sorted array
- k-th missing element in sorted array
- Find the element that appears once in a sorted array
- Find first and last positions of an element in a sorted array
- Maximum element in a sorted and rotated array
- Search an element in a sorted and rotated array
- K'th Smallest/Largest Element in Unsorted Array | Set 1
- First strictly greater element in a sorted array in Java
- First strictly smaller element in a sorted array in Java
- Find the minimum element in a sorted and rotated array
- Python heapq to find K'th smallest element in a 2D array
- Count of only repeated element in a sorted array of consecutive elements
- Find element in a sorted array whose frequency is greater than or equal to n/2.
- Find index of an extra element present in one sorted array
- Find missing element in a sorted array of consecutive numbers