Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Heaps & Priority Queues/Top-K Elements

Learn the pattern · ~14 min

Top-K Elements

also called priority queue, size-k heap

To find the k largest, keep a min-heap of size k: its root is the weakest survivor, and every new item only has to beat that one.

Signalsk largest/smallest/most frequentrepeatedly pick the max/min while items changestreaming data
Cheat sheet and practice

Reach for it when you read

  • +The k largest / smallest / most frequent / closest items, or the k-th largest.
  • +Items arrive as a stream and you must report the k-th largest after each one.
  • +Merge several sorted lists, or take the next best from sorted rows: a heap of the current heads.
  • +Keep taking the biggest (or smallest) item, change it, put it back: last stone weight, scheduling.

Not this one when

  • ×The max or min of every window of size k: old items must expire by position, so a monotonic deque.
  • ×The median of a stream: two heaps, one per half.
  • ×k is fixed and small, like the top 1 or 2: a single pass with one or two variables.

Learn Top-K Elements

First, what's a heap?

A heap is a container that always knows its smallest item (a min-heap) or its largest (a max-heap). Push 5, 1 and 9 into a min-heap and its top is 1. Pop it, and the top becomes 5. Looking at the top is O(1); a push or a pop is O(log size).

In C++, priority_queue<int> is a max-heap. priority_queue<int, vector<int>, greater<int>> is a min-heap.

Top K keeps the best k items seen so far in a heap of size k.

How do we keep the 3 largest?

Walk [5, 1, 9, 3, 7, 2, 8] with k = 3, using a min-heap. The rule is one line:

Push the number. If the heap now holds more than k, pop its top, the smallest.

number what happens popped heap (smallest first)
5 fewer than 3: keep it 5
1 keep it 1, 5
9 keep it 1, 5, 9
3 four items: pop the smallest 1 3, 5, 9
7 pop the smallest 3 5, 7, 9
2 2 is now the smallest: in and straight out 2 5, 7, 9
8 pop the smallest 5 7, 8, 9

The heap ends with the 3 largest, and its top, 7, is the 3rd largest.

The code for it

C++
priority_queue<int, vector<int>, greater<int>> heap;   // min-heap
for (int x : a) {
    heap.push(x);
    if ((int)heap.size() > k) heap.pop();             // drop the weakest
}
// heap.top() is the k-th largest

You don't need to memorise this. It's the table: push, and pop the smallest when there are too many.

Why a min-heap to keep the largest? The item you need at hand is the one that gets kicked out: the weakest of your keepers. A min-heap puts exactly that one on top. A max-heap would show you 9, the one you're surest to keep.

Fine, but how does this help us?

A classic: Top K Frequent Elements. Return the k most frequent values. Take [3, 1, 3, 2, 1, 3, 4, 1, 3] and k = 2. By hand, count each value:

value where it appears count
3 indices 0, 2, 5, 8 4
1 indices 1, 4, 7 3
2 index 3 1
4 index 6 1

The two biggest counts are 4 and 3, so the answer is {3, 1}.

The brute force

Count, sort every distinct value by its count, take the first k:

C++
vector<int> topKFrequentSort(vector<int>& nums, int k) {
    unordered_map<int, int> cnt;
    for (int x : nums) cnt[x]++;
    vector<pair<int, int>> v;                    // {count, value}
    for (auto& [x, c] : cnt) v.push_back({c, x});
    sort(v.rbegin(), v.rend());                  // biggest count first
    vector<int> out;
    for (int i = 0; i < k; i++) out.push_back(v[i].second);
    return out;
}

That's O(n log n), about 1.7 × 10⁶ steps for n = 10⁵, and it passes here. Where sorting breaks is when the numbers keep coming. Kth Largest Element in a Stream wants the k-th largest after every new number. LeetCode's version starts with up to 10⁴ numbers and adds up to 10⁴ more. Re-sorting after each add took about 0.5 s: slow, though it may scrape through. With 10⁵ adds it took over 20 s. And either way, it puts every value in order when only k of them matter.

The one thought that fixes it

