Skip to contentKEEP THE CRAFTTHE SANCTUARY

Heap

A min-heap exposes the smallest retained value while leaving other entries only partially ordered. For largest-k selection, that root is the weakest answer candidate, so compare before replacing and sort only when the output needs full order.

10 practice exercises16 interview problems

Recognize it when A changing collection repeatedly needs its smallest member.

Checking your account…

Heap Code Labs

Mental Model

A heap is a partially ordered binary tree stored in an array. In Python’s min-heap, every parent is no greater than its children, so the root at index zero is globally minimal. The rest of the array is not sorted; only the parent-child relation is guaranteed.

The Heap Order Invariant

For index i, children are 2*i + 1 and 2*i + 2. A push repairs one root-to-leaf path, and a pop moves the last item to the root before repairing one path downward. That gives O(log n) update and O(1) minimum lookup.

Build and Update a Min-Heap

heapq.heapify(values) transforms a list in O(n) time and mutates it. heappush and heappop are O(log n). heappushpop performs the combined operation efficiently and may immediately return a new item smaller than the existing root; heapreplace always removes the current root first and requires a nonempty heap.

Build and Consume a Min-Heap

Reference
import heapq

def consume_smallest(values, additions):
    heap = values.copy()
    heapq.heapify(heap)
    popped = []
    for value in additions:
        heapq.heappush(heap, value)
        popped.append(heapq.heappop(heap))
    return popped, sorted(heap)
Practice

Implement consume_smallest(values, additions). Heapify a copy, then push each addition and pop the current minimum; return popped values and sorted remaining values.

Public tests

  • Verify minimum extraction after pushes

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Build and Consume a Min-Heap

import heapq

def consume_smallest(values, additions):
    heap = values.copy()
    heapq.heapify(heap)
    popped = []
    for value in additions:
        heapq.heappush(heap, value)
        popped.append(heapq.heappop(heap))
    return popped, sorted(heap)

The heapq documentation(opens in a new tab) is explicit that the API is a min-heap. Max-priority code traditionally negates numeric priorities; state that representation instead of mentally reversing comparisons in scattered places.

Keep a Bounded Top K

To retain the k largest values, use a min-heap of at most k candidates. Its root is the weakest retained candidate. Once full, replace the root only when the new value is larger. The invariant is that the heap contains the largest min(k, processed) values from the processed prefix.

Keep a Bounded Largest-K Heap

Reference
import heapq

def largest_k_sorted(values, k):
    heap = []
    for value in values:
        if len(heap) < k:
            heapq.heappush(heap, value)
        elif k and value > heap[0]:
            heapq.heapreplace(heap, value)
    return sorted(heap)
Practice

Implement largest_k_sorted(values, k). Keep at most k candidates in a min-heap and return retained values in ascending order. k is a nonnegative integer; zero retains no values, and k larger than the input retains every available value.

Public tests

  • Verify bounded largest candidates

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Keep a Bounded Largest-K Heap

import heapq

def largest_k_sorted(values, k):
    heap = []
    for value in values:
        if len(heap) < k:
            heapq.heappush(heap, value)
        elif k and value > heap[0]:
            heapq.heapreplace(heap, value)
    return sorted(heap)

Trace a Root that Represents the Candidate Cutoff

Use the existing largest-k Lab with two candidate slots. Once filled, the root is the cutoff: 8 and 7 improve it, while 1 cannot belong to the best two processed values.

print(largest_k_sorted([6, 2, 8, 1, 7], 2)) followed by print(largest_k_sorted([6, 2], 0))

Step Executed statement State Why
1 heapq.heappush(heap, value) value = 6; heap = [6] An unfilled candidate set accepts the first value.
2 heapq.heappush(heap, value) value = 2; heap = [2, 6] The root is now the weakest of two retained candidates.
3 heapq.heapreplace(heap, value) value = 8; heap = [6, 8] Eight improves the root cutoff and displaces two.
4 elif k and value > heap[0]: value = 1; heap stays [6, 8] A weaker new value cannot improve the retained answer.
5 heapq.heapreplace(heap, value); return sorted(heap) value = 7; heap = [7, 8]; result = [7, 8] Seven displaces six; sorting supplies the requested ascending output.
Print Output
1 [7, 8]
2 []

The final sorted list is an output choice; the heap needs only expose its weakest retained candidate during scanning. Duplicates remain separate occurrences, and k zero retains nothing.

Choose a Heap or Sort

Use a heap for repeated best-item extraction, streaming top k, or a changing frontier. Sort when all items are known and the complete order is required; sorting is often simpler and costs O(n log n). For one kth selection, quickselect may offer better average time but has a more delicate invariant.

