In a heap with n elements with the smallest element at the root, the 7th…
2003
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)
- B.
Θ(n)
- C.
Θ(log n)
- D.
Θ(1)
Attempted by 421 students.
Show answer & explanation
Correct answer: D
Key idea: explore only the nodes near the root using a small auxiliary min-heap of candidate nodes.
Initialize an auxiliary min-heap and insert the root of the given min-heap (the smallest element).
Repeat the following k−1 times (here k = 7, so repeat 6 times): extract the minimum element from the auxiliary heap and insert its children from the original heap (if they exist) into the auxiliary heap.
After these extractions, the minimum element remaining at the root of the auxiliary heap is the k-th (7th) smallest element.
Time complexity: each heap operation on the auxiliary heap costs O(log k), and we do O(k) operations overall, so the total time is O(k log k).
Conclusion: for k = 7 this is O(7 log 7), which is Θ(1) with respect to n, so the 7th smallest element can be found in Θ(1) time (treating k as a constant).
A video solution is available for this question — log in and enroll to watch it.