Practice › Heap & Priority Queue
Kth Largest in a Stream
Medium · Heap & Priority Queue · Asked at Amazon, Meta, Microsoft, Adobe
You start with n numbers. Then q more numbers arrive one at a time. After each new number arrives, print the k-th largest of all numbers seen so far (duplicates count separately).
Input
First line: n k. Second line: the n starting numbers. Third line: q. Fourth line: the q new numbers in order.
Output
q lines — the k-th largest after each new number.
Constraints
- 1 ≤ n ≤ 10^5
- 1 ≤ k ≤ n + 1
- 1 ≤ q ≤ 10^5
- −10^9 ≤ values ≤ 10^9
Keep only the k largest numbers in a min-heap. Its top is the k-th largest. A new number replaces the top only if it is bigger — O(log k) per number.
Example 1
Input
4 3 4 5 8 2 5 3 5 10 9 4
Output
4 5 5 8 8
Hints
- Numbers smaller than the current k-th largest can never matter again.
- So keep only the k largest numbers — in a min-heap.
- Its top is exactly the k-th largest.
Approach
Add every starting number to a min-heap, popping whenever its size exceeds k. For each new number do the same and print the top. The heap never holds more than k + 1 numbers, so each step costs O(log k). Because k ≤ n + 1, the heap has exactly k numbers after the first new one arrives.
Complexity: O((n + q) log k) time · O(k) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, k;
cin >> n >> k;
priority_queue<long long, vector<long long>, greater<long long>> pq;
auto add = [&](long long x) {
pq.push(x);
if ((int) pq.size() > k) pq.pop();
};
for (int i = 0; i < n; i++) {
long long x;
cin >> x;
add(x);
}
int q;
cin >> q;
while (q--) {
long long x;
cin >> x;
add(x);
cout << pq.top() << "\n";
}
return 0;
}Python solution
import heapq
import sys
data = list(map(int, sys.stdin.read().split()))
n, k = data[0], data[1]
heap = []
def add(x):
heapq.heappush(heap, x)
if len(heap) > k:
heapq.heappop(heap)
for x in data[2 : 2 + n]:
add(x)
q = data[2 + n]
out = []
for x in data[3 + n : 3 + n + q]:
add(x)
out.append(heap[0])
print("\n".join(map(str, out)))Java solution
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
in.nextToken();
int k = (int) in.nval;
PriorityQueue<Long> pq = new PriorityQueue<>();
for (int i = 0; i < n; i++) {
in.nextToken();
pq.add((long) in.nval);
if (pq.size() > k) pq.poll();
}
in.nextToken();
int q = (int) in.nval;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < q; i++) {
in.nextToken();
pq.add((long) in.nval);
if (pq.size() > k) pq.poll();
sb.append(pq.peek()).append('\n');
}
System.out.print(sb);
}
}Solve Kth Largest in a Stream online · All practice problems