-1

Assume that you are implementing a priority queue PQ that returns the max element on dequeue operation. If we use a max heap to implement the PQ, enqueue is O(______) operation, and dequeue is O(_____) operation

Could someone please answer/explain how you got it...I am thinking log n for both but not sure?

1 Answers1

0

Think of how a binary heap works.

When you insert an item, you add it as the last node of the heap and then sift it up into its proper place. Since a heap that contains n items has a height of log(n), and you might have to sift the item all the way to the top, the worst case is O(log n).

When you remove an item, you replace the root note with the last node in the heap, and then you sift it down. Worst case, you'll have to sift it all the way back down to the bottom of the heap: a move of log(n) levels. Therefore, O(log n).

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351