Heaps & Priority Queues
Master complete binary tree properties, min-heap/max-heap heapify operations, and priority queue applications like Kth largest elements and merging sorted lists.
1. Complete Binary Tree Properties & Heap Invariants
A heap is a specialized tree-based data structure that satisfies the heap property: in a min-heap, for any given node $i$, the key is less than or equal to its children, meaning the smallest element is always at the root. Conversely, a max-heap maintains keys greater than or equal to its children, keeping the largest element at the root.
Array Storage: Heaps are almost exclusively implemented using contiguous arrays without pointer overhead. For any element at index $i$:
- Left child index: $2i + 1$
- Right child index: $2i + 2$
- Parent index: $\lfloor (i - 1) / 2 \rfloor$
2. Heapify Operations & Priority Queues
Dynamic modifications rely on two core maintenance routines:
Sift-Up (Bubble-Up): When a new element is inserted at the end of the array, it bubbles up by comparing against its parent and swapping if the heap property is violated, taking $O(\log n)$ time.
Sift-Down (Bubble-Down): When the root element is popped and replaced by the last element, it sinks down by swapping with its smaller (min-heap) or larger (max-heap) child, running in $O(\log n)$ time. Building a heap from an arbitrary array via bottom-up heapify runs in linear $O(n)$ time.
3. Homework & Quiz Overview
To lock in your mastery, complete the implementation exercises for finding the Kth largest element in an array and Merging $k$ sorted lists.
Quick Check: Test Your Intuition
What is the time complexity of building a heap from an unsorted array of size $n$ using the bottom-up `heapify` algorithm?