AlgoTales · Roadmap

Top K problems

Intermediate · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Top K problems ask for the best few items out of a huge set, such as most sold products or most used words. A small heap of size k solves them in one pass, without sorting everything and without holding everything in memory.

Practical use cases

  • Web app: Trending hashtags this hour. A social app counts hashtag uses per hour and must show the top 10 trending ones. It keeps a small heap of the 10 highest counts and compares each hashtag with the weakest. The trending box refreshes quickly even when there are 2 million distinct tags.
  • Web app: Bestsellers on a shop dashboard. A shop admin wants "Top 5 products this week" from 300,000 order lines. The code counts sales per product, then pushes counts through a heap of size 5. The dashboard widget loads in under a second rather than sorting every product.
  • System: Nearest places and largest files. A maps feature that lists the 5 nearest petrol pumps and a disk tool that lists the 10 biggest files both keep only k candidates. The heap throws out anything that cannot make the list, so the tools work on millions of entries.

The story: The Kirana Bestseller Board

Aarav's uncle ran a kirana store and had a long sales slip with thousands of lines: atta, atta, oil, dal, atta, biscuits... Every Diwali he asked, "Which 3 items sold the most?" Aarav copied the whole slip, sorted it, and counted by hand. It took the entire evening.

Mira showed him the heap way. "First count how often each item appears (a tally, like a hash map). Now you have a short list: item and count. Then use the podium trick from the kth-largest lesson: a shelf with only 3 seats, a min heap on the count."

Each new item with its count is compared with the weakest best-seller on top. If it sells more, the weakest steps off and the new item takes the seat. Otherwise the new item is ignored. At the end, the three items on the shelf are the stars of the store.

This pattern solves a whole family called Top K problems: top K frequent words, K closest points, K biggest files, K cheapest flights. Same recipe: score each thing, keep a size-K heap, evict the weakest.

How to spot this problem, and where you need it

You must show a small "top N" or "best N" list from a very large collection and fully sorting it each time is too slow or uses too much memory.

Signs you need it

  • A dashboard widget says "Top 10", "Most popular", "Trending" or "Nearest 5" and takes seconds to load.
  • You use ORDER BY or sort() over everything and then slice the first few items.
  • The statement asks for the "k most frequent", "k closest" or "k largest" items.

Where to use it in a project

  • Trending lists, bestseller widgets and "most viewed" boxes on dashboards and home pages.
  • Nearby-search features and disk or log analysis tools that report only the biggest or closest few.

The solution

If counting is needed, first count each item with a map. Then keep a heap of size k holding the best seen so far, with the weakest of them on top. For each item, add it, and if the heap has more than k items, remove the weakest. At the end the heap holds the top k. No full sort is needed.

Payoff: Before: sorting 2 million hashtags to show 10. After: one pass with a heap of 10, so the trending box updates in a blink.

Explain it like I am 8

In a mango shop, count how many of each kind were sold. Then give only 3 shelf spots to the best sellers. Whenever a kind sells more than the weakest of the three, it takes that spot. In the end, the shelf shows your top three!

How it works, step by step

  1. Count each item with a map (item to number of times). This is a single pass.
  2. Create a min heap ordered by count.
  3. For each (item, count): push it, and if the heap now has more than K entries, pop the weakest.
  4. After all items, the heap holds exactly the top K.
  5. Pop them out (they come weakest first) and reverse to list the best first.

The code in four languages

PHP

<?php
// A heap lives in a plain array. Spot i has children at 2*i+1 and 2*i+2.
// before($x, $y) answers: "does x belong closer to the top than y?"  (default = min-heap)
class Heap {
    private array $a = [];
    private $before;
    public function __construct(?callable $before = null) {
        $this->before = $before ?? fn($x, $y) => $x < $y;
    }
    public function size(): int { return count($this->a); }
    public function peek() { return $this->a[0] ?? null; }
    public function push($v): void {             // put it at the bottom, then climb
        $this->a[] = $v;
        $i = count($this->a) - 1;
        while ($i > 0) {
            $p = intdiv($i - 1, 2);
            if (!($this->before)($this->a[$i], $this->a[$p])) break;
            [$this->a[$i], $this->a[$p]] = [$this->a[$p], $this->a[$i]];
            $i = $p;
        }
    }
    public function pop() {                      // take the top, put the last one on top, sink it
        if (count($this->a) === 0) return null;
        $top = $this->a[0];
        $last = array_pop($this->a);
        $n = count($this->a);
        if ($n > 0) {
            $this->a[0] = $last;
            $i = 0;
            while (true) {
                $l = 2 * $i + 1; $r = $l + 1; $best = $i;
                if ($l < $n && ($this->before)($this->a[$l], $this->a[$best])) $best = $l;
                if ($r < $n && ($this->before)($this->a[$r], $this->a[$best])) $best = $r;
                if ($best === $i) break;
                [$this->a[$i], $this->a[$best]] = [$this->a[$best], $this->a[$i]];
                $i = $best;
            }
        }
        return $top;
    }
}

