#703

Kth Largest Element in a Stream

Easy Min-heap of size k

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Design a class that receives numbers one by one and, after each one, returns the k-th largest number seen so far.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: after each new number, what's the k-th largest so far?

Why this works: keep only the k largest numbers in a min-heap; its smallest (the top) is the k-th largest.

Example: k = 3, start [4, 5, 8, 2] → heap {4, 5, 8}

add 3 → {3,4,5,8} → drop 3 → top 4add 5 → {4,5,5,8} → drop 4 → top 5add 10 → drop 5 → {5, 8, 10} top 5

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using a max-heap of everything and popping k times on each call.

Solve on LeetCode ↗
Complexity
  • Time: O(log k) per add.
  • Space: O(k).
Topic: Heaps & Priority Queue
🎬 Episodes 64–68: video coming soon