Heap
A heap gives you the smallest (or largest) item in O(1) and lets you add or remove one in O(log n). Use it whenever you keep asking “what is the best item right now?” while the set of candidates keeps changing.
When to reach for it
Section titled “When to reach for it”- The problem says “k largest”, “k smallest”, “kth” or “top k”.
- You are merging several sorted lists, arrays or streams.
- You need the median of data that keeps arriving.
- Sorting is O(n log n) but you only need a few items: O(n log k) is enough.
Template
Section titled “Template”import heapq
# 1. Top k: a min-heap of size k. The root is the kth largest.heap = []for x in nums: heapq.heappush(heap, x) if len(heap) > k: heapq.heappop(heap) # evict the smallest
# 2. k-way merge: heap holds one candidate per sorted source.heap = [(src[0], i, 0) for i, src in enumerate(sources) if src]heapq.heapify(heap)while heap: val, i, j = heapq.heappop(heap) # smallest overall if j + 1 < len(sources[i]): heapq.heappush(heap, (sources[i][j + 1], i, j + 1))
# 3. Two heaps: max-heap (negated) low half, min-heap high half; sizes within 1.For “k largest” use a min-heap of size k. For “k smallest” use a max-heap.
Per-language note
Section titled “Per-language note”- Python:
heapqis min-only, on a plain list. For a max-heap push negated values. Add an index tie-breaker in tuples holding objects that can’t be compared. - Java:
PriorityQueueis a min-heap. For a max-heap usenew PriorityQueue<>(Collections.reverseOrder())or pass a comparator. - JavaScript / TypeScript: there is no built-in heap. LeetCode provides
MinPriorityQueueandMaxPriorityQueue, but they are not standard. The solutions here import a smallHeaphelper. In an interview, say you will assume a heap helper exists and offer to write one.
Problems in this guide
Section titled “Problems in this guide”- Kth Largest Element in an Array — a size-k min-heap keeps the top k
- Merge k Sorted Lists — a min-heap of list heads picks the next node
- Find Median from Data Stream — a max-heap and a min-heap split the data in half