Given a valid min-heap stored as an array, remove the minimum (the root) and return the resulting heap array. Implement the sift-down yourself.
heapDelete(heap)
Removing the root: move the last element to index 0, drop the last slot, then sift the new root down by swapping with its smaller child until the heap property holds.
Input format: the heap array (a valid min-heap). Output the heap after one removal.
[1, 3, 8, 5] // → [3, 5, 8]
[1] // → []
[2, 4, 3] // → [3, 4]
A min-heap's whole point is the smallest element sits at the root, readable in O(1). The hard part: once you remove the root, what fills the hole, and how do you restore order cheaply?
Removing the root and shifting every remaining element up a slot (like deleting the first element of a plain array) would scramble parent/child relationships completely and cost O(n).
Take the last element (the most recently added leaf), drop it into the empty root position, shrink the array by one — O(1), no shifting. This new root is essentially random, so the heap property is very likely broken at the top.
Repair just the one spot that's wrong:
This walks the misplaced value down a single path, swapping below anything smaller, until it settles. Everything else in the tree was already valid — only one path needs fixing, mirroring insertion.
The tree stays complete, so its height is about log₂(n). Sift-down touches at most one node per level — O(log n), far better than re-sorting or shifting. Notice the trade with a sorted array: sorted gives O(1) minimum removal but O(n) insertion. A heap trades a slightly costlier lookup structure for O(log n) on both insertion and deletion — a better balance when you're repeatedly inserting and removing.
def heap_delete(heap):
if len(heap) <= 1:
return []
heap[0] = heap[-1]
heap.pop()
n = len(heap)
i = 0
while True:
smallest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and heap[l] < heap[smallest]:
smallest = l
if r < n and heap[r] < heap[smallest]:
smallest = r
if smallest == i:
break
heap[i], heap[smallest] = heap[smallest], heap[i]
i = smallest
return heap
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.