What is a Heap?
Solution and explanation
What it is
A heap is a complete binary tree that satisfies the heap property:
- Min-heap: every parent is smaller than or equal to its children, so the smallest element is at the root.
- Max-heap: every parent is greater than or equal to its children, so the largest element is at the root.
"Complete" means every level is full except possibly the last, which is filled from the left. Because of this shape, a heap is stored compactly in an array with no pointers.
Min-heap Array: [1, 3, 5, 7, 9, 8]
1 index: 0 1 2 3 4 5
/ \
3 5 For index i:
/ \ / parent = (i - 1) / 2
7 9 8 left = 2i + 1
right = 2i + 2
Core operations
- peek (min or max): O(1) – it is at index 0.
- insert: add at the end, then "sift up" (swap with the parent while the property is violated): O(log n).
- extract (remove root): move the last element to the root, then "sift down" (swap with the smaller child): O(log n).
- build a heap from n elements: O(n) using bottom-up heapify.
Min-heap implementation
class MinHeap {
private final List<Integer> a = new ArrayList<>();
void insert(int x) {
a.add(x);
int i = a.size() - 1;
while (i > 0 && a.get((i - 1) / 2) > a.get(i)) { // sift up
Collections.swap(a, i, (i - 1) / 2);
i = (i - 1) / 2;
}
}
int extractMin() {
int min = a.get(0);
int last = a.remove(a.size() - 1);
if (!a.isEmpty()) {
a.set(0, last);
int i = 0;
while (true) { // sift down
int l = 2 * i + 1, r = 2 * i + 2, smallest = i;
if (l < a.size() && a.get(l) < a.get(smallest)) smallest = l;
if (r < a.size() && a.get(r) < a.get(smallest)) smallest = r;
if (smallest == i) break;
Collections.swap(a, i, smallest);
i = smallest;
}
}
return min;
}
}
Using Java's PriorityQueue
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
for (int x : new int[]{5, 1, 8, 3}) { minHeap.offer(x); maxHeap.offer(x); }
System.out.println(minHeap.poll() + " " + maxHeap.poll()); // 1 8
Complexity summary
- Get min/max: O(1). Insert: O(log n). Extract: O(log n). Build: O(n).
- Search for an arbitrary value: O(n) – a heap is not sorted, only partially ordered.
Applications
- Priority queues: task scheduling, hospital triage, event simulation.
- Dijkstra's and Prim's algorithms.
- Top-K and K-th largest problems, running median (two heaps).
- Heap sort (O(n log n), in place).
- Merging K sorted lists or files.
Note: heaps are not BSTs. A BST orders left < parent < right; a heap only orders parent vs children.
