Kth Largest Element in a Stream

EasyHeap · Top K · Design🧩 Heap & Top-KLeetCode #703 ↗Updated

Problem

Build a class KthLargest(k, nums) that starts with the scores in nums and then receives new scores one at a time. Each call add(val) inserts the score and returns the k-th largest value seen so far (counting duplicates, i.e. k-th in sorted order, not k-th distinct).
Inputk=3, nums=[4,5,8,2]Outputinit
Inputadd 3, 5, 10, 9, 4Output4, 5, 5, 8, 8

0 ≤ nums.length ≤ 104  ·  1 ≤ k ≤ nums.length + 1  ·  -104 ≤ val ≤ 104  ·  ≤ 104 calls to add

Try it yourself

Java
class KthLargest {
    public KthLargest(int k, int[] nums) {
        
    }

    public int add(int val) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Only the k largest values can ever matter: anything smaller than the current k-th largest is buried forever. Keep exactly those k in a min-heap — its root is the answer.
PatternHeap & Top-K

Instinct "K largest / smallest / closest / most frequent", or "always take the best available next"? Keep a heap - size k for top-K, or a ready-queue for scheduling.

Memory hack Guard the top-K club with a bouncer - a min-heap of size k whose root is the weakest member; anyone stronger kicks them out.

Open the Heap & Top-K guide →

Approaches

Brute ForceList + Sort on Every add

Time O(n log n) per addSpace O(n)

Keep every score in a list. On each add, append, sort, and read index size - k. Correct by definition, but re-sorts an almost-sorted list every time (n = scores seen so far).

Java
class KthLargest {
    private final List<Integer> list = new ArrayList<>();
    private final int k;

    public KthLargest(int k, int[] nums) {
        this.k = k;
        for (int x : nums) list.add(x);
    }

    public int add(int val) {
        list.add(val);
        Collections.sort(list);
        return list.get(list.size() - k);
    }
}

Trivial to write; wasteful re-sorting makes many adds slow.

At a glance

LevelApproachTimeSpace
Brute ForceList + Sort on Every addO(n log n) per addO(n)
BetterSorted List + Binary-Search InsertO(n) per addO(n)
OptimalMin-Heap of Size kO(log k) per add (init O(n log k))O(k)
Common pitfalls
  • Using a max-heap of everything — finding the k-th still costs O(k log n) pops.
  • Trimming to k only in add, not in the constructor — heap stays too big.
  • Assuming nums has ≥ k elements — it can be empty when k = 1.
Interview tips
  • Say why the k-th largest is the minimum of the top-k set — hence a min-heap.
  • State per-operation costs separately for init and add.
  • Mention the follow-up: k-th smallest → max-heap of size k.
Pattern
Size-k min-heap → maintain the top-k / k-th largest over a stream of values.
My notes saved in this browser