InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Heap & Priority Queue

Kth Largest Element in a Stream

easy Original ↗ 00:00

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 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 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug