layers

Heaps & Priority Queues
Curriculum

Master heap data structures and priority queues through structural invariants, efficient operations, and optimal element access.

What This Category Is Really About

layersHeap Property

Complete binary tree with ordering constraint. Parent ≥ children (max-heap) or parent ≤ children (min-heap). Enables O(1) min/max access.

priority_highPriority Queue

Abstract data type: insert elements with priority, extract highest priority. Heaps provide efficient implementation: O(log n) operations.

swap_vertHeapify Operations

Bubble up (insert) and bubble down (extract). Restore heap property after modifications. O(log n) time for both operations.

filter_listTop-K Problems

Find K largest/smallest elements efficiently. Maintain heap of size K. Process stream of elements without storing all.

Mental Model & Invariants

Heaps are partially ordered trees optimized for priority access.

"The heap property holds at every node: parent dominates children. This partial ordering enables O(1) peek and O(log n) insert/extract."

The Core Invariant
Every parent node satisfies the heap property relative to its children. Insert and extract operations restore this invariant through bubbling.

Break this, and you lose O(1) access to min/max element.

verified

Heap Property

Max-heap: parent ≥ children. Min-heap: parent ≤ children. Holds at every node in tree.

account_tree

Complete Tree

All levels filled except possibly last. Last level filled left to right. Enables array representation.

speed

Height Guarantee

Complete tree ensures height = O(log n). All operations proportional to height.

swap_vert

Bubble to Restore

Insert: bubble up from bottom. Extract: replace root with last, bubble down. Both restore heap property in O(log n).

When to Think "Heaps"

sensorsStrong Signals

draw

Need repeated access to min/max element

draw

Top-K largest or smallest elements

draw

Merge K sorted lists/arrays

draw

Streaming data with priority

draw

Scheduling problems

draw

Median maintenance

ruleProblem Signals

layers

Don't need full sort, just extremes

layers

Process elements by priority

layers

Maintain partial ordering efficiently

layers

Dynamic dataset with priority queries

Core Patterns You Must Master

filter_list

Top-K Elements

Maintain heap of size K. For K largest, use min-heap. For K smallest, use max-heap.

// Invariant
Heap size never exceeds K. Root is Kth element.
Min-heapMax-heapStreaming
merge

Merge K Sorted Lists

Use min-heap with one element from each list. Extract min, add next from same list.

// Invariant
Heap contains at most K elements. Always extract global minimum.
Priority queuePointersK-way
show_chart

Running Median

Two heaps: max-heap for lower half, min-heap for upper half. Balance sizes.

// Invariant
Max-heap size ≈ min-heap size. Max-heap root ≤ min-heap root.
Two heapsBalanceMedian
schedule

Task Scheduling

Priority queue ordered by deadline or priority. Process tasks in optimal order.

// Invariant
Next task to process is always at heap root.
GreedyPriorityScheduling
build

Heap Construction

Build heap from array in O(n) using bottom-up heapify. More efficient than n insertions.

// Invariant
Process from last non-leaf upward. Each subtree heapified.
HeapifyBottom-upO(n)
sort

Heap Sort

Build max-heap, repeatedly extract max. In-place sorting algorithm.

// Invariant
Heap shrinks from end. Sorted portion grows from end.
In-placeO(n log n)Unstable

How to Learn This Category

1

Understand Heap Property

Draw heap as tree and array. Understand parent-child relationships. Practice converting between representations.

2

Implement Basic Operations

Code insert (bubble up) and extract (bubble down) from scratch. Trace execution step by step.

3

Master Array Indexing

Parent at i, children at 2i+1 and 2i+2. Practice navigating heap using array indices.

4

Learn Top-K Pattern

Use min-heap for K largest, max-heap for K smallest. Understand why heap size is K, not n.

5

Practice Two-Heap Technique

Running median problem. Balance two heaps. Understand when to rebalance.

6

Study Heap Construction

Build heap in O(n) using bottom-up heapify. Understand why it's faster than n insertions.

Canonical Problem List

Common Mistakes

error_outline

Wrong Heap Type for Top-K

Failure Mode

Using max-heap for K largest or min-heap for K smallest. Heap fills with wrong elements.

Mastery Fix

K largest → min-heap (evict smallest). K smallest → max-heap (evict largest).

error_outline

Not Maintaining Heap Size

Failure Mode

Letting heap grow unbounded. Defeats purpose of top-K pattern.

Mastery Fix

After inserting, if size > K, extract root. Maintain exactly K elements.

error_outline

Incorrect Array Indexing

Failure Mode

Off-by-one errors in parent/child calculations. Heap property violated.

Mastery Fix

Parent: (i-1)/2. Left child: 2i+1. Right child: 2i+2. Verify with small examples.

error_outline

Forgetting to Heapify After Extract

Failure Mode

Replacing root but not bubbling down. Heap property broken.

Mastery Fix

After replacing root with last element, bubble down to restore heap property.

error_outline

Comparing Wrong Elements in Two-Heap

Failure Mode

Not maintaining max-heap root ≤ min-heap root. Median calculation incorrect.

Mastery Fix

After insertion, check if max-heap root > min-heap root. Swap if needed.

Interview Guidance

Interview Protocol

What they test

  • Heap type selection (min vs max)
  • Top-K pattern recognition
  • Time complexity analysis
  • Heap property maintenance

Strategy

Identify if problem needs min/max access. For top-K, use opposite heap type. Explain heap property and why operations are O(log n). Mention space complexity.

The Verbal Template

Problem Type

"This is a [top-K / merge / median / scheduling] problem. I need [min/max] access."

Heap Choice

"I'll use [min-heap / max-heap] because [reason: maintain K largest / extract minimum / etc]."

Operations

"Insert is O(log n) bubble up. Extract is O(log n) bubble down. Peek is O(1)."

Complexity

"Time: O(n log k) for n elements with heap size k. Space: O(k) for the heap."

When You've Mastered It

done_all

Choose min vs max heap instantly

done_all

Implement insert and extract correctly

done_all

Recognize top-K pattern immediately

done_all

Navigate heap using array indices

done_all

Maintain heap property after operations

done_all

Analyze time complexity accurately

What This Unlocks Next

route

Advanced Graph Algorithms

Dijkstra's shortest path uses min-heap. Prim's MST uses priority queue. A* search with heuristic priority.

sort

Advanced Sorting

Heap sort, external sorting with K-way merge. Partial sorting for top-K without full sort.

show_chart

Streaming Algorithms

Maintain statistics on unbounded streams. Running median, top-K frequent, approximate quantiles.

schedule

Scheduling & Optimization

Task scheduling, resource allocation, event simulation. Greedy algorithms with priority queues.