Problem 398
Kth Largest in a Stream
Medium · 20 pts · Heap, Design, Data Stream
Problem
Numbers arrive one at a time. You start with N initial numbers, and then Q more numbers are added one by one. After each addition, print the K-th largest number among all the numbers so far (counting duplicates, so in 5 5 3 the 2nd largest is 5). It is guaranteed that there are at least K numbers after every addition. Keeping a min-heap of the K largest numbers answers each query in O(log K).
Input
First line: K and N. Second line: the N initial numbers (empty if N = 0). Third line: Q. Fourth line: the Q numbers to add, in order.
Output
Print Q values, the K-th largest after each addition, separated by spaces.
Constraints
1 <= K <= 10000; 0 <= N, Q <= 10000; N >= K - 1; -10000 <= value <= 10000
Example input
3 4 4 5 8 2 5 3 5 10 9 4
Example output
4 5 5 8 8
Explanation
With K = 3 and initial numbers 4 5 8 2: adding 3 gives 2 3 4 5 8, whose 3rd largest is 4. Adding 5, 10, 9 and 4 makes the 3rd largest 5, 5, 8 and 8.