InterviewPrepKit

Home / Coding / Heap & Priority Queue

Kth Largest Element in a Stream

easy Original β†—
Solving tips
  • Key insight: the k-th largest is the minimum of the k largest, so keep a MIN-heap capped at size k β€” its root is always the answer.
  • On add, push then pop if size exceeds k; anything evicted from the top-k can never return, so the cap is safe.
  • Handle initial nums with fewer than k elements, and remember duplicates each take a slot ('k-th largest', not k-th distinct).
  • Target O(log k) per add and O(k) space; heapq.heappushpop or skipping values <= root avoids extra sifts.

Problem

Build a class that tracks the k-th largest value in a growing stream of numbers.

  • KthLargest(k: int, nums: List[int]) β€” initialize with an integer k and an initial batch of scores nums (which may contain fewer than k values).
  • add(val: int) -> int β€” append val to the stream and return the element that is currently the k-th largest counting duplicates (i.e. the k-th item of the stream sorted in descending order, not the k-th distinct value).

It is guaranteed that whenever add is called, the stream holds at least k elements.

Examples

  • KthLargest(3, [4, 5, 8, 2]), then add(3) -> 4, add(5) -> 5, add(10) -> 5, add(9) -> 8, add(4) -> 8 β€” after each insertion the 3rd largest of the whole stream is returned.
  • KthLargest(1, []), then add(-3) -> -3, add(-2) -> -2 β€” with k = 1 the answer is simply the maximum so far.
  • KthLargest(2, [7, 7]), then add(7) -> 7 β€” duplicates count separately, so the 2nd largest of [7, 7, 7] is 7.

Constraints

  • 1 <= k <= 10^4
  • 0 <= len(nums) <= 10^4
  • -10^4 <= val <= 10^4
  • Up to 10^4 calls to add.

Think about it first

Hint 1 You never need the whole sorted stream β€” after every add you only report one specific value. How much of the stream actually matters for that answer?
Hint 2 Only the k largest elements seen so far can ever influence the answer, and the answer is the smallest among those k. What structure gives you cheap access to the smallest of a set while supporting inserts?
Hint 3 Keep a min-heap capped at size k. On each add, push the value, and if the heap exceeds k elements pop the minimum. The heap's root is then exactly the k-th largest.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.