A topic in the Open Knowledge Graph — a free, open map of 15,290 topics and the order to learn them in.

Heaps and Priority Queues

College Depth 85 in the knowledge graph ☐ I know this ☆ Set as goal
51topics build on this
458prerequisites beneath it
See this on the map →
Binary TreesQueues+1 more→→Dijkstra's AlgorithmFibonacci Heaps and Amortized Analysis+3 more
heap priority-queue min-heap max-heap heapify

Core Idea

A heap is a complete binary tree satisfying the heap property: in a max-heap, every parent is greater than or equal to its children; in a min-heap, every parent is smaller. Heaps are efficiently stored in arrays using index arithmetic: the parent of node i is ⌊(i−1)/2⌋ and its children are 2i+1 and 2i+2. Insertion and deletion each run in O(log n). A priority queue is an abstract data type most commonly implemented with a heap, supporting O(log n) insertion and O(1) peek at the min/max element.

How It's Best Learned

Implement a min-heap from scratch using an array. Carefully trace the sift-up (after insertion) and sift-down (after extraction) operations. Then use Python's heapq module and verify it matches your implementation.

Common Misconceptions

Explainer

You already know that a binary tree organizes data hierarchically and that a queue serves elements in first-in, first-out order. A heap merges these ideas into something new: a binary tree where the ordering rule applies only between parents and children, not across siblings. In a min-heap, every parent is smaller than or equal to its children, which guarantees the smallest element is always at the root. A max-heap flips this so the largest element sits on top. Unlike a binary search tree, a heap makes no promise about left-versus-right ordering — it only enforces the vertical parent-child relationship. This weaker constraint is exactly what makes heaps fast for their intended purpose: quickly accessing the extreme element.

The elegant trick behind heaps is that they can be stored in a plain array rather than a tree of linked nodes. Because a heap is a complete binary tree — every level is fully filled except possibly the last, which fills left to right — there are no gaps in the array. For a node at index `i`, its left child is at `2i + 1`, its right child at `2i + 2`, and its parent at `⌊(i−1)/2⌋`. This index arithmetic replaces pointers entirely, giving you cache-friendly memory access and zero overhead for storing child/parent links. When you insert a new element, you place it at the end of the array (the next open leaf position) and sift up: compare it with its parent, swap if the heap property is violated, and repeat until it settles. When you extract the root (the min or max), you move the last element to the root and sift down: compare it with its children, swap with the smaller (or larger) child, and repeat. Both operations follow a single root-to-leaf or leaf-to-root path, so they run in O(log n) time — the height of the tree.

A priority queue is the abstract interface that heaps implement. It supports three operations: insert an element with a priority, peek at the highest-priority element in O(1), and extract (remove) the highest-priority element in O(log n). You can think of it as a queue where cutting in line is allowed based on urgency. Priority queues appear everywhere: operating system schedulers pick the highest-priority process, Dijkstra's algorithm always relaxes the nearest unvisited node, and event-driven simulations process the earliest upcoming event. In each case, the key requirement is the same — efficiently find and remove the extreme element from a dynamic collection.

One important subtlety: a heap is not sorted. The min-heap guarantee only means the root is the smallest — the second-smallest element could be anywhere in the second level. If you need all elements in order, you must extract them one at a time, each extraction costing O(log n), for a total of O(n log n). This is exactly what heapsort does. But if you only ever need the current minimum or maximum, a heap gives you that in constant time with logarithmic maintenance — a sweet spot that no sorted array or balanced BST matches for this specific access pattern.

Practice Questions 5 questions

Prerequisite Chain

Understanding Zero → The Number Zero → Counting to Five → Counting to 10 → Counting to 20 → Counting a Set of Objects Up to 20 → Cardinality: The Last Number Counted → Matching Numerals to Quantities → Subitizing Small Quantities → Addition Within 10 → Number Bonds to 10 → Addition Within 20 → Doubles and Near Doubles → Doubles Facts Within 10 → Near Doubles Facts Within 20 → Mental Math Strategies for Addition → Mental Math: Adding and Subtracting Tens → Addition Within 100 → Repeated Addition as Multiplication → Multiplication as Equal Groups → Multiplication: Arrays → Basic Multiplication Facts (0s, 1s, 2s, 5s, 10s) → Multiplication Facts Within 100 → Division as Equal Sharing → Division as Grouping (Measurement Division) → Division: Grouping (Repeated Subtraction) Model → Division: Fair Sharing Model → Division as Equal Sharing → Division as Grouping → Basic Division Facts → Division Facts Within 100 → Multiplication and Division Fact Families → Relationship Between Multiplication and Division → Division Facts as Inverse of Multiplication → Remainders and Quotients in Division → Division Word Problems → Multi-Step Word Problems → Solving Multi-Step Word Problems → Multiplication Word Problems → Division Word Problems → Introduction to Long Division → Factors and Multiples → Prime and Composite Numbers → Equivalent Fractions → Relating Fractions and Decimals → Decimal Place Value → Integers and the Number Line → Comparing and Ordering Integers → Absolute Value → Adding Integers → Subtracting Integers → Multiplying Integers → Introduction to Exponents → Order of Operations → Integer Order of Operations → Variable Expressions → The Distributive Property → Variables and Expressions Review → Introduction to Polynomials → Adding and Subtracting Polynomials → Multiplying Polynomials → Factorial → Permutations → Combinations → Counting Principles: Addition and Multiplication Rules → Introduction to Graph Theory → Propositional Logic Foundations → Logical Equivalences → Boolean Algebra → Boolean Type and Truth Values → Comparison Operators and Boolean Tests → Logical Operators and Boolean Algebra → Conditional Statements → Defining and Calling Functions → Functions: Decomposing Problems → Function Parameters and Argument Passing → Return Values → Variable Scope → Introduction to Classes → Objects and Instances → Methods and Attributes → Algorithm Design Basics → Asymptotic Notation: Big-O, Big-Omega, Big-Theta → Big-O Notation and Complexity Analysis → Time and Space Complexity → Heaps and Priority Queues

Longest path: 86 steps · 458 total prerequisite topics

Prerequisites (3)

Leads To (5)