Kth Largest Element in Stream
Practice this coding question on Coding Gurukul.
Problem statement
A weather station keeps a rolling report of the largest gust measurements seen since startup. The archive initially contains some readings, and more readings arrive one at a time. After each arrival, the report must show the value currently occupying rank k when every recorded reading is ordered from largest to smallest. Your task Initialize the stream with n values. For each of q additional values, insert it permanently and print the kth largest value among all readings so far. Equal readings occupy separate ranking positions; this is not the kth distinct value. The initial archive may be empty when k is 1. There will be at least k readings after every insertion that needs an answer. Do not print an answer before the first new reading. Maintain the largest k values in a min heap for O(log k) processing per insertion and O(k) storage. Worked example With k=2 and initial readings [6, 1], adding 4 gives ranked readings [6, 4, 1], so print 4. Adding another 6 gives [6, 6, 4, 1], so print 6. Adding 0 leaves the second-largest value at 6.
Input format
First line: k n q. Next n integers: initial readings (this section is empty when n=0). Next q integers: new readings in arrival order. Whitespace may separate readings across lines.
Output format
Print the kth largest value after each new reading, one per line.
Constraints
0 <= n <= 10000; 1 <= k <= n+1; 1 <= q <= 10000; -10000 <= value <= 10000.
Sample input
2 2 3 6 1 4 6 0
Sample output
4 6 6
Sign in to run or submit a solution in C++, Java or Python.