1

Consider two min-heaps H1,H2 of size n1 and n2 respectively, such that every node in H2 is greater than every node of H1.

How can I merge this two heaps into one heap "H" , in O(n2) (not O(n^2)..)?
(Assume that the heaps represented in arrays of size > n1+n2)

Steve P
  • 168
  • 1
  • 11
user2637293
  • 333
  • 4
  • 16
  • 1
    Hint: If instead you had two sorted lists L1 and L2, with every element of L2 greater than every element of L1, how could you merge them into a single sorted list in O(n) (=O(n2)) time? A heap is a bit like a sorted list that gets wider at the end; what might a corresponding action look like on two heaps? – j_random_hacker May 21 '14 at 12:34
  • 1
    @otus why delete the answer? It seems to fit the constraints. – Niklas B. May 21 '14 at 12:53

1 Answers1

4

A heap can be constucted in linear time see here. This means you need only take all elements and construct a heap from all the elements to get linear complexity. However you can use a "more fancy" heap for instance leftist heap and perform the merge operation even faster.

Community
  • 1
  • 1
Ivaylo Strandjev
  • 64,309
  • 15
  • 111
  • 164