Skip to content
CodeItRaw
Heaps & Priority Queues

Lesson 1/2

Sometimes you want to keep taking the smallest of a pile of numbers while adding new ones in between. Sorting the list again every time is costly, and so is searching for min every time. A heap is for exactly this: both adding and taking out the smallest finish in log n steps.

import heapq
heap = []
for v in [5, 1, 8, 3]:
heapq.heappush(heap, v)
first = heapq.heappop(heap) # 1
second = heapq.heappop(heap) # 3
smallest_left = heap[0] # 5
In Python a heap is an ordinary list; what makes it a heap is the heapq functions. heappush adds, heappop takes out the smallest, heap[0] looks at the smallest without removing it. To turn a list you already have into a heap in one go there is heapq.heapify(values).

Put n numbers on a heap and take them out one by one and they come out sorted; n pushes and n pops at log n each: n log n in all. So sorting with a heap is in the same class as a good sort. The heap's real gain shows when you do not need all of the sorted order.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    Pop the Smallest

    Code reading · Predict the Output

  2. 02

    Sorting with a Heap

    Code reading · Read the Big-O

If you would rather not wait for the order, every problem is open without locks: Problem list