Heaps¶
A heap is a complete binary tree satisfying the heap property: min-heap (parent ≤ children) or max-heap (parent ≥ children). Backed by an array. Insert and extract in O(log n), peek in O(1). Java's PriorityQueue is a min-heap. Key use cases: Top K elements, median finding (two heaps), merge K sorted lists, task scheduling.
Key Concepts¶
Deep Dive: Heap Operations
Deep Dive: Top K Problems
K Largest Elements (min-heap of size K):
public int[] topKLargest(int[] nums, int k) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for (int num : nums) {
minHeap.offer(num);
if (minHeap.size() > k) minHeap.poll();
}
return minHeap.stream().mapToInt(i -> i).toArray();
}
// Time: O(n log k), Space: O(k)
K Closest Points to Origin:
Deep Dive: Find Median from Data Stream (Two Heaps)
class MedianFinder {
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder()); // left half
PriorityQueue<Integer> minHeap = new PriorityQueue<>(); // right half
public void addNum(int num) {
maxHeap.offer(num);
minHeap.offer(maxHeap.poll());
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;
}
}
Common Interview Questions
- Kth Largest Element in an Array
- Top K Frequent Elements
- Find Median from Data Stream
- Merge K Sorted Lists
- K Closest Points to Origin
- Task Scheduler