This question is from an interview:
Find kth largest element in the union of 2 max heaps given that this kth element appears in both heaps in O(k log n).
This is the algorithm that I come 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 that this algorithm will run in O(k log n) time since the extract-max operation will run in O(log n) and I perform it k times.
Is this the right approach? It seems that I have not used the given info "this kth element appears in both heaps"? Is there a better approach utilizing this info?