Skip to content
DSA in JavaScript
← All patterns

Top K Elements

0/16 solved

What it is

Keep a small heap of size k while scanning the data. The heap root is always the weakest of your current top k, so it is the one to replace.

Used for

K largest or smallest items, K most frequent, merging sorted lists, running median.
nums
5
1
9
3
7
2
club
·
·
·

Step 1 of 6

Goal: find the 3 biggest numbers. Sorting everything works but does more than needed. Instead keep a small club of the best 3 so far and always know its weakest member, the first to be kicked out. (A min-heap gives you the weakest in one step.)

You see

  • K largest, smallest or most frequent
  • Merge k sorted inputs
  • Running median
  • You repeatedly need the current min or max

Learn it in

k-Nearest Neighbors AlgorithmHeap (data-structure)Priority QueueHeap Sort

Template

// Keep a min-heap of size k: its root is the kth largest.// JS has no built-in heap, so use MinHeap from the Heap topic.function kthLargest(nums, k, MinHeap) {  const h = new MinHeap();  for (const n of nums) { h.add(n); if (h.heapContainer.length > k) h.poll(); }  return h.peek();}

Practice problems