Min Heap
min-heap
Data Structures
Heaps & Priority Queue
Pull the next task in priority order from a stream of millions, and a sorted array gives you `O(1)` extract but `O(n)` insert; a sorted linked list flips the costs but stays linear; a balanced BST hits `O(log n)` for both but with substantial pointer overhead. A **Heap** quietly outperforms all three for this exact workload by storing a complete binary tree in a flat array and keeping just the min (or max) at the root. This lesson covers the heap property, the parent-and-child index formulas (`parent = (i-1)/2`, `left = 2i+1`, `right = 2i+2`) that let array indices encode tree structure with no pointers, sift-up and sift-down for `O(log n)` insert and extract, and the linear-time `heapify` build. You will see how this maps onto the priority queue abstraction and onto interview staples such as top-K elements, K-th largest, merge K sorted lists, and the streaming median with two heaps; on the systems side, the same structure powers Dijkstra and Prim. In **Trees: Binary Tree Fundamentals**, you saw what a complete binary tree is and how to traverse one; the heap reuses that exact shape but stores it implicitly. **Arrays & Strings** is what makes the implicit storage cheap: a flat array gives `O(1)` parent and child access through arithmetic, with no allocations per node. Next, **Binary Search Tree (BST)** trades the heap's partial ordering for a full ordering invariant, unlocking sorted iteration and key-based search at the cost of needing actual pointers.
Not Started
0%
Practice Problems
Kth Largest Element in a Stream
Design a class that finds the kth largest element in a stream of numbers using a min-heap.
Find Median from Data Stream
Design a data structure that efficiently finds the median from a stream of integers using two heaps.
Design Twitter
Design a simplified Twitter with post, follow/unfollow, and a news feed that merges recent tweets from followed users using a heap.
Find K Pairs with Smallest Sums
Given two sorted arrays, find the k pairs with the smallest sums using a min-heap to efficiently explore candidates.
Kth Largest Element in an Array
Find the kth largest element in an unsorted array using a min-heap or quickselect algorithm.
Code Snippets
Dijkstra in Python with heapq
Dijkstra finds the shortest path in a weighted graph with non-negative edge weights. The Python idiom is `heapq` (a binary min-heap) plus a distance dict, which gives O((V + E) log V) without external libraries. This entry covers the standard single-source template, path reconstruction, and the early-exit shortest-path-to-one-target variant.
Min-Heap via std::priority_queue
`std::priority_queue` is a max-heap by default. To get a min-heap you flip the comparator. This snippet shows the three common forms: a min-heap of ints with `std::greater`, a min-heap of pairs sorting by first element, and a custom comparator over a struct for things like Dijkstra. All run in O(log n) per push/pop.
