Workspace Heaps
0d
DSA topics

Heaps and Priority Queues

A heap guarantees that the root outranks every descendant. Siblings can appear in either order.

Picture the idea

The next job at a priority desk must be the most urgent, even when the people further back are only partly ordered.

When to use it

Choose a heap for repeated best-item extraction, streaming top-k results or scheduling by priority.

How it works

Insert at the next available leaf and exchange with the parent while heap order is broken. Removal replaces the root with the last item, then sifts it down.

  • Peek at the root.
  • Sift up after insertion.
  • Sift down after root removal.
  • Build bottom-up from the last internal node.

Peek is O(1). Push and pop are O(log n). Bottom-up heap construction is O(n). Retaining k candidates for a stream costs O(k) space.

Watch for this mistake

Iterating over the heap backing array does not yield all items in sorted order.

For k largest values, explain why the smallest retained candidate belongs at the root.

Practice in the lab

Related learning