### Problem

Given the 2D matrix or array - sorted row-wise and column-wise, find the kth largest element.

### Example

**Input**

Consider the array below and k=4

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

**Output**

Output should be 22

### Solution

**Method 1 - Use MaxHeaps**

We know if k=1, we should return A[n-1][n-1] i.e. the last element of the array. So, we have to give the kth largest, so we have to start from the end of the array, and keep on selecting the max element adjacent to the last one, and maintain the history of max elements, once we traverse to the next element.

Here is how we should go:

- Create a max-heap
- Insert the last element of each row in the heap and do heapify for each inserted element
- Repeat steps 5,6&7 for k-1 times then go to step-8
- Extract-max element from the heap
- Insert the elements adjacent to the current element, (and do heapify) from the row to which the extracted element corresponds to..
- Heapify for newly inserted element
- Now Extract the largest element from the heap and this will be the required answer, number of elements extracted are equal to k.

Push A[n-1][n-1] in the heap. for i = 1 to k curr_element = pop max element from heap Push the right and bottom neighbor of the popped element from the matrix (if they exist and have not been pushed earlier) return curr_element

Time complexity = loop runs k times (O(k)) * 1 iteration runs O(3*log(k)) times =

**O(k*log(k))**

**References**

## 0 comments:

## Post a Comment