Java Data Structure Program · OT74
Implement a Min Heap in Java
A binary heap is a complete tree stored in an array: the children of index i are at 2i + 1 and 2i + 2. Each parent is no larger than its children, so the minimum is always at index 0.
Problem Statement
Implement a min heap of integers with insert, peek (smallest value), extractMin (remove and return the smallest value) and size.
peek and extractMin on an empty heap must throw an exception.
Input/Output Examples
insert 5, 3, 8, 1; peek()Output1Explanation: the smallest value is at the root.extractMin()Output1Explanation: then 3 becomes the root.insert 2, then extract until emptyOutput2 3 5 8Explanation: values come out in ascending order.Visual Explanation
- Insert 5, 3, 8array3583 sifts up past 5
- Insert 1array13851 sifts up to the root
- extractMinarray358last value moves to the root and sifts down
- Donereturned 1
The tree is always complete, so its height is log2 n, and each sift moves along one root-to-leaf path.
Approaches
The array heap gives logarithmic operations. The sorted list is a simple reference that trades fast extraction for slow insertion.
Approach 1: Array-Based Binary Heap (Recommended)
Idea: store the tree in an array; sift up after insert and sift down after removing the root.
- Insert: put the value at the end, then swap with the parent while it is smaller.
- Extract: save the root, move the last value to the root, then swap it with its smaller child while needed.
- Double the array when it is full.
Time: O(log n) · Space: O(n).
Approach 2: Sorted List
Idea: keep values sorted in a list, inserting each at its binary-search position.
- Insert at the position found by
Collections.binarySearch(). - The minimum is always at index 0.
- Extract by removing index 0.
Time: O(n) insert and extract · Space: O(n).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Array-Based Binary Heap (Recommended)
This is how java.util.PriorityQueue is implemented.
import java.util.Arrays;
public class MinHeapArray {
// Array-backed binary heap: children of i are 2i + 1 and 2i + 2, parent is (i - 1) / 2
static class MinHeap {
private int[] a = new int[4];
private int size = 0;
void insert(int v) {
if (size == a.length) {
a = Arrays.copyOf(a, size * 2);
}
a[size] = v;
int i = size++;
while (i > 0 && a[(i - 1) / 2] > a[i]) { // sift up
swap(i, (i - 1) / 2);
i = (i - 1) / 2;
}
}
int peek() {
if (size == 0) {
throw new IllegalStateException("heap is empty");
}
return a[0];
}
int extractMin() {
int min = peek();
a[0] = a[--size];
int i = 0;
while (true) { // sift down
int l = 2 * i + 1, r = l + 1, smallest = i;
if (l < size && a[l] < a[smallest]) smallest = l;
if (r < size && a[r] < a[smallest]) smallest = r;
if (smallest == i) break;
swap(i, smallest);
i = smallest;
}
return min;
}
int size() { return size; }
private void swap(int i, int j) {
int t = a[i]; a[i] = a[j]; a[j] = t;
}
}
public static void main(String[] args) {
MinHeap h = new MinHeap();
for (int v : new int[] {5, 3, 8, 1}) {
h.insert(v);
}
System.out.println("after inserting 5, 3, 8, 1: peek() = " + h.peek());
System.out.println("extractMin() = " + h.extractMin());
h.insert(2);
StringBuilder rest = new StringBuilder();
while (h.size() > 0) {
rest.append(h.extractMin()).append(h.size() > 0 ? " " : "");
}
System.out.println("insert 2, then extract all: " + rest);
try {
h.extractMin();
} catch (IllegalStateException e) {
System.out.println("extractMin() on empty -> " + e.getMessage());
}
}
}
after inserting 5, 3, 8, 1: peek() = 1 extractMin() = 1 insert 2, then extract all: 2 3 5 8 extractMin() on empty -> heap is empty
Time complexity: O(log n) · Space complexity: O(n).
Approach 2: Sorted List
Simple but slow, because inserting or removing at the front of an ArrayList shifts elements.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MinHeapSortedList {
// A naive "priority queue": keep a sorted list (O(n) insert, O(1) extract), for comparison
static class MinHeap {
private final List<Integer> list = new ArrayList<>();
void insert(int v) {
int pos = Collections.binarySearch(list, v);
list.add(pos >= 0 ? pos : -pos - 1, v);
}
int peek() {
if (list.isEmpty()) {
throw new IllegalStateException("heap is empty");
}
return list.get(0);
}
int extractMin() {
int min = peek();
list.remove(0);
return min;
}
int size() { return list.size(); }
}
public static void main(String[] args) {
MinHeap h = new MinHeap();
for (int v : new int[] {5, 3, 8, 1}) {
h.insert(v);
}
System.out.println("after inserting 5, 3, 8, 1: peek() = " + h.peek());
System.out.println("extractMin() = " + h.extractMin());
h.insert(2);
StringBuilder rest = new StringBuilder();
while (h.size() > 0) {
rest.append(h.extractMin()).append(h.size() > 0 ? " " : "");
}
System.out.println("insert 2, then extract all: " + rest);
try {
h.extractMin();
} catch (IllegalStateException e) {
System.out.println("extractMin() on empty -> " + e.getMessage());
}
}
}
after inserting 5, 3, 8, 1: peek() = 1 extractMin() = 1 insert 2, then extract all: 2 3 5 8 extractMin() on empty -> heap is empty
Time complexity: O(n) insert and extract · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Array-Based Binary Heap | O(log n) | O(n) |
| Sorted List | O(n) insert and extract | O(n) |
Here n is the number of elements. The heap's insert and extract follow one path of length log n; peek is O(1). Building a heap from n values at once can be done in O(n).
Interview Tips and Recommended Approach
- Know the index formulas: parent
(i - 1) / 2, children2i + 1and2i + 2. - Sift down towards the smaller child, or the heap property breaks.
- Know heapify. Sifting down from the middle to the root builds a heap in linear time.
- Know the uses: priority queues, heap sort, Dijkstra and top-k problems.
Recommended Approach: Array-Based Binary Heap
Why: it gives logarithmic insert and extract with a single array and no pointers, which is why the JDK uses the same design.