Kth Largest Element in a Stream

Design a class to find the kth largest element in a stream.

Pattern

Min-Heap of Size K

This problem follows the Min-Heap of Size K pattern, commonly found in the Heap / Priority Queue category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Maintain a min-heap of size k. The root is always the kth largest.

Key Insight

A min-heap of size k keeps the k largest elements — the root (minimum of those k) is the kth largest overall.

Step-by-step

  1. 1Initialize a min-heap with the first k elements
  2. 2For each new element, if it's larger than the heap root:
  3. 3Remove the root and insert the new element
  4. 4The root is always the kth largest

Pseudocode

class KthLargest:
    def __init__(self, k, nums):
        self.k = k
        self.heap = nums[:k]
        heapify(self.heap)
        for num in nums[k:]:
            if num > self.heap[0]:
                heapreplace(self.heap, num)
    
    def add(self, val):
        if len(self.heap) < self.k:
            heappush(self.heap, val)
        elif val > self.heap[0]:
            heapreplace(self.heap, val)
        return self.heap[0]
Complexity Analysis

Time Complexity

O(log k)

Space Complexity

O(k)
More Heap / Priority Queue Problems

Master this pattern with YeetCode

Practice Kth Largest Element in a Stream and similar Heap / Priority Queue problems with flashcards. Build pattern recognition through active recall.

Practice this problem