If you’ve been preparing for coding interviews in 2026, you already know that heap-based problems are among the most frequently tested patterns at top tech companies. Google, Amazon, Meta, Microsoft — they all love heap questions because they test your ability to think about efficiency, trade-offs, and data structure selection under pressure.
In this comprehensive guide, we’ll break down the three most important heap patterns — Top-K Elements, Merge K Sorted Lists, and the Two-Heap pattern — with clean Java implementations, common mistakes to avoid, and a practical 5-day practice plan to get you interview-ready.

What Is a Heap / Priority Queue?
A heap is a specialized complete binary tree that satisfies the heap property: in a min-heap, every parent node is smaller than or equal to its children; in a max-heap, every parent is larger than or equal to its children. This structure gives us O(log n) insertion and deletion, and O(1) access to the minimum (or maximum) element.
In Java, the PriorityQueue class implements a min-heap by default. To create a max-heap, you simply pass Collections.reverseOrder() or a custom comparator. Here is a quick setup:
// Min-Heap (default)
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
// Max-Heap
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
When to use a heap: Whenever you need to repeatedly access the smallest or largest element from a dynamic collection. Classic signals in interview problems include phrases like “kth largest,” “top K,” “k most frequent,” “median,” or “merge k sorted.”
Pattern 1: Top-K Elements
The Top-K pattern is the bread and butter of heap interview problems. The core idea is simple: maintain a heap of size K to efficiently track the K largest (or smallest) elements without sorting the entire input.
Problem: Kth Largest Element in an Array
Given an unsorted array, find the kth largest element. This is LeetCode 215 and one of the most asked interview questions of all time.
public int findKthLargest(int[] nums, int k) {
// Use a min-heap of size k
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for (int num : nums) {
minHeap.offer(num);
if (minHeap.size() > k) {
minHeap.poll(); // Remove the smallest
}
}
return minHeap.peek(); // The kth largest
}
// Time: O(n log k) | Space: O(k)
Why a min-heap of size K? By evicting the smallest element whenever the heap exceeds size K, we guarantee that the heap always contains the K largest elements. The root of the min-heap is the smallest among those K elements — which is exactly the Kth largest overall.
Problem: Top K Frequent Elements
Given an integer array, return the k most frequent elements (LeetCode 347). This combines a frequency map with the Top-K heap pattern.
public int[] topKFrequent(int[] nums, int k) {
// Step 1: Build frequency map
Map<Integer, Integer> freqMap = new HashMap<>();
for (int num : nums) {
freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
}
// Step 2: Use min-heap of size k, ordered by frequency
PriorityQueue<Integer> minHeap = new PriorityQueue<>(
(a, b) -> freqMap.get(a) - freqMap.get(b)
);
for (int num : freqMap.keySet()) {
minHeap.offer(num);
if (minHeap.size() > k) {
minHeap.poll();
}
}
// Step 3: Extract results
int[] result = new int[k];
for (int i = 0; i < k; i++) {
result[i] = minHeap.poll();
}
return result;
}
// Time: O(n log k) | Space: O(n)
Problem: K Closest Points to Origin
Given an array of points, find the K closest points to the origin (0, 0). This is LeetCode 973 and a Meta/Google favorite.
public int[][] kClosest(int[][] points, int k) {
// Max-heap by distance — evict the farthest
PriorityQueue<int[]> maxHeap = new PriorityQueue<>(
(a, b) -> (b[0]*b[0] + b[1]*b[1]) - (a[0]*a[0] + a[1]*a[1])
);
for (int[] point : points) {
maxHeap.offer(point);
if (maxHeap.size() > k) {
maxHeap.poll();
}
}
return maxHeap.toArray(new int[0][]);
}
// Time: O(n log k) | Space: O(k)

