Kth Largest Element in a Stream

easy

Design a class that tracks the k-th largest element in a stream of integers. It is initialized with k and an initial array nums; each add(val) inserts val and returns the k-th largest element seen so far.

To exercise it here, implement kthLargestStream(k, nums, adds): construct the tracker with k and nums, then call add for each value in adds, returning the list of results. If fewer than k elements exist at some step, that result is -1.

Hints

You only ever need the k largest elements seen so far.
Keep them in a min-heap of size k — its root is the k-th largest.
Each add pushes the value and pops the smallest if the heap grows beyond k.

Common doubts

A size-k min-heap holds the k largest and exposes their smallest — the k-th largest — at the root. A max-heap would need all n elements and O(n) work to find the k-th.
Sorting is O(n log n) per query and needs all n elements; the heap is O(log k) per add and stores only k.
The k-th largest isn't defined yet — return -1 (LeetCode guarantees at least k eventually).

Interview follow-ups

Symmetric — a size-k max-heap whose root is the k-th smallest.
Same size-k min-heap, but keyed by frequency instead of value.

Fun facts

  • This is LeetCode 703 — the streaming cousin of 'k-th largest in an array'.
  • The size-k min-heap is the canonical structure behind leaderboards and 'top N' feeds.

Asked at

AmazonFacebookMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: k = 3, nums = [4, 5, 8, 2], adds = [3, 5, 10, 9]
Output: [4, 5, 8, 8]
After each add, the 3rd largest so far is 4, 5, 8, 8.
Example 2
Input: k = 1, nums = [], adds = [1, 2, 3]
Output: [1, 2, 3]
The 1st largest is just the running maximum.
Constraints

- 1 <= k <= 10^4 - 0 <= nums.length <= 10^4 - 1 <= adds.length <= 10^4 - -10^4 <= nums[i], adds[i] <= 10^4

Solve this problem →