Find the kth largest element in a union of 2 max heaps

This question is from the interview:

Find the kth largest element in the union of 2 heaps, given that this kth element appears in both heaps O (k log n).

This is the algorithm I came up with:

While k is not zero
 if(root of max-heap #1 > root of max-heap #2)
 {
    extract-max(heap #1)
 }
 else if(root of max-heap #1 < root of max-heap #2)
 {
    extract-max(heap #2)
 }
 else //case of duplicates
 {
    extract-max(heap #1)
    extract-max(heap #2)
 }
 k--

So, when k = 0, the extract-max function will extract the kth largest.

I think this algorithm will work in O (log n), since the extract-max operation will work in O (log n), and I do it k times.

Is this the right approach? It seems that I did not use this information "this kth element appears in both heaps"? Is there a better approach to using this information?

+4
source share
1 answer

, . , . , , , , k , :

While true
 if(root of max-heap #1 > root of max-heap #2)
 {
    extract-max(heap #1)
 }
 else if(root of max-heap #1 < root of max-heap #2)
 {
    extract-max(heap #2)
 }
 else //case of duplicates
 {
    extract-max(heap #1)
    extract-max(heap #2)
    if (k == 1) {
      break;
    }
 }
 k--

( ) . , , - . , - , extract-max .

0

Source: https://habr.com/ru/post/1542785/


All Articles