Skip to interview prep
Apexed

200. How do you list the k largest elements of a max-heap?

MediumPriority queues & heaps

Technical
Show model answer

Popping k times gives them in descending order in O(k log n) but modifies the heap. The non-destructive version mirrors the kth-smallest trick: an auxiliary max-heap of (value, index) seeded with the root; each pop emits a value and pushes that node's children. Total O(k log k) time and O(k) space.

If order does not matter, a pruned traversal is not enough on its own because you do not know the threshold value in advance, so the auxiliary heap is the standard answer.

How do you list the k largest elements of a max-heap — Data structures & algorithms interview question — Apexed