I'm reviewing for a final and have stumbled upon the following problem:
Binary heaps have priority queue semantics by default:If we insert some element n times, we need to remove it n times before it “disappears.” Imagine you want to implement binary heaps with set semantics instead. How fast can the insert and remove operations be in this case?
(a) insert: O(n) remove: O(logn)
(b) insert: O(log n) remove: O(n)
(c) insert: O(log n) remove: O(log n)
(d) insert: O(1) remove: O(n2)
(e) None of the above.
To insert into a heap implemented with priority queue semantics, it will be O(logn), and so will the removal. But with sets, insertions and removals depend on many factors of the set itself. What do you think the answer should be?
I would say insert: O(n) remove: O(log n). In a set duplicated item is not allowed and attempt to insert a duplicate item should be ignored and since a heap is a binary tree that is completely filled, (with a exception of the bottom) , If you want to insert to a set you search(item) if you find it you do nothing else insert so insertion may take O(n) for both find and insert (you may percolate up at most log n times). deleteMin has o(log n) time complexity