Heap Data Structure
Heap Data Structure
A binary heap is a complete binary tree stored in an array that satisfies the heap property: in a min-heap, every parent is smaller than or equal to its children; in a max-heap, every parent is larger. This structure provides O(1) access to the minimum (or maximum) element and O(log n) insertion and deletion — making it the backbone of priority queues.
Heap Property
- Min-heap:
parent.value ≤ child.valuefor all nodes. The root is the smallest element. - Max-heap:
parent.value ≥ child.valuefor all nodes. The root is the largest element.
The heap is not fully sorted — it only guarantees the parent-child relationship, not the ordering between siblings or across subtrees.
Array Representation
A binary heap is stored as a flat array. For a node at index i:
- Parent:
(i - 1) // 2 - Left child:
2 * i + 1 - Right child:
2 * i + 2
This avoids the overhead of explicit pointers and gives excellent cache locality.
Example min-heap as tree and array:
Tree: 1
/ \
3 5
/ \
7 4
Array: [1, 3, 5, 7, 4]
Index: 0 1 2 3 4
Core Operations
| Operation | Time Complexity | Description |
|---|---|---|
peek() / get_min() | O(1) | Return the root element |
insert(value) | O(log n) | Add element, bubble up |
extract_min() | O(log n) | Remove root, bubble down |
heapify(array) | O(n) | Build heap from array |
How It Works
Insert (Bubble Up)
- Add the new element at the end of the array (next available position)
- Compare it with its parent
- If it's smaller than the parent (min-heap), swap them
- Repeat until the heap property is restored or you reach the root
Extract Min (Bubble Down)
- Save the root (minimum element) to return
- Move the last element to the root position
- Compare the new root with its children
- Swap with the smaller child if the parent is larger
- Repeat until the heap property is restored or you reach a leaf
Build Heap (Heapify)
- Start from the last non-leaf node (index
n//2 - 1) - Apply bubble-down on each node moving toward the root
- This is O(n) — faster than inserting n elements one by one (which would be O(n log n))
Step-by-Step Example
Build a min-heap from [4, 10, 3, 5, 1]:
Start: Last non-leaf at index 1 (value 10)
- Index 1: children are 5, 1. Swap with 1 →
[4, 1, 3, 5, 10] - Index 0: children are 1, 3. Swap with 1 →
[1, 4, 3, 5, 10]- Recurse: index 1 children are 5, 10. No swap needed.
Result: [1, 4, 3, 5, 10] — valid min-heap.
Insert 2: Append → [1, 4, 3, 5, 10, 2]. Bubble up: 2 < 3 → swap → [1, 4, 2, 5, 10, 3]. 2 > 1 → stop.
Extract min: Remove 1, move 3 to root → [3, 4, 2, 5, 10]. Bubble down: 2 < 3 → swap → [2, 4, 3, 5, 10]. Done.
Code Snippet
class MinHeap:
"""Min-heap implementation using an array."""
def __init__(self):
self._data = []
def size(self) -> int:
return len(self._data)
def is_empty(self) -> bool:
return len(self._data) == 0
def peek(self) -> int:
"""Return the minimum element without removing it."""
if self.is_empty():
raise IndexError("Peek at empty heap")
return self._data[0]
def insert(self, value: int) -> None:
"""Add a value to the heap."""
self._data.append(value)
self._bubble_up(len(self._data) - 1)
def extract_min(self) -> int:
"""Remove and return the minimum element."""
if self.is_empty():
raise IndexError("Extract from empty heap")
min_value = self._data[0]
last_value = self._data.pop()
if not self.is_empty():
self._data[0] = last_value
self._bubble_down(0)
return min_value
def _bubble_up(self, index: int) -> None:
"""Move element up until heap property is restored."""
while index > 0:
parent = (index - 1) // 2
if self._data[index] < self._data[parent]:
self._data[index], self._data[parent] = (
self._data[parent],
self._data[index],
)
index = parent
else:
break
def _bubble_down(self, index: int) -> None:
"""Move element down until heap property is restored."""
size = len(self._data)
while True:
smallest = index
left = 2 * index + 1
right = 2 * index + 2
if left < size and self._data[left] < self._data[smallest]:
smallest = left
if right < size and self._data[right] < self._data[smallest]:
smallest = right
if smallest == index:
break
self._data[index], self._data[smallest] = (
self._data[smallest],
self._data[index],
)
index = smallest
def heapify(numbers: list[int]) -> list[int]:
"""Convert an array into a min-heap in O(n) time."""
n = len(numbers)
# Start from last non-leaf and sift down each node
for i in range(n // 2 - 1, -1, -1):
index = i
while True:
smallest = index
left = 2 * index + 1
right = 2 * index + 2
if left < n and numbers[left] < numbers[smallest]:
smallest = left
if right < n and numbers[right] < numbers[smallest]:
smallest = right
if smallest == index:
break
numbers[index], numbers[smallest] = numbers[smallest], numbers[index]
index = smallest
return numbers
Complexity Analysis
Time Complexity:
- Peek: O(1) — the min/max is always at the root.
- Insert: O(log n) — bubble up traverses at most the height of the tree (log n levels).
- Extract min/max: O(log n) — bubble down traverses at most log n levels.
- Build heap: O(n) — not O(n log n) because most nodes are near the bottom and require few swaps.
Space Complexity: O(n)
The array stores all n elements. No extra pointers or links are needed.
Why Build Heap is O(n)
Intuitively: half the nodes are leaves (0 work), a quarter need at most 1 swap, an eighth need at most 2 swaps, and so on. The sum converges to O(n):
n/2 * 0 + n/4 * 1 + n/8 * 2 + ... = O(n)
When to Use Heaps
- Priority queues: Process tasks by priority (job schedulers, event systems).
- Dijkstra's algorithm: Extract the next closest vertex in O(log n).
- K-th largest/smallest: Maintain a heap of size k for streaming top-k problems.
- Merge k sorted lists: Use a min-heap to track the smallest element across all lists.
- Median finding: Two heaps (max-heap for lower half, min-heap for upper half) give O(1) median.
- Heap sort: In-place O(n log n) sorting.
Min-Heap vs. Max-Heap
| Property | Min-Heap | Max-Heap |
|---|---|---|
| Root | Smallest element | Largest element |
| Parent vs. child | Parent ≤ children | Parent ≥ children |
| Use case | Find minimum | Find maximum |
| Priority queue | Lowest priority first | Highest priority first |
To convert min-heap code to max-heap, simply reverse all comparison operators.
Heap vs. BST
| Property | Heap | BST |
|---|---|---|
| Find min/max | O(1) | O(log n) |
| Search arbitrary | O(n) | O(log n) |
| Insert | O(log n) | O(log n) |
| Ordered traversal | O(n log n) | O(n) |
| Memory layout | Array (cache-friendly) | Pointers |
Use a heap when you only need the min/max. Use a BST when you need arbitrary search or sorted traversal.
Key Properties
| Property | Value |
|---|---|
| Structure | Complete binary tree |
| Storage | Array-based |
| Access min/max | O(1) |
| Insert/Delete | O(log n) |
| Build from array | O(n) |
| Sorted order | No (only root guaranteed) |