Kth Largest Element in a Stream (LeetCode 703): Solution and Explanation

Easy
Tree
Design
Binary Search Tree
Heap
Data Stream
Binary Tree

Design a class that is created with an integer k and an initial list of numbers, then receives new numbers one at a time. After each new number, it returns the kth largest value seen so far.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The simplest design stores every number and sorts after each insertion, returning the element k positions from the end. That costs O(n log n) per call. Keeping a sorted list and inserting with binary search is better at O(n) per call because of shifting, but with ten thousand calls on a growing list it still adds up.

The key realization is that you never need numbers smaller than the current kth largest. Once a value falls below the top k, nothing that arrives later can bring it back into the top k, since new arrivals only push values down the ranking. So you only need to keep the k largest values seen so far.

Among those k values, the one you need to report is the smallest, and when a new value arrives the one you may need to throw away is also the smallest. A min-heap of size k makes both operations cheap: its top is the kth largest overall, and if a push makes it hold k + 1 values, popping the top removes the value that just dropped out of the top k.

Approach: Min-heap of size k

  1. In the constructor, store k and turn nums into a min-heap with heapify.
  2. Pop from the heap until it holds at most k values, discarding the smallest numbers that can never be the answer.
  3. In add, push the new value onto the heap.
  4. If the heap now has more than k values, pop the smallest.
  5. Return the heap top, self.minHeap[0], which is the kth largest value.

Step-by-step example

k = 3, nums = [4,5,8,2], then add(3), add(5), add(10), add(9), add(4)
  1. Heapify gives [2,4,5,8]. It has four values, so pop 2, leaving {4,5,8}.
  2. add(3): the heap becomes {3,4,5,8}, then pop 3. The top is 4, so return 4.
  3. add(5): push to get {4,5,5,8}, pop 4. Return 5. add(10): push to get {5,5,8,10}, pop 5. Return 5.
  4. add(9): push to get {5,8,9,10}, pop 5. Return 8.
  5. add(4): push to get {4,8,9,10}, pop 4. Return 8. The three largest values seen are 8, 9 and 10.

Code: Python, Java, C++

1class KthLargest:
2    def __init__(self, k: int, nums: List[int]):
3        self.minHeap, self.k = nums, k
4        heapq.heapify(self.minHeap)
5        while len(self.minHeap) > k:
6            heapq.heappop(self.minHeap)
7
8    def add(self, val: int) -> int:
9        heapq.heappush(self.minHeap, val)
10        if len(self.minHeap) > self.k:
11            heapq.heappop(self.minHeap)
12        return self.minHeap[0]

Time and space complexity

Time

O(n log n) to build, O(log k) per add

Heapify is O(n), and popping down to k values is O((n - k) log n). Each add does one push and at most one pop on a heap of size k + 1.

Space

O(k)

After construction the heap holds at most k values. During construction it briefly holds all n initial numbers, since it reuses the input list.

Other approaches

Sorted list with binary search insertion (time O(n) per add, space O(n))

Keep all numbers in a sorted list and insert each new value at the position found by binary search, then read the element k from the end. Lookup is instant but insertion shifts elements.

Counting array over the value range (time O(R) per add, space O(R))

Because values lie between -10^4 and 10^4, keep a count per value and walk down from the maximum to find the kth largest. Each add is O(1) to record but answering scans up to the range size.

Common mistakes

  • Using a max-heap of every number, which makes each query require popping k times and pushing them back.
  • Forgetting to trim the initial heap to k values, so the first add returns the wrong element when nums has more than k values.
  • Assuming the heap has k values when nums starts with fewer. The problem guarantees at least k values after each add, so the top is valid once the new value is pushed.
  • Popping before pushing in add, which can throw away a value that should stay in the top k.

Frequently asked questions

Why use a min-heap instead of a max-heap for the kth largest element?

You only need the k largest values, and the one you report and the one you evict are both the smallest of them. A min-heap of size k puts exactly that value at the top, so each update is O(log k).

What is the time complexity of add?

Each call pushes one value and pops at most one from a heap of size k + 1, so it is O(log k). Reading the top is O(1).

What happens if the initial array has fewer than k elements?

The heap simply holds what it has. Because the problem guarantees at least k values once add is called, the heap reaches size k by then and its top is the correct answer.