// Top K most frequent items: count first, then keep the K best counts in a min heap.
function topKFrequent(array $items, int $k): array {
    $counts = array_count_values($items);                    // item => how many times
    $heap = new Heap(fn($x, $y) => $x[0] < $y[0]);           // entries are [count, item]
    foreach ($counts as $item => $count) {
        $heap->push([$count, $item]);
        if ($heap->size() > $k) $heap->pop();                // evict the weakest
    }
    $best = [];
    while ($heap->size() > 0) $best[] = $heap->pop()[1];     // weakest comes out first...
    return array_reverse($best);                             // ...so flip it
}

$slip = str_split('AAAAABBBCCDEEEEFFFFFF');                  // A x5, B x3, C x2, D x1, E x4, F x6
echo implode(' ', topKFrequent($slip, 3)), PHP_EOL;          // F A E

JavaScript

// A heap lives in a plain array. Spot i has children at 2*i+1 and 2*i+2.
// before(x, y) answers: "does x belong closer to the top than y?"  (default = min-heap)
class Heap {
  constructor(before = (x, y) => x < y) { this.a = []; this.before = before; }
  size() { return this.a.length; }
  peek() { return this.a[0]; }
  push(v) {                          // put it at the bottom, then climb
    const a = this.a; a.push(v);
    let i = a.length - 1;
    while (i > 0) {
      const p = (i - 1) >> 1;
      if (!this.before(a[i], a[p])) break;
      [a[i], a[p]] = [a[p], a[i]]; i = p;
    }
  }
  pop() {                            // take the top, put the last one on top, sink it
    const a = this.a;
    if (a.length === 0) return null;
    const top = a[0], last = a.pop();
    if (a.length > 0) {
      a[0] = last;
      let i = 0;
      for (;;) {
        const l = 2 * i + 1, r = l + 1; let best = i;
        if (l < a.length && this.before(a[l], a[best])) best = l;
        if (r < a.length && this.before(a[r], a[best])) best = r;
        if (best === i) break;
        [a[i], a[best]] = [a[best], a[i]]; i = best;
      }
    }
    return top;
  }
}

// Top K most frequent items: count first, then keep the K best counts in a min heap.
function topKFrequent(items, k) {
  const counts = new Map();                                  // item => how many times
  for (const it of items) counts.set(it, (counts.get(it) || 0) + 1);
  const heap = new Heap((x, y) => x[0] < y[0]);              // entries are [count, item]
  for (const [item, count] of counts) {
    heap.push([count, item]);
    if (heap.size() > k) heap.pop();                         // evict the weakest
  }
  const best = [];
  while (heap.size() > 0) best.push(heap.pop()[1]);          // weakest comes out first...
  return best.reverse();                                     // ...so flip it
}

const slip = 'AAAAABBBCCDEEEEFFFFFF'.split('');              // A x5, B x3, C x2, D x1, E x4, F x6
console.log(topKFrequent(slip, 3).join(' '));                // F A E

Java

import java.util.*;
import java.util.function.BiPredicate;

public class Main {
    // A heap lives in a plain list. Spot i has children at 2*i+1 and 2*i+2.
    // before(x, y) answers: "does x belong closer to the top than y?"
    static class Heap<T> {
        private final List<T> a = new ArrayList<>();
        private final BiPredicate<T, T> before;

        Heap(BiPredicate<T, T> before) { this.before = before; }

        int size() { return a.size(); }

        void push(T v) {                          // put it at the bottom, then climb
            a.add(v);
            int i = a.size() - 1;
            while (i > 0) {
                int p = (i - 1) / 2;
                if (!before.test(a.get(i), a.get(p))) break;
                Collections.swap(a, i, p);
                i = p;
            }
        }

        T pop() {                                 // take the top, put the last one on top, sink it
            if (a.isEmpty()) return null;
            T top = a.get(0);
            T last = a.remove(a.size() - 1);
            int n = a.size();
            if (n > 0) {
                a.set(0, last);
                int i = 0;
                while (true) {
                    int l = 2 * i + 1, r = l + 1, best = i;
                    if (l < n && before.test(a.get(l), a.get(best))) best = l;
                    if (r < n && before.test(a.get(r), a.get(best))) best = r;
                    if (best == i) break;
                    Collections.swap(a, i, best);
                    i = best;
                }
            }
            return top;
        }
    }