Go back to the first table and stop when 2 arrives. The keepers are 5, 7 and 9.

  • For 2 to be among the 3 largest, it has to beat at least one keeper, so it has to beat the weakest, 5. It doesn't, so it's out.
  • It stays out. A keeper is only ever replaced by something bigger, so the weakest keeper only goes up.
  • Whether 7 comes before or after 9 never mattered. Only the weakest keeper did.

So all you need at hand is the weakest keeper, and that's the top of the min-heap. The heap never holds more than k + 1 items, so each step costs log k, not log n.

For Top K Frequent, rank by count instead of value: run the same heap on {count, value} pairs.

C++
vector<int> topKFrequent(vector<int>& nums, int k) {
    unordered_map<int, int> cnt;
    for (int x : nums) cnt[x]++;                       // rank by count
    using P = pair<int, int>;                          // {count, value}
    priority_queue<P, vector<P>, greater<P>> heap;     // min-heap: weakest count on top
    for (auto& [item, c] : cnt) {
        heap.push({c, item});
        if ((int)heap.size() > k) heap.pop();
    }
    vector<int> out;
    while (!heap.empty()) { out.push_back(heap.top().second); heap.pop(); }
    return out;                                        // weakest first
}

Dry run

The map's order is arbitrary; the result isn't. Say it hands us 1, 2, 3, 4:

value : count what happens popped heap (weakest first)
1 : 3 keep it 1 : 3
2 : 1 keep it 2 : 1, 1 : 3
3 : 4 three items: pop the weakest 2 : 1 1 : 3, 3 : 4
4 : 1 in and straight out 4 : 1 1 : 3, 3 : 4

Output [1, 3]: the same two values as the brute force (any order is accepted).

Why it's O(n log k)

Counting touches each of the n numbers once: O(n). Then each distinct value is pushed once and popped at most once, on a heap of at most k + 1 items: O(log k) each. That's O(n log k) time, and O(n) space for the counts.

From sorting everything to keeping k, by only ever comparing a newcomer with the weakest keeper.

The k smallest? A max-heap

K Closest Points to Origin wants the k smallest distances, so flip the heap: a max-heap, with the farthest keeper on top. Compare squared distances; no square root needed.

C++
priority_queue<pair<int, int>> heap;               // max-heap of {dist², index}
for (int i = 0; i < (int)pts.size(); i++) {
    heap.push({pts[i][0] * pts[i][0] + pts[i][1] * pts[i][1], i});
    if ((int)heap.size() > k) heap.pop();          // drop the farthest
}

For (3, 3), (5, −1), (−2, 4), (1, 1), (0, 2) the squared distances are 18, 26, 20, 2, 4, and with k = 2 the heap keeps (1, 1) and (0, 2).

A stream? Keep the heap in a class

For Kth Largest Element in a Stream, keep the size-k min-heap between calls. Each add is one push, maybe one pop, then return heap.top(): O(log k). With k = 3 and [4, 5, 8, 2], adding 3, 5, 10, 9, 4 returns 4, 5, 5, 8, 8.

Several sorted lists? The next best is a head

Merge k Sorted Lists: [1, 4, 5], [1, 3, 4], [2, 6]. Each list is sorted, so the smallest item left anywhere is one of the heads. Put the heads in a min-heap. Pop the smallest, and push its successor, the only new candidate it unlocks.

C++
ListNode* mergeKLists(vector<ListNode*>& lists) {
    auto cmp = [](ListNode* x, ListNode* y) { return x->val > y->val; };
    priority_queue<ListNode*, vector<ListNode*>, decltype(cmp)> heap(cmp);   // min-heap on val
    for (ListNode* h : lists) if (h) heap.push(h);   // seed with every head
    ListNode dummy, *tail = &dummy;
    while (!heap.empty()) {
        ListNode* cur = heap.top(); heap.pop();
        tail->next = cur; tail = cur;
        if (cur->next) heap.push(cur->next);         // its successor is the new candidate
    }
    return dummy.next;
}

The pops come out 1, 1, 2, 3, 4, 4, 5, 6, and the heap never holds more than 3 nodes.

