Editorial for K-th Smallest Stream
Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.
Submitting an official solution before solving the problem yourself is a bannable offence.
Approach
We want the -th smallest after each prefix.
A direct sort of every prefix is too slow.
Keep a max-heap containing exactly the smallest values seen so far.
- If the heap has fewer than
values, push the new value.
- Otherwise, compare the new value to the largest inside this set (the heap top).
- If the new value is smaller, it belongs in the
smallest set, so replace the top.
- Otherwise ignore it.
- If the new value is smaller, it belongs in the
Then:
- if heap size is less than
, answer is
-1; - else the heap top is the current
-th smallest.
In Python, heapq is a min-heap, so we store negatives to simulate a max-heap.
Time complexity is .
Solution (Python)
import heapq
n, k = map(int, input().split())
values = list(map(int, input().split()))
heap = []
answers = []
for x in values:
if len(heap) < k:
heapq.heappush(heap, -x)
elif x < -heap[0]:
heapq.heapreplace(heap, -x)
if len(heap) < k:
answers.append("-1")
else:
answers.append(str(-heap[0]))
print("\n".join(answers))
Comments