Command Palette

Search for a command to run...

Module 18

Heaps and Priority Queues

Always know the smallest or largest: how a heap works inside an array, Java's PriorityQueue, top-K, two heaps and K-way merge.

Intermediate 5 lessons 9 problems ~60 min of lessons

A heap answers one question fast: what is the smallest (or largest) item right now? Adding an item and removing the top both cost O(log n), and peeking at the top is O(1). It does this with a complete binary tree stored inside a plain array.

This module opens the heap up (sift-up and sift-down drawn step by step), then teaches the three heap patterns that cover most interview problems: keep a heap of size K for top-K questions, balance two heaps for running medians, and merge K sorted sources by always taking the smallest head.

Best after: Binary Trees

Part 1

Learn the ideas

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. A max-heap as a simulation tool: repeatedly take the two largest.

  2. K smallest by a computed key: a max-heap of size K keyed on squared distance.

  3. Top-K as a long-lived data structure: the min-heap's top is always the k-th largest.

  4. Greedy with a heap: always run the task with the most copies left; then see the counting formula behind it.

  5. The two-heaps pattern as a class.

  6. 18.6IPOHardTwo Heaps

    Unlock options over time: sorted by requirement, and a max-heap of the options you can currently afford.

  7. Rows as sorted lists: K-way merge, or binary search on the value with a staircase count.

  8. K-way merge with a window: the heap holds one element per list; the range is heap minimum to the running maximum.

  9. Deciding in hindsight: give ladders to the largest climbs so far by keeping them in a min-heap, and pay bricks for the smallest.