The notes

Definition

A complete binary tree that satisfies the heap property.

Complete tree

  • Filled level by level, left to right (no gaps except on the last level)
  • A tree with a gap before the last node is NOT a complete tree

Two types

Max heap

  • Root is the largest element
  • Parent is always >= its children
  • Value decreases down

Min heap

  • Root is the smallest element
  • Parent is always <= its children
  • Value increases down

How a heap is stored (array representation)

Index formulas

  • Left child(i) = 2i + 1
  • Right child(i) = 2i + 2
  • Parent(i) = (i - 1) / 2

Key operations

Insertion (push)

  • 1. Add the new element to the next available spot
  • 2. "Bubble up" (percolate up) to fix the property (swap with parent if needed)

Extraction (pop)

  • 1. Remove the root (max/min)
  • 2. Replace the root with the last element
  • 3. "Sink down" (percolate down) to fix the property (swap with child if needed)

Why heaps are useful

  • Priority queues: a line of tasks with priorities
  • Heapsort: efficient sorting
  • Top K elements: finding the largest or smallest numbers

Time complexity

  • O(log N) for insert/delete
  • O(1) for peek

Data structures deck

  1. 1. Linear vs non-linear
  2. 2. Arrays
  3. 3. Hashmaps
  4. 4. Stacks
  5. 5. Queue
  6. 6. Linked list
  7. 7. Binary tree
  8. 8. BST
  9. 9. Graphs
  10. 10. Heaps

Watch the lesson