AlgoTales · Roadmap

Kth largest/smallest

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

Where you will meet this in real life

To find the k-th largest item you keep a small heap of only the best k items seen so far. The weakest of them sits on top, so each new item is checked against just that one, and memory stays tiny however big the data is.

Practical use cases

  • Web app: Tracking the 10th best score live. A quiz site shows "Score to beat for the top 10". The code keeps a min heap of 10 scores. A new score is compared only with the smallest of them, and if it is higher, it replaces that one. The line updates instantly with millions of players. Memory use stays at ten numbers.
  • Web app: Fifth-highest salary per department. An HR tool needs "the 5th highest salary in each department" repeatedly. For each department a heap of 5 values is kept while rows stream in. No department list needs to be fully sorted, and the report runs quickly on large payroll data.
  • System: Search engines and big data jobs. Search engines keep only the best few hundred results while scanning billions of pages. Big data jobs use a small heap of size k per machine so that no machine has to hold or sort all the data. The small results are then combined at the end.

The story: The Podium With Only Three Seats

Mrs. Sharma's school had a quiz with 1,000 students. Scores trickled in through the day, and the principal kept asking, "Who is third on the leaderboard right now?" Kabir wrote all the scores on a long list and sorted it again and again. His fingers hurt.

Mira had a better idea. "We only care about the top three. Build a podium with only 3 seats. A new score gets a seat only if it is better than the weakest person on the podium."

To find the weakest finalist instantly, she kept the podium as a min heap: the smallest score of the three always stood on top. Score 4 arrived while the podium was full of 7, 10, 20? She compared with the top: not better, so out. Score 15? Better than 7! 7 left, 15 sat down, and the heap shuffled itself.

The surprise: to find the k-th largest, you use a min heap of size k, and the answer is simply the top of the heap. For the k-th smallest, mirror it with a max heap. You never sort the other 997 scores.

How to spot this problem, and where you need it

You want the k-th best or the best k items from a very large or never-ending set of values, and you cannot afford to sort or even hold all of them.

Signs you need it

  • You load all values into an array and sort it just to read the 10th item.
  • Data arrives as a stream or is too large for memory, and the answer must stay up to date.
  • The task says "k-th largest", "k-th smallest", "k-th best score" for a large k-limited result.

Where to use it in a project

  • Live leaderboards and "score to beat" widgets that track only a fixed number of top entries.
  • Reports that need percentiles or the nth highest value over large database results.

The solution

To find the k-th largest, keep a min heap that never holds more than k items. For each new value, push it; if the heap now has more than k items, remove the smallest. After all values are seen, the top of the heap is the k-th largest. For the k-th smallest, use a max heap in the same way.

Payoff: Before: sorting 5 million scores to find the 10th. After: one pass with a heap of 10, and about 4 steps per new score.

Explain it like I am 8

A school photo has only 3 seats on the stage for the tallest kids. When a new kid walks in, you only need to check the shortest kid already on stage. If the new kid is taller, swap them. At the end, the shortest kid on the stage is the 3rd tallest in the whole school.

How it works, step by step

  1. Choose the heap: for the k-th largest use a min heap; for the k-th smallest use a max heap.
  2. Feed numbers in. While the heap holds fewer than k items, just push.
  3. Once it holds k, a new number has to beat the top (the weakest of the best k) to get in.
  4. If it beats the top, remove the top and push the new number (it sinks into place). Otherwise ignore it.
  5. When the numbers run out, the top of the heap is your k-th largest.

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;
    }
}

// k-th LARGEST: keep the k best in a MIN heap, so the weakest of them is on top.
function kthLargest(array $nums, int $k): int {
    $heap = new Heap();
    foreach ($nums as $x) {
        $heap->push($x);
        if ($heap->size() > $k) $heap->pop();      // too many: the weakest has to leave
    }
    return $heap->peek();
}

// k-th SMALLEST: mirror it with a MAX heap.
function kthSmallest(array $nums, int $k): int {
    $heap = new Heap(fn($x, $y) => $x > $y);
    foreach ($nums as $x) {
        $heap->push($x);
        if ($heap->size() > $k) $heap->pop();
    }
    return $heap->peek();
}

