Skip to lesson

Top-k problems find the k most significant items efficiently using bounded priority queues in O(n log k).

Kth largest element using a size-k min heap

A top-k problem asks for the k best items, such as the k largest or most frequent, and a heap of size k solves it in O(n log k) time.

Finding the kth largest element in an array of n numbers often arises in ranking systems. A brute-force approach sorts the entire array in descending order, taking O(n log n) time. Sorting all n elements does unnecessary work when k is much smaller than n.

Example 1 · Brute force: sort everything, O(n log n) time, O(n) space

Main.javaJava
import java.util.*;
public class Main {    public static void main(String[] args) {        int[] scores = {52, 91, 67, 88, 73, 95, 60};        int k = 3;        int[] sorted = scores.clone();        Arrays.sort(sorted);                              // sorts all n values        System.out.println(k + "rd largest: " + sorted[sorted.length - k]);    }}
Output
3rd largest: 88

What this code does

  • The array is copied and fully sorted, so every value is put in order even though only one is needed.
  • After sorting, the kth largest is simply the value k places from the end.

Example 2 · Better: k passes for the maximum, O(n * k) time, O(n) space

Main.javaJava
public class Main {    public static void main(String[] args) {        int[] scores = {52, 91, 67, 88, 73, 95, 60};        int k = 3;        boolean[] used = new boolean[scores.length];        int answer = 0;        for (int round = 0; round < k; round++) {         // k passes over the array            int best = -1;            for (int i = 0; i < scores.length; i++) {                if (!used[i] && (best == -1 || scores[i] > scores[best])) best = i;            }            used[best] = true;            answer = scores[best];        }        System.out.println(k + "rd largest: " + answer);    }}
Output
3rd largest: 88

What this code does

  • Each pass finds the largest unused value and marks it used.
  • After k passes the last value found is the kth largest.
  • This beats full sorting when k is tiny, but it gets slow as k grows.

Example 3 · Optimal: size-k min-heap, O(n log k) time, O(k) space

Main.javaJava
import java.util.PriorityQueue;
public class Main {    static int findKthLargest(int[] nums, int k) {        PriorityQueue<Integer> minHeap = new PriorityQueue<>(k);        for (int num : nums) {            minHeap.offer(num);            if (minHeap.size() > k) {                minHeap.poll();            }        }        return minHeap.peek();    }
    public static void main(String[] args) {        int[] nums = {3, 2, 1, 5, 6, 4};        System.out.println("2nd largest: " + findKthLargest(nums, 2));        System.out.println("4th largest: " + findKthLargest(nums, 4));    }}
Output
2nd largest: 5
4th largest: 3

What this code does

  • minHeap size is bounded at k, evicting the smallest element whenever size exceeds k.
  • After processing all elements, the heap contains the k largest values.
  • The root of the min-heap is the kth largest element.
  • It is faster because the heap holds only k values, so each of the n numbers costs O(log k) instead of sorting all of them.

We solve this problem efficiently by maintaining a min-heap of fixed size k. Iterate through each number in the array and offer it into the min-heap. Whenever the heap size exceeds k, poll the minimum element from the top. At any point, the heap preserves the k largest numbers encountered so far. Because it is a min-heap, the root holds the smallest among the top k candidates. Therefore, the root peek value is precisely the kth largest element. Processing n items with a size-k heap costs O(n log k) time and O(k) extra memory.

Order of execution

Put the size-k heap steps in order

Find the kth largest number with a min-heap. Put the steps in the order the code runs them.

Top k frequent elements and k closest points

To find the top k frequent elements, count frequencies with a HashMap in O(n). Then keep a min-heap of size k ordered by frequency and evict the lowest count when it grows past k.

Example 4 · Top K Frequent Elements

Main.javaJava
import java.util.*;
public class Main {    static List<Integer> topKFrequent(int[] nums, int k) {        Map<Integer, Integer> counts = new HashMap<>();        for (int n : nums) counts.put(n, counts.getOrDefault(n, 0) + 1);
        PriorityQueue<Integer> minHeap = new PriorityQueue<>(            Comparator.comparingInt(counts::get)        );
        for (int num : counts.keySet()) {            minHeap.offer(num);            if (minHeap.size() > k) {                minHeap.poll();            }        }
        List<Integer> result = new ArrayList<>();        while (!minHeap.isEmpty()) result.add(minHeap.poll());        return result;    }
    public static void main(String[] args) {        int[] nums = {1, 1, 1, 2, 2, 3};        System.out.println("Top 2 frequent: " + topKFrequent(nums, 2));    }}
Output
Top 2 frequent: [2, 1]

What this code does

