💡 Summary: Always Knowing the Biggest or Smallest Item Fast
Suppose you have a list of exam scores, tasks, or prices and keep asking, "What is the highest (or lowest) value right now?" A Binary Heap is a special tree (shaped like a filled-in pyramid from top to bottom, left to right) that keeps the biggest item at the top in a Max-Heap, or the smallest item at the top in a Min-Heap.
Even better, a heap fits neatly inside a regular array without needing extra node pointers. Using that structure, Heap Sort pulls out the top item again and again to sort an array right inside its own memory space—without needing an extra copy of the array.
n, you can jump between family members using simple index math—no pointers needed:
- Parent & Child Formulas: For any item at index
i, its parent is at(i - 1) // 2, its left child is at2 * i + 1, and its right child is at2 * i + 2. - Turning an Array into a Max-Heap (
heapify): Leaf items at the bottom have no children, so we start from the last non-leaf node (n // 2 - 1) and move up to index0, pushing any smaller parent down below larger children. - How Heap Sort Works: Once a Max-Heap is built, the largest number is at index
0. Swap it with the last item in the unsorted part, shrink the active heap by one, and push the new root down into its right spot—repeating until the whole array is sorted.
| Operation | Time Complexity | Extra Space | What to Remember for Exams |
|---|---|---|---|
| Build Heap (Bottom-Up) | O(n) | O(1) | Faster than inserting n items one by one (O(n log n)) |
| Insert or Remove Top | O(log n) | O(1) | At most one swap per tree level as an item bubbles up/down |
| Heap Sort | O(n log n) | O(1) | Predictable speed in all cases, though it is not a stable sort |
def sift_down_max(arr, n, i):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[left] > arr[largest]:
largest = left
if right < n and arr[right] > arr[largest]:
largest = right
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
sift_down_max(arr, n, largest)
def build_max_heap(arr):
n = len(arr)
for idx in range(n // 2 - 1, -1, -1):
sift_down_max(arr, n, idx)
return arr
def heap_sort(arr):
n = len(arr)
build_max_heap(arr)
for end in range(n - 1, 0, -1):
arr[0], arr[end] = arr[end], arr[0] # Put largest at the back
sift_down_max(arr, end, 0) # Fix the remaining heap front
return arr
sample = [12, 11, 13, 5, 6, 7]
heap_copy = build_max_heap(sample.copy())
sorted_copy = heap_sort(sample.copy())
print("Original Array :", sample)
print("Max-Heap Array :", heap_copy)
print("Heap Sorted :", sorted_copy)
- Keep the Two Halves Balanced: Make sure the two heaps differ in size by at most
1item, and every number in the Max-Heap is smaller than or equal to every number in the Min-Heap. - Read the Middle Quickly: If both heaps have the same count, the median is the average of their two top numbers; if one has one extra item, its top number is the median.
#include
#include
#include
using namespace std;
class MedianFinder {
private:
priority_queue lowerMax; // Max-heap for smaller half
priority_queue, greater> upperMin; // Min-heap for larger half
public:
void addNum(int num) {
if (lowerMax.empty() || num <= lowerMax.top()) {
lowerMax.push(num);
} else {
upperMin.push(num);
}
// Balance sizes so lowerMax has at most 1 extra item
if (lowerMax.size() > upperMin.size() + 1) {
upperMin.push(lowerMax.top());
lowerMax.pop();
} else if (upperMin.size() > lowerMax.size()) {
lowerMax.push(upperMin.top());
upperMin.pop();
}
}
double findMedian() const {
if (lowerMax.size() > upperMin.size()) {
return static_cast(lowerMax.top());
}
return (lowerMax.top() + upperMin.top()) / 2.0;
}
};
int main() {
MedianFinder mf;
vector stream = {5, 15, 1, 3, 2, 8};
cout << "Running medians: ";
for (int x : stream) {
mf.addNum(x);
cout << mf.findMedian() << " ";
}
cout << "\n";
return 0;
}
- 1. Sorting When Memory Is Tight (Heap Sort): Sorts data right inside the existing array without needing extra memory for a full temporary copy.
- 2. Live Middle Value (Running Median): Useful when tracking typical response times or scores as new numbers arrive one by one.
- 3. Finding the Top-K Items in a Stream: Keeps track of the top 3 or top 10 highest scores or most common errors without storing everything in sorted order.
- 4. Picking the Most Urgent or Earliest Task: A Min-Heap lets a scheduler grab whichever task has the earliest deadline or highest urgency next.
- 5. Combining Multiple Sorted Lists: A small Min-Heap helps pick the next smallest item across several sorted lists smoothly.
import heapq
# 3. Finding the Top-3 Most Frequent Error Codes Using a Min-Heap
class TopKTracker:
def __init__(self, k):
self.k = k
self.min_heap = [] # Stores (count, code)
def update_counts(self, counts_dict):
self.min_heap = []
for code, cnt in counts_dict.items():
if len(self.min_heap) < self.k:
heapq.heappush(self.min_heap, (cnt, code))
elif cnt > self.min_heap[0][0]:
heapq.heapreplace(self.min_heap, (cnt, code))
return sorted(self.min_heap, reverse=True)
error_counts = {"E404": 18, "E500": 94, "E401": 42, "E503": 67, "E429": 12}
tracker = TopKTracker(k=3)
print("3. Top-3 Error Codes:", tracker.update_counts(error_counts))
- 6. Shortest Route Finder (Dijkstra's Algorithm): Helps pick the closest unvisited stop next when finding shortest paths on a map or network.
- 7. Connecting Networks at Minimum Cost (Prim's Algorithm): Chooses the cheapest next connection to link nodes together.
- 8. Matching Highest Bids or Closest Drivers: Quickly surfaces the top bid or nearest option from a pool of candidates.
- 9. Predictable Sorting Without Worst-Case Slowdowns: Unlike basic Quick Sort (which can slow down to O(n²) on tricky inputs), Heap Sort stays at O(n log n).
- 10. Firing Scheduled Timers in Order: A Min-Heap keyed by time lets an app wake up whichever timer is due soonest.
import heapq
# 10. Running Scheduled Timers from Soonest to Latest
timers = []
heapq.heappush(timers, (250, "SessionCleanup"))
heapq.heappush(timers, (120, "CacheRefresh"))
heapq.heappush(timers, (180, "MetricsFlush"))
fired = []
while timers:
due_ms, job = heapq.heappop(timers)
fired.append(f"{job}@{due_ms}ms")
print("10. Timer Execution Order:", " -> ".join(fired))
- A heap is NOT a sorted array—and NOT a Binary Search Tree: In a Max-Heap, index
0is the biggest number, but the rest of the array is only partially ordered for heap rules—not sorted from left to right. - Heap Sort is not stable: If two items have the same value, their original relative order might change during swaps.
- Python's
heapqis a Min-Heap by default: To make it act like a Max-Heap for numbers, store-valueand flip the sign back when you pop it.
checkpoints = [
"Heap Shape & Order: Complete binary tree where parent beats (or is beaten by) children.",
"Build Heap in O(n): Bottom-up heapify builds a heap in linear time.",
"Heap Sort: O(n log n) time and O(1) extra space, but not stable."
]
for item in checkpoints:
print("*", item)