Video in progress

Strong Middle 🧠 Problem solving

You need to find the K largest elements in an array. Do you choose a heap or quickselect?

If K is small or the data arrives as a stream, a min-heap of size K, O(n log K). If everything is in memory and it's a one-off query, quickselect is O(n) on average, but O(n²) in the worst case, and it modifies the array.

📖 Answer

A full sort is O(n log n). It works, but it does more work than needed.

The min-heap version:

static int[] topK(int[] a, int k) {
    PriorityQueue<Integer> heap = new PriorityQueue<>(k);  // min-heap
    for (int x : a) {
        if (heap.size() < k) heap.add(x);
        else if (x > heap.peek()) { heap.poll(); heap.add(x); }
    }
    return heap.stream().mapToInt(Integer::intValue).toArray();
}

At the top of the heap sits the smallest of the K largest so far. A new element gets in only if it's larger than that. Memory is O(K): even if you look for the top 100 in 10 GB of logs, you keep only 100 elements.

Quickselect is quicksort with one side thrown away: you partition around a pivot and descend only into the part where the K-th position lies. On average n + n/2 + n/4 + ... = O(n). If the pivot isn't chosen randomly, a sorted input drops it to O(n²).

How I choose:

Situation Choice
a stream, doesn't fit in memory heap
K ≈ n/2, array in memory quickselect
the result must be ordered heap, then a K log K sort
the original array can't be modified heap or a copy

Watch out for boxing: a million Integers in a heap put noticeable GC pressure on the system. In a very hot path it's worth writing your own heap over an int[].