Heap and priority queue

A heap is an almost complete binary tree where each parent is smaller (min-heap) or larger (max-heap) than its children. It gives access to the minimum or maximum in O(1), and both insertion and extraction are O(log n). It is the common implementation of the priority queue.

Example

import heapq
h = []
heapq.heappush(h, 5)
heapq.heappush(h, 2)
heapq.heappop(h)  # 2

Related concepts

The whole glossary