Menu
CoddyTech

Kth Largest Element in a Stream

EasyHeappython iconjava iconcpp iconc iconjs icon+10

A stream of integers starts with the values in nums. Then the values of adds arrive one at a time. After each arrival, record the k-th largest value among everything seen so far, counting equal values separately. Return the recorded values in order, one for each value of adds.

nums holds at least k-1 values, so after the first arrival there are always at least k values to choose from.

Function

kthLargestStream(k: integer, nums: integer-array, adds: integer-array) → integer-array
kinteger
the rank to report, 1 for the largest value
numsinteger-array
the values already in the stream
addsinteger-array
the values that arrive, in order
Returnsinteger-array
the k-th largest value after each arrival

Constraints

  • 1 ≤ nums.length ≤ 104
  • 1 ≤ adds.length ≤ 104
  • 1 ≤ k ≤ nums.length + 1
  • -104 ≤ nums[i], adds[i] ≤ 104
  • nums can be in any order, and equal values count as separate values.

Examples

Input
k = 3nums = [7, 1, 5]adds = [3, 9, 6, 2, 8]
Output
[3, 5, 6, 6, 7]
Explanation
After 3 arrives the third largest of 7, 5, 3 and 1 is 3. Then 9 lifts it to 5, 6 lifts it to 6, 2 changes nothing, and 8 lifts it to 7 (9, 8, 7).
challenge icon

Follow-up

How would you answer the same question if values could also be removed from the stream?

Reset code
def kthLargestStream(k, nums, adds):
    # Write code here

Test #1

Test #2

Test #3

Arguments

k = 3
nums = [7, 1, 5]
adds = [3, 9, 6, 2, 8]

Expected Output

[3, 5, 6, 6, 7]