Heap / Top K
Advanced · 11 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A heap is a structure that always hands you the smallest (or biggest) item quickly. For "top K" questions you keep a small heap of only K items, so you never need to sort the whole data.
Practical use cases
- Web app: Top 10 trending hashtags. A social app shows the 10 hottest hashtags from millions of posts. Sorting every tag is wasteful. Keeping a small group of 10 and kicking out the weakest each time a stronger tag arrives gives the list in one pass, with memory for only 10 tags instead of millions.
- Web app: Nearest 5 restaurants. A food-delivery app needs the 5 closest restaurants out of 20,000. A heap of size 5 holds the best so far, and each new restaurant either replaces the farthest of them or is skipped. The app shows the closest five restaurants quickly, without sorting all 20,000 restaurants for each customer.
- Web app: Leaderboard of top players. A game site shows the top 100 scores of the day from a stream of results, without storing and sorting every score. The leaderboard stays current all day, because each score only has to beat the weakest of the top 100.
- System: Log analysis. Operations tools find the 20 slowest requests or the most common errors in billions of log lines while keeping just 20 items in memory. The list is ready after a single pass over the data.
The story: The Top Two Snacks of the Canteen
The school canteen sold hundreds of snacks a day: vada, jalebi, chai, samosa. Mrs. Sharma wanted to print a board of the top 2 best-sellers. Kabir counted every item and then wrote all the counts on cards and sorted the whole pile of cards, though there were only 4 kinds of snacks. Later, at the big mela, there were 4,000 kinds of snacks. Sorting 4,000 cards just to show 2 felt silly.
Mira heard the clue words: "top k", "k most frequent", "k largest", "k closest", "k-th best". And k is much smaller than the pile. "Don't sort everything," she said. "Hold a small podium with only k places. When a new snack comes in, put it on the podium. If the podium has too many people, the weakest one steps down."
To find the weakest quickly, the podium is a min-heap: the smallest item is always on top, and kicking it out is cheap. After going through all the snacks, whoever is still on the podium is the answer.
The big idea is a small heap of size k guarding the top. That beats sorting when k is small, and it works on a never-ending stream too.
How to spot this problem, and where you need it
You only need the best few items (top 10, nearest 5, slowest 20) from a large collection, and fully sorting everything feels like too much work.
Signs you need it
- The wording is "top K", "K largest", "K closest", "most frequent K" or "trending".
- You call sort() on a huge list and then take the first few items.
- Data arrives continuously and the list of best items must stay current.
Where to use it in a project
- Trending, popular and recommended lists on feeds, shops and news sites.
- Nearest-place searches in maps and delivery apps that show only a handful of results.
- Leaderboards and log reports that show only the worst or best few items.
The solution
Keep a heap that holds at most K items, arranged so the weakest of them is on top. For each new item, if the heap has fewer than K items, add it. Otherwise compare with the weakest on top: if the new item is better, swap it in, else ignore it. At the end the heap holds the K winners. Each item costs only a tiny heap adjustment.
Payoff: Before: sorting 5 million items. After: one pass with a heap of 10 items.
Explain it like I am 8
There is a podium with only two places. Each new runner steps on; if there are three people, the slowest of the three steps off. At the end the two on the podium are the winners. You never needed to line up all the runners in order.
How it works, step by step
- Clues: "top k", "k-th largest", "k most frequent", "k nearest", "stream of data". Think heap.
- First prepare scores if needed (here: count how often each item appears with a hash map).
- Use a min-heap of size k for the k largest (the top of the heap is the weakest of the best). Use a max-heap for the k smallest.
- For every item: push it. If the heap grows beyond k, pop the top (the smallest).
- When done, the heap holds the answer. Pop everything (or sort the k items) to print it in order.
The code in four languages
PHP
<?php
// Top K Frequent: keep a min-heap of at most k (count, word) pairs
function topK(array $words, int $k): array {
$counts = array_count_values($words); // word => how many times
$heap = new SplMinHeap(); // smallest count on top
foreach ($counts as $word => $c) {
$heap->insert([$c, $word]);
if (count($heap) > $k) {
$heap->extract(); // weakest steps off the podium
}
}
$result = [];
while (!$heap->isEmpty()) {
$result[] = $heap->extract()[1]; // weakest first
}
return array_reverse($result); // strongest first
}
$words = ["vada", "jalebi", "chai", "samosa", "chai", "vada", "chai", "samosa", "chai", "samosa"];
echo implode(", ", topK($words, 2)); // chai, samosaJavaScript
// Top K Frequent: keep a min-heap of at most k [count, word] pairs
class MinHeap {
constructor() { this.a = []; }
size() { return this.a.length; }
push(x) {
const a = this.a;
a.push(x);
let i = a.length - 1;
while (i > 0) { // bubble up
const p = (i - 1) >> 1;
if (a[p][0] <= a[i][0]) break;
[a[p], a[i]] = [a[i], a[p]];
i = p;
}
}
pop() {
const a = this.a;
const top = a[0];
const last = a.pop();
if (a.length) {
a[0] = last;
let i = 0;
for (;;) { // sink down
const l = 2 * i + 1, r = l + 1;
let m = i;
if (l < a.length && a[l][0] < a[m][0]) m = l;
if (r < a.length && a[r][0] < a[m][0]) m = r;
if (m === i) break;
[a[m], a[i]] = [a[i], a[m]];
i = m;
}
}
return top;
}
}
function topK(words, k) {
const counts = new Map();
for (const w of words) counts.set(w, (counts.get(w) || 0) + 1);
const heap = new MinHeap(); // smallest count on top
for (const [word, c] of counts) {
heap.push([c, word]);
if (heap.size() > k) {
heap.pop(); // weakest steps off the podium
}
}
const result = [];
while (heap.size()) result.push(heap.pop()[1]); // weakest first
return result.reverse(); // strongest first
}
const words = ["vada", "jalebi", "chai", "samosa", "chai", "vada", "chai", "samosa", "chai", "samosa"];
console.log(topK(words, 2).join(", ")); // chai, samosaJava
import java.util.*;
public class Main {
// Top K Frequent: keep a min-heap of at most k (count, word) pairs
record Entry(int count, String word) {}
static List<String> topK(String[] words, int k) {
Map<String, Integer> counts = new LinkedHashMap<>(); // word -> how many times
for (String w : words) counts.merge(w, 1, Integer::sum);
PriorityQueue<Entry> heap = new PriorityQueue<>(Comparator.comparingInt(Entry::count)); // smallest count on top
for (var e : counts.entrySet()) {
heap.add(new Entry(e.getValue(), e.getKey()));
if (heap.size() > k) {
heap.poll(); // weakest steps off the podium
}
}
List<String> result = new ArrayList<>();
while (!heap.isEmpty()) {
result.add(heap.poll().word()); // weakest first
}
Collections.reverse(result); // strongest first
return result;
}
public static void main(String[] args) {
String[] words = {"vada", "jalebi", "chai", "samosa", "chai", "vada", "chai", "samosa", "chai", "samosa"};
System.out.println(String.join(", ", topK(words, 2))); // chai, samosa
}
}Go
package main
import (
"container/heap"
"fmt"
"slices"
"strings"
)
// Entry is one (count, word) pair.
type Entry struct {
count int
word string
}
// minHeap keeps the smallest count on top.
type minHeap []Entry
func (h minHeap) Len() int { return len(h) }
func (h minHeap) Less(i, j int) bool { return h[i].count < h[j].count }
func (h minHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *minHeap) Push(x any) { *h = append(*h, x.(Entry)) }
func (h *minHeap) Pop() any {
old := *h
last := old[len(old)-1]
*h = old[:len(old)-1]
return last
}
// topK is Top K Frequent: keep a min-heap of at most k (count, word) pairs.
func topK(words []string, k int) []string {
counts := map[string]int{} // word -> how many times
for _, w := range words {
counts[w]++
}
h := &minHeap{} // smallest count on top
for word, c := range counts {
heap.Push(h, Entry{c, word})
if h.Len() > k {
heap.Pop(h) // weakest steps off the podium
}
}
var result []string
for h.Len() > 0 {
result = append(result, heap.Pop(h).(Entry).word) // weakest first
}
slices.Reverse(result) // strongest first
return result
}
func main() {
words := []string{"vada", "jalebi", "chai", "samosa", "chai", "vada", "chai", "samosa", "chai", "samosa"}
fmt.Println(strings.Join(topK(words, 2), ", ")) // chai, samosa
}Time: O(n log k) · Extra space: O(n). Counting uses O(n) memory; then each of the distinct items costs one heap step of size k. Sorting everything would cost O(n log n).
Watch out for
- Using a max-heap for the k largest and keeping everything. A min-heap of size k throws away the weakest so memory and time stay small.
- Forgetting to count first. A heap of raw words does not know the frequencies.
- Not remembering that heap pops come out weakest first, so the final list must be reversed.
Quick check
- Which clue points to a heap?
- "Return the k most frequent / largest items"
- "Find the middle of a linked list"
- "Is the string a palindrome?"
- To keep the k LARGEST items, which heap do you use?
- A max-heap of size n
- A sorted list of size n
- A min-heap of size k
- Why is the heap approach better than sorting all items when k is small?
- It uses recursion
- It does not need counts
- Each step costs only about log k, not log n