Skip to content

Heap

Heap in under a minute

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.

  • 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.
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.

  • Python: heapq is 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: PriorityQueue is a min-heap. For a max-heap use new PriorityQueue<>(Collections.reverseOrder()) or pass a comparator.
  • JavaScript / TypeScript: there is no built-in heap. LeetCode provides MinPriorityQueue and MaxPriorityQueue, but they are not standard. The solutions here import a small Heap helper. In an interview, say you will assume a heap helper exists and offer to write one.