Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting a node from the middle of a heap

Deleting a node from the middle of the heap can be done in O(lg n) provided we can find the element in the heap in constant time. Suppose the node of a heap contains id as its field. Now if we provide the id, how can we delete the node in O(lg n) time ?

One solution can be that we can have a address of a location in each node, where we maintain the index of the node in the heap. This array would be ordered by node ids. This requires additional array to be maintained though. Is there any other good method to achieve the same.

PS: I came across this problem while implementing Djikstra's Shortest Path algorithm.

like image 986
Jonh Avatar asked Nov 04 '22 15:11

Jonh


1 Answers

The index (id, node) can be maintained separately in a hashtable which has O(1) lookup complexity (on average). The overall complexity then remains O(log n).

like image 157
Candide Avatar answered Nov 09 '22 05:11

Candide