Skip to content
UPEEC

Heaps

A complete binary tree where each parent is ≤ (min-heap) or ≥ (max-heap) its children.

Intermediate
Comments 0

A heap is stored in an array: the children of index ii are at 2i+12i+1 and 2i+22i+2.

  • Get min/max: O(1)O(1)
  • Insert / remove top: O(log⁡n)O(\log n)
import heapq
h = []
heapq.heappush(h, 5)
heapq.heappush(h, 1)
heapq.heappop(h)      # 1

Heaps implement priority queues — task schedulers, Dijkstra's algorithm and heap sort.

Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.

Discussion (0)

Sign in or join free to ask questions and discuss this topic.