Remember this

  • k largest → min-heap; k smallest → max-heap. The top is the one that gets kicked out.
  • C++ priority_queue is a max-heap by default; greater<> makes it a min-heap.
  • Rank by something else (a count, a distance)? Push {key, item} pairs.
  • Several sorted inputs? Don't collect everything: the next best is always one of the heads.
  • Whenever a problem asks for the k largest, smallest, most frequent or closest, or the k-th one, it's a heap of size k.

Practise it on Kth Largest Element in an Array, then Kth Largest Element in a Stream (a stream), Top K Frequent Elements (rank by count), K Closest Points to Origin (a max-heap), Last Stone Weight (keep taking the best) and Merge k Sorted Lists (heads of sorted lists).

Below, watch Kth Largest Element in an Array run line by line.

Watch it work, line by line

Kth Largest Element in an Array ↗, a = [5, 1, 9, 2, 8, 3], k = 3 → 5. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.

Loading the walkthrough…

When to use it, and when not

Ask yourself

Do I need only the best k (largest, smallest, most frequent, closest) of many items, or the current best over and over as items arrive?

Reach for it when

  • +k largest/smallest/most frequent
  • +repeatedly pick the max/min while items change
  • +streaming data
  • +k much smaller than n -> O(n log k)

It fails when

  • ×You need everything fully sorted anyway, or k is close to nuse Just sort
  • ×Frequencies or values are bounded small integers (<= n)use Bucket sort by frequency, O(n)
  • ×One k-th element of a static array, and reordering it is fineuse Quickselect, O(n) average
  • ×You need arbitrary deletion or ordered iterationuse Ordered set
  • ×You need a running median, i.e. both halves at onceuse Two heaps
  • ×You think k largest needs a max-heap of all n: that's O(n) space and can't streamuse Size-k min-heap

Looks like it, isn't (and the other way round)

  • Task Scheduler looks like Top-K Elements, needs Greedy

    A heap simulation works, but a counting formula on the max frequency gives O(n).

  • Last Stone Weight II looks like Top-K Elements, needs 0/1 Knapsack

    Its sibling last-stone-weight is a heap simulation, but greedy smashing is not optimal here. Every outcome is |S1 - S2| for some split, so find the subset sum closest to total/2.

Why this pattern and not another

You need the k best (or the k-th) from a large or streaming input without fully sorting. A size-k min-heap maintains exactly those k in O(log k) per element.

Recall card

Answer each one out loud before you open it. Come back in three days and try again without reading the page.

  • 1For the k largest, min-heap or max-heap? Why?Reveal

    A min-heap of size k. Its root is the weakest of the k kept, the one a new value has to beat and the one you pop.

  • 2What does the root of the size-k heap mean when you're done?Reveal

    The k-th best overall: exactly k − 1 kept values are better than it.

  • 3What's the cost, and why is it better than sorting?Reveal

    O(n log k) time and O(k) space, versus O(n log n) and O(n). It also works on a stream.

Practice ladder

every problem →
  1. 1Kth Largest Element in a Streama streamEasy
  2. 2Last Stone Weightkeep taking the bestEasy
  3. 3Kth Largest Element in an Arraythe hookMedium
  4. 4K Closest Points to Origink smallest by a keyMedium
  5. 5Top K Frequent Elementsrank by frequencyMedium
  6. 6Sort Characters By Frequencyrank by frequencyMedium
  7. 7Furthest Building You Can Reachspend on the k biggestMedium
  8. 8Reorganize Stringkeep taking the bestMedium
  9. 9IPOsort by one key, heap on anotherHard

Finished Top-K Elements? Mark it done and Lessgo moves you to the next step.

Start the climb9 steps from E-Rank to S, with a coachPractise itthe cheat sheet and every problem, easy to OA level
Back to Top-K Elements

On this page

The lessonWatch it workThe templateWhen to use itRecallPractice ladder
TodayReviewPatternsProblems

The template: frame and slot · every line explained, then clean C++, Java and Python to revise from

Start the free 7-day trial