Kth Largest Element in a Stream

Easy

Topics
HeapDesignBinary Search Tree

Design a class to find the kth largest element in a stream (the kth largest in sorted order, not the kth distinct). Implement KthLargest(k, nums) which initializes with an integer k and a stream of integers nums, and add(val) which appends val and returns the kth largest element so far.

Example 1

KthLargest(3, 4, 5, 8, 2)add(3)add(5)add(10)add(9)add(4)
Its root is then the kth largest, and each add costs log k rather than a re-sort.
Calls run top to bottom; the arrow shows what each one returns.
Input:  operations = ["KthLargest","add","add","add","add","add"], values = [[3,4,5,8,2],[3],[5],[10],[9],[4]]
Output: [null,4,5,5,8,8]

Constraints

  • 1 <= k <= 10^4
  • At least k elements exist when add is queried.
  • At most 10^4 calls to add.
Editorial — intuition, approach, complexity and pitfalls

Intuition

You only ever need the k largest values seen so far; the kth largest is the smallest of those. A min-heap of size k keeps exactly them, with the answer sitting at its root.

Approach

  1. Push all initial numbers into a min-heap, then pop until only k remain.
  2. On add, push the new value; if the heap exceeds size k, pop the smallest.
  3. The heap root is the kth largest element.

Dry Run

KthLargest(3, [4, 5, 8, 2])
  heapify [4, 5, 8, 2], then pop until only 3 remain  ->  heap [4, 5, 8]
  the 2 is discarded; the root 4 is the 3rd largest of 4, 5, 8, 2
  add 3    [4, 5, 8]   push 3,  size 4, pop the smallest (3)    root 4
  add 5    [4, 5, 8]   push 5,  pop the smallest (4)            root 5
  add 10   [5, 5, 8]   push 10, pop the smallest (5)            root 5
  add 9    [5, 10, 8]  push 9,  pop the smallest (5)            root 8
  add 4    [8, 9, 10]  push 4,  pop the smallest (4)            root 8
answer null|4|5|5|8|8
Adding 3 to a stream whose 3rd largest is already 4 should change nothing, and the
heap makes that cheap rather than special: 3 goes in and comes straight back out
as the smallest of the four.
It has to be a MIN-heap, which reads backwards until you see why. The heap holds
the k LARGEST values seen so far, so the smallest member of that set is the kth
largest overall -- and a min-heap keeps precisely that at its root, readable in
O(1). A max-heap would park the single biggest value on top and leave you walking
k - 1 entries per query.
Note what the heap never holds again: the 2 dropped during construction, and every
value later evicted. Once something falls out of the top k it can never return, so
throwing it away costs nothing.

Complexity

  • Time — O(log k) per add: each add does a heap push/pop bounded by size k.
  • Space — O(k): the heap holds at most k elements.

Common Pitfalls

  • Keep a min-heap (smallest on top), not a max-heap — the kth largest is the minimum of the top k.

Full Solution — all languages

class KthLargest:
    def __init__(self, k, nums):
        import heapq
        self.k = k
        self.heap = list(nums)
        heapq.heapify(self.heap)
        while len(self.heap) > k:
            heapq.heappop(self.heap)

    def add(self, val):
        import heapq
        heapq.heappush(self.heap, val)
        if len(self.heap) > self.k:
            heapq.heappop(self.heap)
        return self.heap[0]
Asked at Adobe
SensAI
Beta
Tap the mic to stop voice mode