heapq · Python
heap[0]
Reads the minimum without removing it.
heap[0]
Complexity
| Best case | O(1) |
|---|---|
| Worst case | O(1) |
| Extra space | O(1) |
The heap invariant places the minimum at index 0.
Tested example
heap = [5, 9, 7]
heapq.heapify(heap)
assert heap[0] == 5 # the minimum is always at index 0
assert len(heap) == 3 # nothing removed
# heap[1:] is only heap-ordered (each parent <= its children), not sorted
Behaviour
- Returns
- The smallest item.
- Errors and preconditions
- IndexError if the heap is empty.
- Changes
- Nothing.
- Memory and invalidation
- No allocation.