Kth Largest Element in a Stream

Pattern: Top K

easy

Keep a min heap of the k largest values seen. Each add pushes the value and pops if the heap passes size k. The top, the smallest of the k largest, is the kth largest. Each add is O(log k).

The problem

Build KthLargest(k, nums) with add(val), which adds val to the stream and returns the kth largest value so far. With k = 3 and nums = [4, 5, 8, 2], adding 3, 5, 10, 9, 4 returns 4, 5, 5, 8, 8. There are always at least k values when add is asked.

Think first

  • Which values can ever be the answer again?
  • Among those, which one is the answer?
  • Which heap keeps that one on top?

Hints

    Brute force, and why it fails

    Sort all values after every add: O(n log n) per call.

    The key insight

    The kth largest is the minimum of the k largest, so a size-k min heap answers in O(1) and updates in O(log k).

    Dry run

    heap4 5 8

    k = 3, nums = [4, 5, 8, 2]. After adding them and trimming to 3: heap 4, 5, 8.

    Step 1 of 4

    The plan

    constructor: for x in nums: add(x)
    add(val): push val; if size > k: pop; return top
    

    Complexity

    Time
    O(log k) per add
    Space
    O(k)

    The heap never grows past k + 1 items.

    Edge cases

    • k = 1: the maximum so far.
    • Starting with fewer than k values.
    • Negative values.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class KthLargest {
        private final int k;
        private final PriorityQueue<Integer> heap = new PriorityQueue<>();   // the k largest so far; smallest on top
    
        public KthLargest(int k, int[] nums) {
            this.k = k;
            for (int x : nums) add(x);
        }
    
        public int add(int val) {
            heap.add(val);
            if (heap.size() > k) heap.poll();       // drop the smallest: it is not among the k largest
            return heap.peek();                     // the smallest of the k largest is the kth largest
        }
    }

    C++

    class KthLargest {
    public:
        int k;
        priority_queue<int, vector<int>, greater<int>> heap;   // the k largest so far; smallest on top
    
        KthLargest(int k, vector<int> nums) : k(k) {
            for (int x : nums) add(x);
        }
    
        int add(int val) {
            heap.push(val);
            if (static_cast<int>(heap.size()) > k) heap.pop();   // drop the smallest: it is not among the k largest
            return heap.top();                      // the smallest of the k largest is the kth largest
        }
    };

    Python

    import heapq
    
    class KthLargest:
        def __init__(self, k: int, nums: list[int]):
            self.k = k
            self.heap = []                          # the k largest so far; smallest on top
            for x in nums:
                self.add(x)
    
        def add(self, val: int) -> int:
            heapq.heappush(self.heap, val)
            if len(self.heap) > self.k:
                heapq.heappop(self.heap)            # drop the smallest: it is not among the k largest
            return self.heap[0]                     # the smallest of the k largest is the kth largest

    Common mistakes

    • Using a max heap, which needs k pops to answer.
    • Returning before trimming the heap.

    Similar problems