    record CountItem(int count, char item) {}

    // Top K most frequent items: count first, then keep the K best counts in a min heap.
    static List<Character> topKFrequent(char[] items, int k) {
        Map<Character, Integer> counts = new LinkedHashMap<>();       // item => how many times
        for (char it : items) counts.merge(it, 1, Integer::sum);
        Heap<CountItem> heap = new Heap<>((x, y) -> x.count() < y.count());
        for (var e : counts.entrySet()) {
            heap.push(new CountItem(e.getValue(), e.getKey()));
            if (heap.size() > k) heap.pop();                          // evict the weakest
        }
        List<Character> best = new ArrayList<>();
        while (heap.size() > 0) best.add(heap.pop().item());          // weakest comes out first...
        Collections.reverse(best);                                    // ...so flip it
        return best;
    }

    public static void main(String[] args) {
        char[] slip = "AAAAABBBCCDEEEEFFFFFF".toCharArray();          // A x5, B x3, C x2, D x1, E x4, F x6
        System.out.println(topKFrequent(slip, 3));                    // [F, A, E]
    }
}

Go

package main

import "fmt"

// A heap lives in a plain slice. Spot i has children at 2*i+1 and 2*i+2.
// before(x, y) answers: "does x belong closer to the top than y?"
type Heap[T any] struct {
	a      []T
	before func(x, y T) bool
}

func (h *Heap[T]) Size() int { return len(h.a) }

// Push puts it at the bottom, then climbs.
func (h *Heap[T]) Push(v T) {
	h.a = append(h.a, v)
	i := len(h.a) - 1
	for i > 0 {
		p := (i - 1) / 2
		if !h.before(h.a[i], h.a[p]) {
			break
		}
		h.a[i], h.a[p] = h.a[p], h.a[i]
		i = p
	}
}

// Pop takes the top, puts the last one on top, and sinks it.
func (h *Heap[T]) Pop() (T, bool) {
	var zero T
	if len(h.a) == 0 {
		return zero, false
	}
	top := h.a[0]
	last := h.a[len(h.a)-1]
	h.a = h.a[:len(h.a)-1]
	n := len(h.a)
	if n > 0 {
		h.a[0] = last
		i := 0
		for {
			l, r, best := 2*i+1, 2*i+2, i
			if l < n && h.before(h.a[l], h.a[best]) {
				best = l
			}
			if r < n && h.before(h.a[r], h.a[best]) {
				best = r
			}
			if best == i {
				break
			}
			h.a[i], h.a[best] = h.a[best], h.a[i]
			i = best
		}
	}
	return top, true
}

type countItem struct {
	count int
	item  rune
}

// topKFrequent counts first, then keeps the K best counts in a min heap.
func topKFrequent(items []rune, k int) []rune {
	counts := map[rune]int{} // item => how many times
	for _, it := range items {
		counts[it]++
	}
	heap := &Heap[countItem]{before: func(x, y countItem) bool { return x.count < y.count }}
	for item, count := range counts {
		heap.Push(countItem{count, item})
		if heap.Size() > k {
			heap.Pop() // evict the weakest
		}
	}
	var best []rune
	for heap.Size() > 0 {
		top, _ := heap.Pop()
		best = append(best, top.item) // weakest comes out first...
	}
	for i, j := 0, len(best)-1; i < j; i, j = i+1, j-1 { // ...so flip it
		best[i], best[j] = best[j], best[i]
	}
	return best
}

func main() {
	slip := []rune("AAAAABBBCCDEEEEFFFFFF") // A x5, B x3, C x2, D x1, E x4, F x6
	for _, r := range topKFrequent(slip, 3) {
		fmt.Print(string(r), " ")
	}
	fmt.Println() // F A E
}

Time: O(n + m log k) · Extra space: O(m). One pass to count n items, then m distinct items each costing a log k heap step (m is the number of different items). The counting map takes the memory.

Watch out for

  • Sorting everything when only K results are needed. A size-K heap does far less work.
  • Using a max heap and keeping it all. A min heap of size K lets you throw the weakest away cheaply.
  • Forgetting that results come out weakest-first from a min heap, so reverse them if you need best-first.

Quick check

  1. For the K most frequent items, what is the first step?
    • Build a max heap of letters
    • Sort the slip
    • Count how often each item appears
  2. Which heap, and how big?
    • Max heap of size n
    • Min heap of size K
    • Min heap of size n
  3. Which of these is a Top K problem?
    • Is this number in the list?
    • Reverse a string
    • Find the 5 closest cafes to me