$scores = [7, 10, 4, 3, 20, 15];
echo kthLargest($scores, 3), PHP_EOL;              // 10
echo kthSmallest($scores, 3), PHP_EOL;             // 7

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;
  }
}

// k-th LARGEST: keep the k best in a MIN heap, so the weakest of them is on top.
function kthLargest(nums, k) {
  const heap = new Heap();
  for (const x of nums) {
    heap.push(x);
    if (heap.size() > k) heap.pop();               // too many: the weakest has to leave
  }
  return heap.peek();
}

// k-th SMALLEST: mirror it with a MAX heap.
function kthSmallest(nums, k) {
  const heap = new Heap((x, y) => x > y);
  for (const x of nums) {
    heap.push(x);
    if (heap.size() > k) heap.pop();
  }
  return heap.peek();
}

const scores = [7, 10, 4, 3, 20, 15];
console.log(kthLargest(scores, 3));                // 10
console.log(kthSmallest(scores, 3));               // 7

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(); }
        T peek() { return a.isEmpty() ? null : a.get(0); }

        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;
        }
    }

    // k-th LARGEST: keep the k best in a MIN heap, so the weakest of them is on top.
    static int kthLargest(int[] nums, int k) {
        Heap<Integer> heap = new Heap<>((x, y) -> x < y);
        for (int x : nums) {
            heap.push(x);
            if (heap.size() > k) heap.pop();      // too many: the weakest has to leave
        }
        return heap.peek();
    }

    // k-th SMALLEST: mirror it with a MAX heap.
    static int kthSmallest(int[] nums, int k) {
        Heap<Integer> heap = new Heap<>((x, y) -> x > y);
        for (int x : nums) {
            heap.push(x);
            if (heap.size() > k) heap.pop();
        }
        return heap.peek();
    }

    public static void main(String[] args) {
        int[] scores = {7, 10, 4, 3, 20, 15};
        System.out.println(kthLargest(scores, 3));     // 10
        System.out.println(kthSmallest(scores, 3));    // 7
    }
}

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) }
func (h *Heap[T]) Peek() T   { return h.a[0] }

// 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
}

// kthLargest keeps the k best in a MIN heap, so the weakest of them is on top.
func kthLargest(nums []int, k int) int {
	heap := &Heap[int]{before: func(x, y int) bool { return x < y }}
	for _, x := range nums {
		heap.Push(x)
		if heap.Size() > k {
			heap.Pop() // too many: the weakest has to leave
		}
	}
	return heap.Peek()
}

// kthSmallest mirrors it with a MAX heap.
func kthSmallest(nums []int, k int) int {
	heap := &Heap[int]{before: func(x, y int) bool { return x > y }}
	for _, x := range nums {
		heap.Push(x)
		if heap.Size() > k {
			heap.Pop()
		}
	}
	return heap.Peek()
}

func main() {
	scores := []int{7, 10, 4, 3, 20, 15}
	fmt.Println(kthLargest(scores, 3))  // 10
	fmt.Println(kthSmallest(scores, 3)) // 7
}

Time: O(n log k) · Extra space: O(k). Each of the n numbers costs at most one push and one pop in a heap that never holds more than k items. Sorting everything would be O(n log n).

Watch out for

  • Using a max heap for the k-th largest. A min heap of size k is the right one, so you can evict the weakest quickly.
  • Letting the heap grow past k. Pop whenever the size becomes k + 1.
  • Off-by-one on k. The 1st largest is the maximum, so k = 1 should return the biggest number.

Quick check

  1. To find the k-th largest, which heap of size k do we keep?
    • A max heap
    • A min heap
    • No heap, just sort
  2. When the heap is full and a new number is smaller than the top, what happens?
    • It is ignored (or pushed then popped straight away)
    • The heap doubles
    • It replaces the top
  3. Time to find the k-th largest among n numbers with this method?
    • O(n²)
    • O(n log k)
    • O(k log n)