Data Structures & Algorithms · Revision notes

Heaps & Priority Queues

A binary heap is a complete binary tree stored in an array that keeps the min (or max) at the root; insert and extract are O(log n), peek is O(1), and building is O(n). It implements priority queues, heap sort and Top-K selection.

Quick revision

  • Min-heap: parent <= children; parent (i-1)//2, children 2i+1, 2i+2
  • insert/extract O(log n), peek O(1), build O(n)
  • Heap sort: max-heap, swap root to end, sift-down; O(n log n), in place, unstable
  • Top K largest: min-heap size K, O(n log k); merge K lists O(N log K)
  • Median: max-heap (low) + min-heap (high)
Read the full Heaps & Priority Queues notes on Doubtclip →