Zero-Indexed Binary Min-Heap Design
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Build a binary min-heap from first principles backed by a single 0-indexed dynamic list, without importing heapq, queue.PriorityQueue, or any built-in sorting/heap routines. Every node in the tree must obey the min-heap ordering rule: a parent's integer value is never greater than either of its children's values.
Inside the 0-based backing array, a node stored at position i maps to its neighbors as follows:
- Parent slot:
(i - 1) // 2wheneveri > 0 - Left child slot:
2 * i + 1 - Right child slot:
2 * i + 2
Design a MinHeap class supporting five operations:
__init__(): Creates an initially empty heap.insert(val: int) -> None: Pushes integervalinto the heap while preserving the min-heap invariant.extract_min() -> Optional[int]: Deletes and returns the minimum integer currently in the heap, or returnsNonewhen no elements are present.peek() -> Optional[int]: Reads and returns the minimum integer without mutating the heap, or returnsNonewhen empty.size() -> int: Reports how many integers the heap currently holds.
To evaluate your implementation, implement the driver run_min_heap_operations(operations: List[str], arguments: List[List[int]]) -> List[Optional[int]], which instantiates one MinHeap, executes each named method ("insert", "extract_min", "peek", or "size") with its corresponding argument list ([val] for "insert" and [] for all other calls), and returns a list of outputs in call order (None for "insert").
Examples
Example 1
Input:
operations = ["insert", "insert", "insert", "insert", "peek", "extract_min", "insert", "size", "extract_min", "extract_min"]
arguments = [[12], [4], [9], [2], [], [], [-6], [], [], []]
Output:
[None, None, None, None, 2, 2, None, 4, -6, 4]
Walk-through:
- Inserting 12, 4, 9, and 2 builds [2, 4, 9, 12], so peek() sees 2 and the first extract_min() removes 2, leaving [4, 12, 9].
- insert(-6) bubbles -6 all the way to index 0 ([-6, 4, 9, 12]), bringing size() to 4.
- The final two extract_min() calls pop -6 and then 4 in ascending order.
Example 2
Input:
operations = ["peek", "insert", "insert", "extract_min", "size", "extract_min", "extract_min"]
arguments = [[], [7], [7], [], [], [], []]
Output:
[None, None, None, 7, 1, 7, None]
Walk-through:
- Calling peek() on a fresh empty heap safely returns None.
- Two copies of 7 are inserted; the first extract_min() returns one copy and leaves size() == 1.
- The second extract_min() removes the remaining 7 (shrinking the heap from size 1 to 0), and the trailing extract_min() on the now-empty heap returns None.
Constraints
1 <= len(operations) == len(arguments) <= 500,000- Each
operations[k]is"insert","extract_min","peek", or"size". - Every inserted value is an integer in
-10^9 <= val <= 10^9, and duplicate values are allowed. insertandextract_minmust run inO(log n)time (n= current heap size).peekandsizemust run inO(1)time.- Auxiliary space per call (excluding the array storing the
nheap elements) must beO(1).
Step-by-step walkthrough
Understand the goal and judge interface
We need to build a
MinHeapclass from first principles using a single 0-indexed dynamic list (self.data), withoutheapqor built-in sorting helpers:insert(val)— pushesvalin O(log n) time.extract_min()— removes and returns the minimum integer in O(log n) time, orNoneif empty.peek()— returns the minimum integer without removing it in O(1) time, orNoneif empty.size()— returns the current element count in O(1) time.
The automated judge exercises our class via
run_min_heap_operations(operations, arguments), which instantiates oneMinHeap, replays each operation in sequence, and collects each call's return value into a list (insertappendsNone).Why a plain list is too slow
Suppose we tried to store the numbers in a regular Python list without a tree structure:
- Unsorted list:
insertisappendin O(1), butpeekandextract_minmust scan allnitems in O(n) time. - Sorted list: keeping the minimum at the end makes
peekandextract_minO(1), butinsertmust shift up tonitems to keep the list sorted, taking O(n) time.
With up to
500,000calls,ncan reach hundreds of thousands, so O(n) per operation requires tens of billions of steps. A binary min-heap relaxes full sorting into a much cheaper local rule: every parent only needs to be<=its two children. That keeps the global minimum at the root while letting updates touch only one root-to-leaf path of length aboutlog2(n)(at most ~19 steps for500,000elements!).- Unsorted list:
Store a complete binary tree inside a 0-indexed array
A complete binary tree fills every level completely before starting the next level, and fills the bottom level strictly from left to right with no gaps. Because there are no gaps, we never need
leftorrightnode objects — reading the tree level by level packs cleanly into a listself.data:Tree view (values [indices]) Array view 2 [0] / \ idx: 0 1 2 3 4 5 4 [1] 3 [2] data: [2, 4, 3, 10, 6, 9] / \ / 10 [3] 6 [4] 9 [5] For any node at index idx: parent_idx = (idx - 1) // 2 (for idx > 0; e.g. idx 4 -> (4 - 1) // 2 = 1) left_idx = 2 * idx + 1 (e.g. idx 1 -> 3) right_idx = 2 * idx + 2 (e.g. idx 1 -> 4)Because every parent is
<=its children, the smallest element in the entire heap is always at the rootself.data[0], giving O(1)peekandsize:class MinHeap: def __init__(self) -> None: # data: 0-indexed array storing a complete binary tree in level order. # Root (minimum) is at data[0]; node idx has parent (idx - 1) // 2 # and children 2 * idx + 1 (left) and 2 * idx + 2 (right), e.g. [2, 4, 9, 12]. self.data: List[int] = [] def size(self) -> int: return len(self.data) def peek(self) -> Optional[int]: if not self.data: return None # Min-heap invariant guarantees the global minimum sits at index 0. return self.data[0]Insert in O(log n): Append at the end and sift up
Where can a new element go without breaking the complete-tree shape? Only at the very next open leaf slot —
self.data.append(val).That new leaf might be smaller than its parent, violating the min-heap rule at that one edge. We repair it by sifting up: while
idx > 0and the child is strictly smaller than its parent, swap them and step up toparent_idx. Using<=inself.data[parent_idx] <= self.data[idx]stops immediately on ties so duplicate values never do pointless swaps.Insert 2 into [4, 12, 9]: 1) Append 2 at idx 3: 2) 2 < parent 12 (idx 1), swap: 3) 2 < parent 4 (idx 0), swap: 4 [0] 4 [0] 2 [0] / \ / \ / \ 12 [1] 9 [2] 2 [1] 9 [2] 4 [1] 9 [2] / / / 2 [3] 12 [3] 12 [3] [4, 12, 9, 2] [4, 2, 9, 12] [2, 4, 9, 12] (idx == 0, stop!)def insert(self, val: int) -> None: # Append at the next open leaf slot to keep the tree complete, # then bubble the new value up until its parent is <= it. self.data.append(val) last_idx = len(self.data) - 1 self._sift_up(last_idx) def _sift_up(self, idx: int) -> None: # Walk up the single leaf-to-root path (at most floor(log2(n)) swaps). while idx > 0: parent_idx = (idx - 1) // 2 # Use <= so equal values stop immediately without wasted swaps. if self.data[parent_idx] <= self.data[idx]: break self.data[parent_idx], self.data[idx] = self.data[idx], self.data[parent_idx] idx = parent_idxExtract-min in O(log n): Promote the last leaf and sift down
We cannot remove
self.data[0]withpop(0)— that shifts every remaining item left in O(n) time. Instead:- Save
min_val = self.data[0]to return at the end. - Pop
last_val = self.data.pop()from the end in O(1) time, keeping the tree complete. - If
self.datais now empty (the heap had only 1 element), we are already done! Otherwise, placelast_valatself.data[0]and sift it down.
When sifting down, why must we swap with the smaller child rather than just any smaller child? Look at
[10, 6, 3](root10, left child6, right child3): if we swapped10with left child6,6would become the parent of3(6 > 3), breaking the heap! Swapping with3puts3above both6and10, keeping every parent<=its children:Wrong (swap with larger child 6): Right (swap with smaller child 3): 10 6 10 3 / \ ---> / \ / \ ---> / \ 6 3 10 3 (6 > 3 BROKEN!) 6 3 6 10 (3 <= 6, 3 <= 10 OK!)Tracking
smallest_idxacrossidx,left_idx(if< n), andright_idx(if< n) handles zero, one, or two children cleanly in one loop, using O(1) extra variables instead of recursion:def extract_min(self) -> Optional[int]: if not self.data: return None min_val = self.data[0] last_val = self.data.pop() # Guard against size 1 -> 0: if popping emptied self.data, nothing remains to sift. if self.data: self.data[0] = last_val self._sift_down(0) return min_val def _sift_down(self, idx: int) -> None: # Repeatedly swap node idx with the SMALLER of its existing children # so the promoted child remains <= its sibling. n = len(self.data) while True: left_idx = 2 * idx + 1 right_idx = 2 * idx + 2 smallest_idx = idx if left_idx < n and self.data[left_idx] < self.data[smallest_idx]: smallest_idx = left_idx # Comparing against smallest_idx picks right_idx only if it beats BOTH parent and left child. if right_idx < n and self.data[right_idx] < self.data[smallest_idx]: smallest_idx = right_idx if smallest_idx == idx: break self.data[idx], self.data[smallest_idx] = self.data[smallest_idx], self.data[idx] idx = smallest_idx- Save
Wire up the operation runner
Now we implement
run_min_heap_operationsto instantiateMinHeap, dispatch each command string to its matching method, and record each output:def run_min_heap_operations(operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]: heap = MinHeap() # results: return value of each operation in order (None for insert), e.g. [None, 2, 2] results: List[Optional[int]] = [] for op, args in zip(operations, arguments): if op == "insert": heap.insert(args[0]) results.append(None) elif op == "extract_min": results.append(heap.extract_min()) elif op == "peek": results.append(heap.peek()) elif op == "size": results.append(heap.size()) else: raise ValueError(f"Unknown operation: {op}") return resultsTrace through Example 1
Let's follow
self.dataand the returned value across all 10 calls in Example 1:Step Call Heap array after call Return What happened ---- -------------- --------------------- ------ --------------------------------------------- 1 insert(12) [12] None Appended at root 2 insert(4) [4, 12] None 4 < 12 -> sifted up to root 3 insert(9) [4, 12, 9] None 9 >= parent 4 -> stayed at idx 2 4 insert(2) [2, 4, 9, 12] None 2 swapped past 12 (idx 1), then past 4 (idx 0) 5 peek() [2, 4, 9, 12] 2 Read data[0] without modifying heap 6 extract_min() [4, 12, 9] 2 Popped 12 to root; swapped with smaller child 4 7 insert(-6) [-6, 4, 9, 12] None -6 swapped past 12 (idx 1), then past 4 (idx 0) 8 size() [-6, 4, 9, 12] 4 len(self.data) 9 extract_min() [4, 12, 9] -6 Popped 12 to root; swapped with smaller child 4 10 extract_min() [9, 12] 4 Popped 9 to root; 9 <= left child 12 -> stayedComplete solution
from typing import Any, Dict, List, Optional, Set, Tuple class MinHeap: def __init__(self) -> None: # data: 0-indexed array storing a complete binary tree in level order. # Root (minimum) is at data[0]; node idx has parent (idx - 1) // 2 # and children 2 * idx + 1 (left) and 2 * idx + 2 (right), e.g. [2, 4, 9, 12]. self.data: List[int] = [] def size(self) -> int: return len(self.data) def peek(self) -> Optional[int]: if not self.data: return None # Min-heap invariant guarantees the global minimum sits at index 0. return self.data[0] def insert(self, val: int) -> None: # Append at the next open leaf slot to keep the tree complete, # then bubble the new value up until its parent is <= it. self.data.append(val) last_idx = len(self.data) - 1 self._sift_up(last_idx) def extract_min(self) -> Optional[int]: if not self.data: return None min_val = self.data[0] last_val = self.data.pop() # Guard against size 1 -> 0: if popping emptied self.data, nothing remains to sift. if self.data: self.data[0] = last_val self._sift_down(0) return min_val def _sift_up(self, idx: int) -> None: # Walk up the single leaf-to-root path (at most floor(log2(n)) swaps). while idx > 0: parent_idx = (idx - 1) // 2 # Use <= so equal values stop immediately without wasted swaps. if self.data[parent_idx] <= self.data[idx]: break self.data[parent_idx], self.data[idx] = self.data[idx], self.data[parent_idx] idx = parent_idx def _sift_down(self, idx: int) -> None: # Repeatedly swap node idx with the SMALLER of its existing children # so the promoted child remains <= its sibling. n = len(self.data) while True: left_idx = 2 * idx + 1 right_idx = 2 * idx + 2 smallest_idx = idx if left_idx < n and self.data[left_idx] < self.data[smallest_idx]: smallest_idx = left_idx # Comparing against smallest_idx picks right_idx only if it beats BOTH parent and left child. if right_idx < n and self.data[right_idx] < self.data[smallest_idx]: smallest_idx = right_idx if smallest_idx == idx: break self.data[idx], self.data[smallest_idx] = self.data[smallest_idx], self.data[idx] idx = smallest_idx def run_min_heap_operations(operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]: heap = MinHeap() # results: return value of each operation in order (None for insert), e.g. [None, 2, 2] results: List[Optional[int]] = [] for op, args in zip(operations, arguments): if op == "insert": heap.insert(args[0]) results.append(None) elif op == "extract_min": results.append(heap.extract_min()) elif op == "peek": results.append(heap.peek()) elif op == "size": results.append(heap.size()) else: raise ValueError(f"Unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Imagine organizing runners into an upside-down tournament bracket where the fastest time (smallest number) always stands at the very top. Instead of wasting effort keeping all n runners lined up in exact sorted order from 1st to 100,000th, we enforce only one local rule — the min-heap invariant (every parent's value is less than or equal to its two children's values). Because "less than or equal" is transitive down the tree, the overall minimum is guaranteed to sit at the root (data[0]).
A naive list fails at scale because an unsorted list requires an O(n) full scan on every extract_min, while a sorted list requires shifting up to n elements in O(n) time on every insert — totaling tens of billions of steps across 500,000 calls. Instead, we pack a complete binary tree (a binary tree where every level is completely full except possibly the bottom level, which fills strictly from left to right with no gaps) into a flat 0-indexed list using arithmetic index formulas (parent = (i - 1) // 2, left = 2 * i + 1, right = 2 * i + 2). Inserting appends at the end and bubbles up one path (_sift_up), while extracting saves data[0], moves the last element into data[0], and pushes it down toward its smaller child (_sift_down) — both touching at most floor(log2(n)) levels.
Trace 4 tiny operations from Example 1's opening values to see both repairs:
insert(12)->data = [12].insert(4)-> append gives[12, 4];4 < parent 12, so swap to[4, 12].insert(2)-> append gives[4, 12, 2];2 < parent 4(index(2 - 1) // 2 = 0), so swap to[2, 12, 4].extract_min()-> save2, pop last value4into root[4, 12], check left child12(4 <= 12, so stop), and return2.
Complexity
insert: O(log n) time, wherenis the current heap size. Appending to a Python dynamic array takes amortized O(1) time (constant time on average across resizes), and_sift_upwalks at most one leaf-to-root path of heightfloor(log2(n)), doing O(1) work per level.extract_min: O(log n) time. Popping the last list element is O(1), and_sift_downwalks down at mostfloor(log2(n))levels, performing at most two child comparisons and one swap per level.peekandsize: O(1) time.peekreadsself.data[0]directly, andsizereads Python's stored list lengthlen(self.data).- Total run time across
qcalls: O(q log q), because the heap holds at mostqitems and each call takes at most O(log q) time. - Space: O(n) storage and O(1) auxiliary space. Storing
nelements requires O(n) space inself.data, while iterativewhileloops in_sift_upand_sift_downallocate only a handful of integer index variables (avoiding O(log n) recursive call-stack frames).
Edge cases
- Empty heap (
size == 0): callingpeek()orextract_min()returnsNonecleanly without raising anIndexError. - Transition from size 1 to size 0 (as in Example 2):
self.data.pop()removes the sole element and leavesself.dataempty; checkingif self.data:skipsself.data[0] = last_valso it does not write out of bounds, and subsequentinsertcalls work normally. - Node with only a left child: in a complete binary tree, the last internal node may have
left_idx == n - 1andright_idx == n(out of bounds); checkingleft_idx < nandright_idx < nseparately prevents reading past the end. - Duplicate values and tied children:
_sift_upbreaks whenparent <= childand_sift_downuses strict<, so equal values never spin or swap needlessly, and every duplicate copy is eventually extracted. - Negative and extreme values (
-10^9to10^9): direct<and<=comparisons handle negative numbers, zero, and large values without subtraction overflow.
Common mistakes
- Swapping with the larger child (or blindly with the left child) in
_sift_down: if root10has left child6and right child3, swapping10with6makes6the parent of3(6 > 3), corrupting the min-heap invariant. Always promote the smaller child. - Forgetting the
if self.data:check inextract_min: when the heap has 1 item,pop()emptiesself.data, so assigningself.data[0] = last_valcrashes withIndexError: list assignment index out of range. - Confusing 0-indexed and 1-indexed heap formulas:
i // 2,2 * i, and2 * i + 1only work when index0is left unused; for a 0-indexed array (root = 0), parent is(i - 1) // 2and children are2 * i + 1and2 * i + 2. - Calling
self.data.pop(0)to remove the minimum: removing index0shifts alln - 1remaining elements in O(n) time and destroys the parent-child index relationships across the tree. - Writing recursive
_sift_up/_sift_down: recursion uses O(log n) call-stack frames, violating the strict O(1) auxiliary-space requirement.
Follow-up questions
- How can you build a valid min-heap from an arbitrary list of n integers in O(n) time rather than O(n log n)? Copy the input list into
self.data, then run_sift_down(i)backwards from the last non-leaf node (i = n // 2 - 1) down to0(all indices>= n // 2are leaves of size 1 and already valid heaps). Because bottom levels hold most of the nodes and travel the shortest distance — roughlyn / 2leaves travel0steps,n / 4height-1 nodes travel at most1step,n / 8height-2 nodes travel at most2steps, and in generaln / 2^(h + 1)nodes travel at mosthsteps — the total work sums to at mostn, giving O(n) time instead of O(n log n) fromnseparateinsertcalls. - What changes are needed to support decrease_key and arbitrary index deletion in O(log n) time? For
decrease_key(index, new_val), overwriteself.data[index] = new_valand call_sift_up(index)since making a value smaller can only violate the heap rule aboveindex. Fordelete(index), poplast_val = self.data.pop(), and ifindex < len(self.data), writeself.data[index] = last_valand call both_sift_up(index)and_sift_down(index)becauselast_valcame from an unrelated branch and could be either smaller than its new parent or larger than its new children. In real callers (like Dijkstra's shortest-path algorithm), swaps constantly move items to new array indices, so you also store unique item IDs alongside a hash mapid_to_indexupdated inside every swap to locate any item's current index in O(1) time. - How would you make this heap safe for multiple threads reading and writing concurrently? Wrap every method — including
peekandsize, not justinsertandextract_min— with a single mutex (a mutual-exclusion lock that lets only one thread access the heap at a time), because during_sift_downself.data[0]temporarily holds a large leaf value before sifting completes. If worker threads also need to block until an item arrives, attach a condition variable (a synchronization primitive that lets threads sleep until signaled) to that lock soextract_minwaits while empty andinsertwakes one waiting thread — the exact design used by Python'squeue.PriorityQueue. Under extreme multi-core contention where one lock becomes a bottleneck, systems either shard items across multiple independent locked heaps (trading exact global order for throughput) or switch to a concurrent skip list (a layered linked structure supporting lock-free concurrent updates across different regions).
Follow-up questions
- How can you build a valid min-heap from an arbitrary list of n integers in O(n) time rather than O(n log n)?
- What changes are needed to support decrease_key and arbitrary index deletion in O(log n) time?
- How would you make this heap safe for multiple threads reading and writing concurrently?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array