Kth Largest Element in a Stream

Design a data structure that processes integers one by one and returns the kth largest element after each insertion. The structure should support fast updates by maintaining a fixed-size heap.

Input Format

k = size of the heap to maintain, nums = stream values in insertion order

Output Format

array of kth largest values after each insertion; use -1 until at least k elements are seen

Constraints

  • 1 <= k <= 10^5
  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

Examples

Example 1:

Input:

k = 3
nums = [4,5,8,2]

Output:

[-1,-1,4,4]

Explanation:

The third insertion makes 4 the kth largest.

Example 2:

Input:

k = 2
nums = [1,2,3]

Output:

[-1,1,2]

Explanation:

The kth largest updates as the stream grows.

Loading...
Kth Largest Element in a Stream - Heap