A Binary Heap is a specialized complete binary tree that satisfies the Heap Property. In a Min-Heap, the key at the root is the absolute minimum among all keys in the tree; in a Max-Heap, the root is the absolute maximum. Heaps power Priority Queues, Heap Sort ($O(n \log n)$), and Dijkstra’s Shortest Path Algorithm.
Imagine an Emergency Room triage system:
Because a binary heap is a Complete Binary Tree (every level is completely filled except possibly the last, which is filled from left to right), it can be stored directly inside a contiguous flat array with ZERO pointer overhead:
| Operation | Action | Time Complexity |
|---|---|---|
peek() | Inspects the min/max element at the root (arr[0]) | $O(1)$ |
insert(val) | Adds to the end of array and bubbles up (Sift-Up) | $O(\log n)$ |
extractMin() / pop() | Swaps root with last item, pops end, and sinks down (Sift-Down) | $O(\log n)$ |
heapify(arr) | Converts an unordered array into a valid heap in-place | $O(n)$ Linear Time! |
Find the $K$ most frequent elements in an array using a Min-Heap of size $K$ in $O(n \log k)$ time:
[10, 20, 15, 30] after inserting 5[10, 20, 15, 30][10, 20, 15, 30, 5]| Step | Index i | Value | Parent Index p = (i-1)//2 | Parent Value | Comparison | Action |
|---|---|---|---|---|---|---|
| 1 | 4 | 5 | 1 | 20 | $5 < 20$ | Swap 5 and 20 → [10, 5, 15, 30, 20] |
| 2 | 1 | 5 | 0 | 10 | $5 < 10$ | Swap 5 and 10 → [5, 10, 15, 30, 20] |
| 3 | 0 (Root) | 5 | - | - | At Root | Done! |
Result: 5 bubbled up to root in $\log_2 n$ steps!
peek())?heapify operation that transforms an arbitrary array of $n$ elements into a valid heap?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.