Medium Heaps

Top-K Elements

Finds the k largest values in an array using a min-heap bounded to size k: each value is pushed onto the heap, and once the heap holds more than k elements the smallest is popped off, so by the end the heap holds exactly the k largest values seen. Runs in O(n log k), much faster than sorting the whole array when k is small. Receives an array of integers and a target k, and returns the k largest values in descending order.

Visualization

Input

Algorithm code

Custom input

Saved inputs

References