Keep only the largest k values by maintaining a small min-heap.

Algorithm

Steps

  1. Store the heap in an array.
  2. Compare parent and child indexes instead of building explicit tree nodes.
  3. Swap only when the heap order is violated.
  4. Print the deterministic final heap state for replay comparison.

Complexity

  • Time: O(n log k)
  • Space: O(k)
bounded heap For top-k largest values, a min-heap of size k keeps the current cutoff at the root.

Python DSA Implementation

basic.py
def list_string(values):
    return "[" + ", ".join(str(v) for v in values) + "]"

def heap_insert(heap, value):
    heap.append(value)
    child = len(heap) - 1
    while child > 0:
        parent = (child - 1) // 2
        if heap[parent] <= heap[child]:
            break
        heap[parent], heap[child] = heap[child], heap[parent]
        child = parent

def heap_pop(heap):
    smallest = heap[0]
    heap[0] = heap.pop()
    parent = 0
    while True:
        left = parent * 2 + 1
        right = left + 1
        if left >= len(heap):
            break
        child = left
        if right < len(heap) and heap[right] < heap[left]:
            child = right
        if heap[parent] <= heap[child]:
            break
        heap[parent], heap[child] = heap[child], heap[parent]
        parent = child
    return smallest
values = [5, 1, 9, 3, 7, 2]
heap = []
for value in values:
    heap_insert(heap, value)
    if len(heap) > 3:
        heap_pop(heap)
print(list_string(sorted(heap, reverse=True)))

Output

[9, 7, 5]

Implementation notes

  • This Python version uses the lesson's manual min-heap helpers over a mutable list, not heapq. heap_insert appends each value and sifts it upward with parent index (child - 1) // 2.
  • The heap is bounded to size 3: after each insert, if len(heap) > 3 calls heap_pop(heap) to remove the current minimum at the root. That keeps the root as the top-k cutoff while retaining the largest values seen so far.
  • Both helper functions mutate the same list in place with tuple-assignment swaps; no replacement heap object is allocated while scanning values.
  • The replay-visible heap states show the bounded min-heap evolving through [1, 5, 9], [3, 5, 9], and [5, 7, 9]. The final sorted(heap, reverse=True) allocates an ordered output list [9, 7, 5] without changing the heap itself; Python manages that output list while it is referenced.