Question
An operator delete(i) for a binary heap data structure is to be designed to delete the item in the -th node. Assume that the heap is implemented in an array and refers to the -th index of the array. If the heap tree has depth (number of edges on the path from the root to the farthest leaf), then what is the time complexity to re-fix the heap efficiently after the removal of the element?
Official answer and solution
- Official answer
- B
- From
- Official GATE 2016 answer key
Solution
Analyze the heap deletion algorithm by swapping with the last leaf and applying heapify.
In a binary heap of depth stored in an array, deleting the item at index is performed as follows:
- Replace the element at index with the last element of the heap (the rightmost leaf at the bottom level).
- Decrease the heap size by 1.
- The newly placed element may violate the heap ordering property in one of two directions:
- If the element is smaller (in a max-heap) than its parent, it must bubble down using
heapify-down(orsift-down). In the worst case, it traverses a path down to a leaf, taking at most comparisons and swaps. - If the element is larger (in a max-heap) than its parent, it must bubble up using
heapify-up(orsift-up). In the worst case, it traverses a path up to the root, taking at most comparisons and swaps.
- If the element is smaller (in a max-heap) than its parent, it must bubble down using
In either case, restoring the heap property takes at most time. Since it requires traversing tree levels and cannot be done in time in the worst case, the time complexity is but not .
B
Confusing the number of tree levels with the number of nodes , which would give .
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2016 Computer Science and Information Technology (CS) Session 1
- Question
- 47 of 65, printed as CS Q.37
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.