You are designing a small library to monitor statistics over a stream of integers.
Implement a data structure that, given an integer k and an initial list of integers, supports the following operation:
add(val)
: insert the integer
val
into the stream and return the
k-th largest
element among all elements seen so far (including the new one).
More formally, after each call to add, if you took all numbers that have been provided (both the initial list and all numbers added so far), sorted them in non-decreasing order, you should return the element that is k positions from the end (the k-th largest). You may assume that k is always valid (i.e., there are at least k elements after each add call).
Define a class or type with:
k
(an integer)
nums
(a list/array of integers, possibly empty)
add(val: int) -> int
that inserts
val
and returns the current k-th largest element.
1 \le k \le 10^4
10^4
calls to
add
will be made.
add
calls within typical interview time complexity expectations.
Describe only the code-level behavior and interface; you do not need to provide a working implementation here.