Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

DSA
Data Structures & Algorithms
0/15 completed
Beginner
Big-O and complexityArrays and stringsHash maps and setsTwo pointers and sliding windows
Intermediate
Linked listsStacks and queuesRecursion and backtrackingSorting algorithmsBinary search
Advanced
Trees and binary search treesHeaps and priority queuesGraphs: BFS and DFSDynamic programming
Pro
Shortest paths, topological sort and union-findSolving problems in coding interviews
Tracks / Data Structures & Algorithms / Advanced

Heaps and priority queues

A priority queue always gives you the item with the highest priority next, not the one that arrived first: the most urgent hospital patient, the next timer to fire, the cheapest path to explore. It's implemented with a heap, a tree-shaped structure stored in a plain array that makes both "add" and "take the best" O(log n).

The heap property

In a min-heap, every parent is smaller than (or equal to) its children, so the minimum is always at the root. The tree is kept complete (filled level by level), which lets it live in a list without pointers:

           1                 index:  0  1  2  3  4  5  6
         /   \               value: [1, 3, 2, 7, 4, 5, 6]
        3     2
       / \   / \             children of i: 2i + 1 and 2i + 2
      7   4 5   6            parent of i:   (i - 1) // 2

Building one from scratch

Python · editable

Height is log₂ n, so sifting up or down takes at most O(log n) swaps.

Python's heapq

Use the standard library. heapq works on an ordinary list as a min-heap:

Python · editable

For a max-heap, push negated keys: heapq.heappush(h, (-score, name)).

Top-k with a heap

To find the k largest of n items, keep a min-heap of size k: the smallest of your current top k sits at the root, ready to be replaced. That's O(n log k) time and O(k) memory, which works even for a stream too big to sort:

Python · editable

Merging k sorted lists

Each list's next item goes into a heap; repeatedly take the smallest. O(n log k) for n total items, the basis of external sorting and of databases merging sorted files:

Python · editable

Running median with two heaps

Keep the lower half in a max-heap and the upper half in a min-heap, balanced in size. The median is always at one or both roots:

Python · editable

Scheduling with a heap

Rooms needed for a set of meetings: sort by start time, and keep a min-heap of end times of meetings in progress:

Python · editable

Operating system schedulers, timer wheels, event simulations and Dijkstra's shortest-path algorithm (in the advanced graphs lesson) all run on heaps.

Heap operations at a glance

Operation Cost
Peek at the min O(1)
Push O(log n)
Pop the min O(log n)
Build from n items (heapify) O(n)
Search for an arbitrary item O(n): heaps aren't sorted

Practice

  1. Find the k-th largest element in a list using a heap of size k.
  2. Sort a "nearly sorted" list where each item is at most k places from its final position, in O(n log k).
  3. Simulate a hospital queue: patients have a severity (1 = most urgent) and arrival order; urgent first, then first come, first served.
✎ Check your understanding

1.Where is the smallest item in a min-heap?

2.What does pushing onto a heap of n items cost?

3.How do you find the 10 largest numbers in a stream of a billion numbers with little memory?

← Trees and binary search trees