Algorithm patterns← All patterns

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).

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
0
2
1
1
2
5
3
6
4
4
5
heap is empty
k = 2popped = –

Empty min-heap. It will hold at most k = 2 numbers: the 2 largest seen so far.

1 / 12
solution.ts
1function findKthLargest(nums: number[], k: number): number {
2 const heap = new MinHeap<number>();
3 for (const num of nums) {
4 heap.push(num);
5 if (heap.size() > k) heap.pop();
6 }
7 return heap.peek();
8}

Practice next