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
{
extract-max(heap
}
else if(root of max-heap
{
extract-max(heap
}
else //case of duplicates
{
extract-max(heap
extract-max(heap
}
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?
source
share