Skip to content

Heap Basics

Lesson 1 of 7 · 5 min

Heap Basics

Step 1 of 25

Four bids in a plain array. Read as a tree, index i parents 2i+1 and 2i+2 — that arithmetic is the tree.

The Idea

A heap is a complete binary tree where every parent beats its children — smaller, in a min-heap. That is a much weaker promise than sorting, and much cheaper to keep.

Only the root is guaranteed. Push and pop cost O(log n); peeking at the winner costs O(1). The tree lives in a plain array: node i has children at 2i + 1 and 2i + 2.

Real-World Example

An auction house's bid board only ever shows the current highest offer. Nobody maintains a full ranking of every bid ever shouted — that work would be wasted, because only the top one can win. A new bid either takes the board or quietly disappears into the pile.

The Code

Your turn

What does this print?

import heapq
h = [5, 8, 2]
heapq.heapify(h)
heapq.heappush(h, 4)
print(heapq.heappop(h), heapq.heappop(h))

Mini quiz

1 / 3

In a min-heap, what is guaranteed about the value at index 0?