  • Counts map records the occurrence frequency of each number.
  • Min-heap orders elements by their frequency count.
  • Evicting minimum frequency keeps the k most frequent keys.

This costs O(u log k), where u is the number of unique values.

The k closest points problem works the same way. Use the squared distance x^2 + y^2 (no square root needed) and a max-heap of size k, evicting the farthest point when the size exceeds k, for O(n log k) time.

Merging k sorted lists in O(N log k) time

Consider k pre-sorted lists containing a combined total of N elements. A brute-force solution concatenates all elements together and sorts them, requiring O(N log N) time. We can optimize this to O(N log k) by merging lists simultaneously with a min-heap.

Example 5 · Brute force: join all lists and sort, O(N log N) time, O(N) space

Main.javaJava
import java.util.*;
public class Main {    public static void main(String[] args) {        int[][] lists = {{1, 4, 7}, {2, 5}, {3, 6, 8}};        List<Integer> all = new ArrayList<>();        for (int[] list : lists) {            for (int v : list) all.add(v);        }        Collections.sort(all);                            // ignores that each list is already sorted        System.out.println(all);    }}
Output
[1, 2, 3, 4, 5, 6, 7, 8]

What this code does

  • All N values are copied into one list and sorted from scratch.
  • The sorting step ignores the fact that every input list is already in order.
  • The heap version uses that order and only compares the k current list heads.

Example 6 · Optimal: min-heap of list heads, O(N log k) time, O(k) space

Main.javaJava
import java.util.*;
public class Main {    static class Node {        int val;        int listIdx;        int elemIdx;        Node(int val, int listIdx, int elemIdx) {            this.val = val;            this.listIdx = listIdx;            this.elemIdx = elemIdx;        }    }
    static List<Integer> mergeKSorted(int[][] lists) {        PriorityQueue<Node> pq = new PriorityQueue<>(Comparator.comparingInt(n -> n.val));        for (int i = 0; i < lists.length; i++) {            if (lists[i].length > 0) {                pq.offer(new Node(lists[i][0], i, 0));            }        }
        List<Integer> merged = new ArrayList<>();        while (!pq.isEmpty()) {            Node curr = pq.poll();            merged.add(curr.val);            if (curr.elemIdx + 1 < lists[curr.listIdx].length) {                pq.offer(new Node(lists[curr.listIdx][curr.elemIdx + 1], curr.listIdx, curr.elemIdx + 1));            }        }        return merged;    }
    public static void main(String[] args) {        int[][] lists = {            {1, 4, 7},            {2, 5, 8},            {3, 6, 9}        };        System.out.println("Merged list: " + mergeKSorted(lists));    }}
Output
Merged list: [1, 2, 3, 4, 5, 6, 7, 8, 9]

What this code does

  • The priority queue tracks the active head pointer across all k lists.
  • Smallest element is polled and its list successor is pushed into the queue.
  • Total execution time is O(N log k) where N is total element count.
  • It is faster because the heap only compares the k current heads, so each of the N values costs O(log k) instead of O(log N).

Initialize a min-heap of size k with the head element of each non-empty list. Repeatedly poll the minimum element from the heap and append it to our sorted output list. If the extracted element has a successor in its original list, push that successor into the heap. Every extraction and insertion takes O(log k) time. Each of the N elements enters and leaves the heap once, giving O(N log k) total time. Auxiliary memory is bounded by O(k) elements in the heap.

Next step

Check your understanding

10 quick questions