Tech Interview RoomStudy guides

Heaps & Intervals

Find the Kth largest element in an array.

Intermediate · 2 min read · Lesson 3 of 5 in Heaps & Intervals

Problem

[3,2,1,5,6,4], k = 2 → 5. Do better than sorting the whole array.

Approach

  • Min-heap of size k: the root is the kth largest after processing all elements. O(n log k), great for streams.
  • Quickselect: partition like quicksort around a random pivot and recurse into only the side containing the target index. Average O(n), worst case O(n²) (made unlikely with a random pivot).
java
import java.util.PriorityQueue;
import java.util.concurrent.ThreadLocalRandom;

class KthLargest {
    static int withHeap(int[] nums, int k) {
        PriorityQueue<Integer> heap = new PriorityQueue<>();   // min-heap
        for (int n : nums) {
            heap.offer(n);
            if (heap.size() > k) heap.poll();
        }
        return heap.peek();
    }

    static int quickselect(int[] nums, int k) {
        int[] a = nums.clone();
        int target = a.length - k;                // index of kth largest in ascending order
        int lo = 0, hi = a.length - 1;
        while (true) {
            int p = partition(a, lo, hi);
            if (p == target) return a[p];
            if (p < target) lo = p + 1; else hi = p - 1;
        }
    }

    // Lomuto partition around a random pivot
    private static int partition(int[] a, int lo, int hi) {
        int r = ThreadLocalRandom.current().nextInt(lo, hi + 1);
        swap(a, r, hi);
        int pivot = a[hi], store = lo;
        for (int i = lo; i < hi; i++) if (a[i] < pivot) swap(a, i, store++);
        swap(a, store, hi);
        return store;
    }

    private static void swap(int[] a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; }

    public static void main(String[] args) {
        int[] nums = {3, 2, 1, 5, 6, 4};
        System.out.println(withHeap(nums, 2));      // 5
        System.out.println(quickselect(nums, 2));   // 5
    }
}

Complexity

Heap: O(n log k) time, O(k) space. Quickselect: O(n) average, O(n²) worst; O(1) extra space if done in place.

Follow-up questions interviewers ask

Try answering each one before you open it.

How do you maintain the median of a stream of numbers?

Keep two heaps: a max-heap for the lower half and a min-heap for the upper half, rebalanced so their sizes differ by at most one. Insert into the appropriate heap, rebalance, and the median is the top of the larger heap or the average of both tops. O(log n) per insert, O(1) per median.