Practice › Heap & Priority Queue
K Largest Elements
Easy · Heap & Priority Queue · Asked at Amazon, Microsoft, TCS, Infosys, Wipro
Print the k largest elements of the array in decreasing order.
Input
First line: n k. Second line: n integers.
Output
k integers in decreasing order, space-separated.
Constraints
- 1 ≤ k ≤ n ≤ 10^5
- −10^9 ≤ a[i] ≤ 10^9
Keep a min-heap of size k: push every element and pop when the heap grows past k. The heap ends up holding the k largest — O(n log k).
Example 1
Input
7 3 12 5 787 1 23 787 4
Output
787 787 23
Example 2
Input
3 3 1 2 3
Output
3 2 1
Hints
- Sorting the whole array works in O(n log n), but you only need k elements.
- Keep a min-heap of the k largest seen so far.
- Its top is the smallest of them — the one to throw out when something bigger arrives.
Approach
Push each element into a min-heap; whenever the heap has more than k elements, pop the top. At the end the heap holds the k largest. Pop them all (they come out in increasing order) and print in reverse. For k much smaller than n this is O(n log k).
Complexity: O(n 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;
for (int i = 0; i < n; i++) {
long long x;
cin >> x;
pq.push(x);
if ((int) pq.size() > k) pq.pop();
}
vector<long long> res;
while (!pq.empty()) {
res.push_back(pq.top());
pq.pop();
}
reverse(res.begin(), res.end());
for (int i = 0; i < k; i++) cout << res[i] << (i + 1 < k ? ' ' : '\n');
return 0;
}Python solution
import heapq
import sys
data = list(map(int, sys.stdin.read().split()))
n, k = data[0], data[1]
heap = []
for x in data[2 : 2 + n]:
heapq.heappush(heap, x)
if len(heap) > k:
heapq.heappop(heap)
print(*sorted(heap, reverse=True))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();
}
long[] res = new long[k];
for (int i = k - 1; i >= 0; i--) res[i] = pq.poll();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < k; i++) sb.append(res[i]).append(i + 1 < k ? " " : "\n");
System.out.print(sb);
}
}