In a heap with n elements with the smallest element at the root, the 7th smallest element can be found in time
(A) Θ(n log n)
(C) Θ(log n)
In order to find out the kth smallest element, we have to first extract 6 elements from heap and then root of the resultant heap will be the kth smallest.Total time complexity = 6 Extract-min operations = 6*log2n = O(log2n)
But we can find out kth smallest from heap using a clever approach by extracting elements from heap non-destructively. We will use extra space to create a new min-heap which will contain maximum k elements at any time.
Initialize the root element of new-heap with the root of old heap (minimum element)
For k-1 times repeat the following :
Extract the root of the new min-heap using extract-min and insert the 2 children of the extracted root from the original heap into the new heap. Resulting heap will contain k elements and root of which will be our kth smallest in the original heap. This grows the new heap by one on every removal (remove one, add two), which means it will never hold more than K elements, and so the remove-one-add-two will take O(3*log(K)). After k iterations, it is O(3*k*logk) = O(k*logk).
In order to implement this, Nodes in the new heap should store indexes of their corresponding nodes in the original heap, rather than the node values themselves.
For 7 elements, it will take 7log7 = O(1) time as new heap will create only 7 elements.
See question 1 of https://www.geeksforgeeks.org/data-structures-and-algorithms-set-9/
This solution is contributed by Pranjul Ahujka
Quiz of this Question
Attention reader! Don’t stop learning now. Learn all GATE CS concepts with Free Live Classes on our youtube channel.