What Is a Heap
A heap is a complete binary tree where each node satisfies the heap property: in a min-heap, every parent node is less than or equal to its children; in a max-heap, every parent is greater than or equal to its children. This structure enables constant-time access to the minimum or maximum element, making heaps ideal for priority queues and efficient sorting.
Heaps are stored in arrays using a simple indexing scheme: for a node at index i, its left child is at 2i + 1, right child at 2i + 2, and parent at floor((i - 1)/2). This compact layout avoids pointer overhead and supports efficient traversal.
The heap property helps the root is always the smallest (min-heap) or largest (max-heap) element. This allows operations like insert and extract-min/max to run in O(log n) time, which is faster than maintaining a sorted range.
How a Heap Works
When inserting a new element, it's added at the end of the range and then "bubbled up" by comparing it with its parent and swapping if necessary to restore the heap property. This process continues until the element reaches a valid position.
To remove the root (the minimum or maximum), the last element in the range replaces it. Then, the new root is "bubbled down" by comparing it with its children and swapping with the smaller (in min-heap) or larger (in max-heap) child. This continues until the heap property is restored.
For example, inserting 1 into a min-heap containing [3, 5, 6] results in [1, 3, 6, 5]. The 1 swaps with 3, then stops because 1 < 3. Removing the root gives [5, 6], with 5 replacing the root and bubbling down.
Types of Heaps
There are two primary types:
| Type | Heap Property | Use Case | Example |
|---|---|---|---|
| Min-Heap | Parent ≤ Children | Prioritizing low values (e.g., task scheduling) | Root = 2, children = 4, 5 |
| Max-Heap | Parent ≥ Children | Prioritizing high values (e.g., critical alerts) | Root = 9, children = 7, 6 |
Both types maintain the complete binary tree structure. A complete tree means all levels are filled except possibly the last, which is filled left-to-right. This guarantees logarithmic height and efficient operations.
While binary heaps are most common, variants exist. Fibonacci heaps offer better amortized performance for certain operations, though they're complex and rarely used in practice. Binary heaps remain standard due to simplicity and predictable behavior.
Common Misconceptions and Clarifications
Many confuse heaps with binary search trees (BSTs). Unlike BSTs, heaps do not maintain sorted order between siblings or across levels. A heap only enforces parent-child ordering. For example, a min-heap may have a left child larger than a right child, which is invalid in a BST.
Another misconception is that heaps are inherently sorted. They are not. The entire structure is not ordered. Only the root is likely to be the minimum or maximum. Elements can appear in any order below the root.
Heaps are not the same as priority queues, though they're often used together. A priority queue is an abstract data type that supports insertion and extraction of the highest-priority element. A heap is one implementation of a priority queue. Other implementations exist, such as balanced BSTs or arrays, but heaps are preferred for their O(log n) performance and space efficiency.
Practical Uses and Real-World Examples
Heaps underlie many algorithms. Dijkstra's shortest path algorithm uses a min-heap to efficiently select the next closest vertex. Heapsort sorts an range in O(n log n) time by repeatedly extracting the minimum and placing it at the end.
In operating systems, process schedulers use min-heaps to prioritize tasks based on urgency or deadline. The kernel extracts the highest-priority task from the heap and runs it. New tasks are inserted into the heap with their priority level.
I once implemented a job scheduler for a web scraping service. Each job had a priority (1-10) and a delay. Using a min-heap with priority and timestamp as keys, I ensured jobs ran in correct order even when multiple were queued simultaneously. The heap maintained consistency during changing inserts and removals.
According to the Wikipedia entry on heaps, the term was introduced by J. W. J. Williams in 1964 for his heapsort algorithm. The structure was later refined by Robert W. Floyd, who optimized the heap construction phase.
Python's heapq module implements a min-heap using a list. It provides functions like heappush, heappop, and heapify. The module assumes the underlying list represents a min-heap. To simulate a max-heap, negate values during insertion and reversal during extraction.
Key Distinction: Heap vs Range
An range can store elements in any order. A heap enforces a specific structural constraint. While both use arrays internally, only a heap guarantees the heap property.
For example, the range [3, 5, 6] can represent a valid min-heap with 3 as root and 5, 6 as children. But [6, 5, 3] violates the min-heap property because 6 > 5 and 6 > 3, even though it's a valid range.
This distinction matters when choosing data structures. If you need fast access to the smallest element, a heap is optimal. If you need sorted traversal, use a sorted range or BST.
Understanding what is a heap is foundational for efficient algorithm design. Its ability to balance speed, memory usage, and correctness makes it indispensable in systems requiring priority-based processing.