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.
For example, consider the following 2D array.
10, 20, 30, 40 15, 25, 35, 45 24, 29, 37, 48 32, 33, 39, 50 The 3rd smallest element is 20 and 7th smallest element is 30
The idea is to use min heap. Following are detailed step.
1) Build a min heap of elements from first row. A heap entry also stores row number and column number.
2) Do following k times.
…a) Get minimum element (or root) from min heap.
…b) Find row number and column number of the minimum element.
…c) Replace root with the next element from same column and min-heapify the root.
3) Return the last extracted root.
Following is C++ implementation of above algorithm.
7th smallest element is 30
Time Complexity: The above solution involves following steps.
1) Build a min heap which takes O(n) time
2) Heapify k times which takes O(kLogn) time.
Therefore, overall time complexity is O(n + kLogn) 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 first and last positions of an element in a sorted array
- Maximum element in a sorted and rotated array
- Find the element that appears once in a sorted array
- Search an element in a sorted and rotated array
- K'th Smallest/Largest Element in Unsorted Array | Set 1
- Find the minimum element in a sorted and rotated array
- First strictly greater element in a sorted array in Java
- First strictly smaller element in a sorted array in Java
- Python heapq to find K'th smallest element in a 2D array
- Find missing element in a sorted array of consecutive numbers
- Find position of an element in a sorted array of infinite numbers
- Find index of an extra element present in one sorted array
- Find element in a sorted array whose frequency is greater than or equal to n/2.