Pattern 08 / 10 · Advanced
Heap / Priority Queue
Keep only the k best so far; the weakest of them is always on top.
The idea
A min-heap gives the smallest item in O(1) and adds or removes in O(log k). Push every number, and whenever the heap holds more than k items, pop the smallest. What stays is the k largest, and the top is the k-th largest.
time O(n log k)space O(k)
Reach for it when
- You need the k largest, k smallest or k most frequent items.
- You repeatedly take the smallest or largest item from a changing collection.
- Merging several sorted lists or streams.
Watch it run
215. Kth Largest Element in an Array
Return the k-th largest element in the array (in sorted order, not the k-th distinct).
MediumOpen on LeetCode ↗
Example 1
Input: nums = [3, 2, 1, 5, 6, 4], k = 2
Output: 5
Example 2
Input: nums = [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4
Output: 4
WALKTHROUGH INPUT · nums = [3, 2, 1, 5, 6, 4], k = 2
3
02
11
25
36
44
5heap is empty
k = 2popped = –
Empty min-heap. It will hold at most k = 2 numbers: the 2 largest seen so far.
1function findKthLargest(nums: number[], k: number): number {2const heap = new MinHeap<number>();3for (const num of nums) {4heap.push(num);5if (heap.size() > k) heap.pop();6}7return heap.peek();8}