Heap Ordering and Candidate Mistakes

  • Reading the heap array as sorted gives wrong second/third-order results.
  • Pushing every item for top k wastes O(n) space instead of O(k).
  • Negated max-heap tuples need consistent signs in every comparison and returned value.
  • Equal tuple priorities compare later fields, which may be non-comparable objects.
  • Calling heapreplace on an empty heap raises an error.

Explain It in an Interview

Name the root meaning and the candidate invariant. Explain which single path an update repairs. Distinguish O(n) heapify from n separate O(log n) pushes, and state whether final sorting adds O(k log k). Avoid claiming the internal array is ordered beyond the heap property.

Update a Bounded Heap(opens in a new tab) practices candidate replacement. Kth Largest Element in an Array(opens in a new tab) tests whether heap size and root meaning are chosen for the requested rank.

Template To Memorize

Learn this shape by heart; most problems in this family change only one or two lines of it.

Two heaps for the median

Push through small to large, then rebalance.

Numbers arrive one at a time and you need the median at any moment.

Trigger words

  • running median
  • median of a stream
  • median at any time
  • sliding window median
import heapq

class RunningMedian:
    def __init__(self):
        self.small = []   # max-heap of the lower half (stored as negatives)
        self.large = []   # min-heap of the upper half

    def add(self, num):
        heapq.heappush(self.small, -num)
        heapq.heappush(self.large, -heapq.heappop(self.small))  # move the biggest small up
        if len(self.large) > len(self.small):
            heapq.heappush(self.small, -heapq.heappop(self.large))

    def median(self):
        if len(self.small) > len(self.large):
            return -self.small[0]
        return (-self.small[0] + self.large[0]) / 2

Spot it when

  • 'Find median from data stream'.
  • Sliding median.

Remember

  • small may hold one extra item; then its top is the median.
  • Every add is O(log n); median is O(1).

How problems bend it

  • Odd total only: Return -self.small[0] directly.

Python Version Note

Python 3.11+

These Labs use the min-heap heapq API available in the browser runtime. Negated numeric priorities provide a max-priority representation without requiring newer max-heap helpers.

Verify in Python docs(opens in a new tab)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Heapify n valuesO(n)O(n)Stored heap uses linear space; heapify mutates it, so the ownership copy in the Lab also costs O(n).
Retain and sort largest kO(n * log(k + 2) + k * log(k + 2))O(n * log(k + 2) + k * log(k + 2))Nonnegative k, constant-cost comparable values; includes final sorting. Zero k still scans n input values in O(n).

Space

O(n) for heapify n values; O(k) for retain and sort largest k.

Assumptions

  • Stored heap uses linear space; heapify mutates it, so the ownership copy in the Lab also costs O(n).
  • Nonnegative k, constant-cost comparable values; includes final sorting. Zero k still scans n input values in O(n).

Invariants Worth Saying Aloud

  1. Each parent is no greater than its children; only index zero is globally minimal.
  2. A bounded largest-k heap holds the largest min(k, processed) values.
  3. A full heap replaces its weakest candidate only with a strictly larger value.

When To Use Or Avoid Heap

Use It When

  • Use heapq for repeated minimum extraction or a bounded top-k frontier.
  • Retain only candidates that can still belong to the requested answer.

Choose Another Tool When

  • Sort once when a complete static order is the answer.
  • Do not read arbitrary heap positions as ranks.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Treating the heap array as sorted ranks

A valid heap can store 4 before 2 even though its root is 1. Index one is not the second smallest member.

Prevent it: Pop the minimum from a copy when observing the next rank, or sort for full ordering.

Avoid

second = heap[1]

Use instead

remaining = heap.copy()
heapq.heappop(remaining)
second = remaining[0]

Evicting as soon as size equals the limit

A heap of exactly k candidates is valid. Removing at equality leaves only k minus one.

Prevent it: Evict only after exceeding the allowed candidate count.

Avoid

heapq.heappush(heap, value)
if len(heap) >= k:
    heapq.heappop(heap)

Use instead

heapq.heappush(heap, value)
if len(heap) > k:
    heapq.heappop(heap)

Replacing the cutoff with a worse candidate

heapreplace always removes the existing root. An unconditional replacement can discard a better retained answer.

Prevent it: For largest-k selection, replace only when the new value exceeds the non-empty heap root.

Avoid

heapq.heapreplace(heap, value)

Use instead

if value > heap[0]:
    heapq.heapreplace(heap, value)

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.