joseiedo
Heap Patterns
Overview

Heap Patterns

January 16, 2026
1 min read

Find Top K Elements

import java.util.PriorityQueue;
public int[] fn(int[] arr, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<>(CRITERIA);
for (int num: arr) {
// TODO: logic to push onto heap according to problem's criteria
heap.add(num);
if (heap.size() > k) {
heap.remove();
}
}
int[] ans = new int[k];
for (int i = 0; i < k; i++) {
ans[i] = heap.remove();
}
return ans;
}