Pattern 2: Merge K Sorted Lists
The Merge K Sorted Lists pattern (LeetCode 23) is another heap classic. The idea is to use a min-heap to always pick the smallest element across all K lists, achieving an efficient merge without comparing all heads manually.
public ListNode mergeKLists(ListNode[] lists) {
PriorityQueue<ListNode> minHeap = new PriorityQueue<>(
(a, b) -> a.val - b.val
);
// Add the head of each non-null list
for (ListNode node : lists) {
if (node != null) {
minHeap.offer(node);
}
}
ListNode dummy = new ListNode(0);
ListNode current = dummy;
while (!minHeap.isEmpty()) {
ListNode smallest = minHeap.poll();
current.next = smallest;
current = current.next;
if (smallest.next != null) {
minHeap.offer(smallest.next);
}
}
return dummy.next;
}
// Time: O(N log k) where N = total nodes | Space: O(k)
Key insight: The heap always holds at most K nodes (one from each list), so each insertion and extraction is O(log K). We process every node exactly once, giving us O(N log K) total time — a massive improvement over the brute-force O(N·K) approach.
Pattern 3: Two-Heap — Find Median from Data Stream
The two-heap pattern is one of the most elegant data structure techniques in all of interview prep. By maintaining a max-heap for the lower half of numbers and a min-heap for the upper half, you can find the median in O(1) time after O(log n) insertions.
class MedianFinder {
private PriorityQueue<Integer> maxHeap; // lower half
private PriorityQueue<Integer> minHeap; // upper half
public MedianFinder() {
maxHeap = new PriorityQueue<>(Collections.reverseOrder());
minHeap = new PriorityQueue<>();
}
public void addNum(int num) {
maxHeap.offer(num);
minHeap.offer(maxHeap.poll()); // Balance
// Keep maxHeap same size or 1 larger
if (minHeap.size() > maxHeap.size()) {
maxHeap.offer(minHeap.poll());
}
}
public double findMedian() {
if (maxHeap.size() > minHeap.size()) {
return maxHeap.peek();
}
return (maxHeap.peek() + minHeap.peek()) / 2.0;
}
}
// addNum: O(log n) | findMedian: O(1) | Space: O(n)
How it works: Every new number first goes into the max-heap (lower half), then the max of the lower half moves to the min-heap (upper half). If the upper half grows larger, we rebalance. This invariant ensures the median is always at one or both heap roots.

Common Mistakes and Interview Tips
After reviewing hundreds of interview submissions, here are the mistakes that trip candidates up the most:
- Using the wrong heap type. For "K largest," use a min-heap of size K (not a max-heap). For "K smallest," use a max-heap of size K. This is counterintuitive but essential — you evict the element you don't want.
- Forgetting to handle null or empty inputs. Always check if lists, arrays, or nodes are null before adding to the heap.
- Integer overflow in comparators. Using
a - bcan overflow for large integers. PreferInteger.compare(a, b)in production code. - Not recognizing heap signals. If the problem says "kth," "top," "smallest/largest K," "median," or "merge sorted" — think heap immediately.
- Overcomplicating with sorting. Sorting gives O(n log n). A heap-based Top-K solution is O(n log k), which is faster when k is much smaller than n.
Pro tip: In interviews, always state the time and space complexity out loud after writing your solution. Interviewers notice and appreciate this. For heap problems, the pattern is almost always O(n log k) time and O(k) space.
5-Day Heap Mastery Practice Plan
Follow this structured plan to build confidence with heap patterns. Spend 60–90 minutes per day.
| Day | Focus Area | Problems to Solve |
|---|---|---|
| Day 1 | Heap Fundamentals | Kth Largest Element (LC 215), Last Stone Weight (LC 1046), Kth Largest in Stream (LC 703) |
| Day 2 | Top-K Pattern | Top K Frequent Elements (LC 347), K Closest Points (LC 973), Sort Characters by Frequency (LC 451) |
| Day 3 | Merge K Sorted | Merge K Sorted Lists (LC 23), Kth Smallest in Sorted Matrix (LC 378), Find K Pairs with Smallest Sums (LC 373) |
| Day 4 | Two-Heap Pattern | Find Median from Data Stream (LC 295), Sliding Window Median (LC 480), IPO (LC 502) |
| Day 5 | Mixed Review + Timed | Reorganize String (LC 767), Task Scheduler (LC 621), Ugly Number II (LC 264). Do each under 25 minutes. |
Start Practicing Today
Heap and priority queue patterns are not going away — if anything, they are appearing more in 2026 interviews as companies raise the bar on data structure fluency. The three patterns we covered today — Top-K, Merge K Sorted, and Two-Heap — will help you solve the majority of heap problems you encounter.
Bookmark this page, follow the 5-day practice plan, and come back to review the code templates before your next interview. If you found this guide helpful, share it with a friend who is also preparing. For more data structures and algorithms content, explore our other coding interview guides on this blog and subscribe for weekly updates. Good luck — you've got this!
