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) // 2 whenever i > 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 integer val into the heap while preserving the min-heap invariant.
  • extract_min() -> Optional[int]: Deletes and returns the minimum integer currently in the heap, or returns None when no elements are present.
  • peek() -> Optional[int]: Reads and returns the minimum integer without mutating the heap, or returns None when 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.
  • insert and extract_min must run in O(log n) time (n = current heap size).
  • peek and size must run in O(1) time.
  • Auxiliary space per call (excluding the array storing the n heap elements) must be O(1).

Step-by-step walkthrough

  1. Understand the goal and judge interface

    We need to build a MinHeap class from first principles using a single 0-indexed dynamic list (self.data), without heapq or built-in sorting helpers:

    • insert(val) — pushes val in O(log n) time.
    • extract_min() — removes and returns the minimum integer in O(log n) time, or None if empty.
    • peek() — returns the minimum integer without removing it in O(1) time, or None if 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 one MinHeap, replays each operation in sequence, and collects each call's return value into a list (insert appends None).

  2. 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: insert is append in O(1), but peek and extract_min must scan all n items in O(n) time.
    • Sorted list: keeping the minimum at the end makes peek and extract_min O(1), but insert must shift up to n items to keep the list sorted, taking O(n) time.

    With up to 500,000 calls, n can 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 about log2(n) (at most ~19 steps for 500,000 elements!).

  3. 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 left or right node objects — reading the tree level by level packs cleanly into a list self.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 root self.data[0], giving O(1) peek and size:

    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]
    
  4. 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 > 0 and the child is strictly smaller than its parent, swap them and step up to parent_idx. Using <= in self.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_idx
    
  5. Extract-min in O(log n): Promote the last leaf and sift down

    We cannot remove self.data[0] with pop(0) — that shifts every remaining item left in O(n) time. Instead:

    1. Save min_val = self.data[0] to return at the end.
    2. Pop last_val = self.data.pop() from the end in O(1) time, keeping the tree complete.
    3. If self.data is now empty (the heap had only 1 element), we are already done! Otherwise, place last_val at self.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] (root 10, left child 6, right child 3): if we swapped 10 with left child 6, 6 would become the parent of 3 (6 > 3), breaking the heap! Swapping with 3 puts 3 above both 6 and 10, 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_idx across idx, left_idx (if < n), and right_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
    
  6. Wire up the operation runner

    Now we implement run_min_heap_operations to instantiate MinHeap, 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 results
    
  7. Trace through Example 1

    Let's follow self.data and 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 -> stayed
    
  8. Complete 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:

  1. insert(12) -> data = [12].
  2. insert(4) -> append gives [12, 4]; 4 < parent 12, so swap to [4, 12].
  3. insert(2) -> append gives [4, 12, 2]; 2 < parent 4 (index (2 - 1) // 2 = 0), so swap to [2, 12, 4].
  4. extract_min() -> save 2, pop last value 4 into root [4, 12], check left child 12 (4 <= 12, so stop), and return 2.

Complexity

  • insert: O(log n) time, where n is the current heap size. Appending to a Python dynamic array takes amortized O(1) time (constant time on average across resizes), and _sift_up walks at most one leaf-to-root path of height floor(log2(n)), doing O(1) work per level.
  • extract_min: O(log n) time. Popping the last list element is O(1), and _sift_down walks down at most floor(log2(n)) levels, performing at most two child comparisons and one swap per level.
  • peek and size: O(1) time. peek reads self.data[0] directly, and size reads Python's stored list length len(self.data).
  • Total run time across q calls: O(q log q), because the heap holds at most q items and each call takes at most O(log q) time.
  • Space: O(n) storage and O(1) auxiliary space. Storing n elements requires O(n) space in self.data, while iterative while loops in _sift_up and _sift_down allocate only a handful of integer index variables (avoiding O(log n) recursive call-stack frames).

Edge cases

  • Empty heap (size == 0): calling peek() or extract_min() returns None cleanly without raising an IndexError.
  • Transition from size 1 to size 0 (as in Example 2): self.data.pop() removes the sole element and leaves self.data empty; checking if self.data: skips self.data[0] = last_val so it does not write out of bounds, and subsequent insert calls work normally.
  • Node with only a left child: in a complete binary tree, the last internal node may have left_idx == n - 1 and right_idx == n (out of bounds); checking left_idx < n and right_idx < n separately prevents reading past the end.
  • Duplicate values and tied children: _sift_up breaks when parent <= child and _sift_down uses strict <, so equal values never spin or swap needlessly, and every duplicate copy is eventually extracted.
  • Negative and extreme values (-10^9 to 10^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 root 10 has left child 6 and right child 3, swapping 10 with 6 makes 6 the parent of 3 (6 > 3), corrupting the min-heap invariant. Always promote the smaller child.
  • Forgetting the if self.data: check in extract_min: when the heap has 1 item, pop() empties self.data, so assigning self.data[0] = last_val crashes with IndexError: list assignment index out of range.
  • Confusing 0-indexed and 1-indexed heap formulas: i // 2, 2 * i, and 2 * i + 1 only work when index 0 is left unused; for a 0-indexed array (root = 0), parent is (i - 1) // 2 and children are 2 * i + 1 and 2 * i + 2.
  • Calling self.data.pop(0) to remove the minimum: removing index 0 shifts all n - 1 remaining 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 to 0 (all indices >= n // 2 are leaves of size 1 and already valid heaps). Because bottom levels hold most of the nodes and travel the shortest distance — roughly n / 2 leaves travel 0 steps, n / 4 height-1 nodes travel at most 1 step, n / 8 height-2 nodes travel at most 2 steps, and in general n / 2^(h + 1) nodes travel at most h steps — the total work sums to at most n, giving O(n) time instead of O(n log n) from n separate insert calls.
  • What changes are needed to support decrease_key and arbitrary index deletion in O(log n) time? For decrease_key(index, new_val), overwrite self.data[index] = new_val and call _sift_up(index) since making a value smaller can only violate the heap rule above index. For delete(index), pop last_val = self.data.pop(), and if index < len(self.data), write self.data[index] = last_val and call both _sift_up(index) and _sift_down(index) because last_val came 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 map id_to_index updated 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 peek and size, not just insert and extract_min — with a single mutex (a mutual-exclusion lock that lets only one thread access the heap at a time), because during _sift_down self.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 so extract_min waits while empty and insert wakes one waiting thread — the exact design used by Python's queue.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

Similar questions

More Pony.Ai interview questions

All 1 Pony.Ai questions →