Heap Extract Min or Max Bubble Down in DSA Python - Time & Space Complexity
When we remove the smallest or largest item from a heap, we need to fix the heap order. This fixing is called bubbling down.
We want to know how the time to fix the heap grows as the heap gets bigger.
Analyze the time complexity of the following code snippet.
def bubble_down(heap, index=0):
size = len(heap)
while True:
left = 2 * index + 1
right = 2 * index + 2
smallest = index
if left < size and heap[left] < heap[smallest]:
smallest = left
if right < size and heap[right] < heap[smallest]:
smallest = right
if smallest == index:
break
heap[index], heap[smallest] = heap[smallest], heap[index]
index = smallest
This code moves the root element down the heap to restore the heap property after extraction.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that compares and swaps the current node with its children.
- How many times: At most, it runs once per level of the heap, moving down from the root to a leaf.
Each time the heap size doubles, the height grows by one, so the number of steps grows slowly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 4 steps (heap height) |
| 100 | About 7 steps |
| 1000 | About 10 steps |
Pattern observation: The number of steps grows slowly, roughly proportional to the height of the heap, which increases logarithmically with input size.
Time Complexity: O(log n)
This means the time to fix the heap grows slowly as the heap gets bigger, only increasing with the height of the heap.
[X] Wrong: "Bubble down takes linear time because it looks at many elements in the heap."
[OK] Correct: The bubble down only moves down one path from root to leaf, not all elements, so it takes time proportional to the heap height, not the total number of elements.
Understanding bubble down time helps you explain how heaps keep their order efficiently. This skill shows you can analyze how data structures behave as they grow, a key part of problem solving.
"What if the heap was a ternary heap (each node has 3 children) instead of binary? How would the time complexity change?"
Practice
bubble down operation in a min-heap after extracting the minimum element?Solution
Step 1: Understand extract-min operation
When we remove the minimum element (root) from a min-heap, the last element is moved to the root position.Step 2: Apply bubble down to restore heap
The bubble down operation moves this element down the tree to restore the min-heap property by swapping it with the smaller child until correct.Final Answer:
To restore the min-heap property by moving the root element down to its correct position -> Option DQuick Check:
Bubble down fixes heap after extract-min [OK]
- Thinking bubble down inserts new elements
- Confusing bubble down with bubble up
- Assuming bubble down removes max element
i and j in a list heap during bubble down?Solution
Step 1: Recall Python tuple unpacking syntax
Python allows swapping two variables in one line using tuple unpacking: a, b = b, a.Step 2: Apply to list elements
To swap elements at indices i and j in list heap, use heap[i], heap[j] = heap[j], heap[i].Final Answer:
heap[i], heap[j] = heap[j], heap[i] -> Option CQuick Check:
Python swap uses tuple unpacking [OK]
- Assigning one element twice causing same value
- Using non-existent swap function
- Trying method swap on list which doesn't exist
heap = [2, 5, 3, 10, 7], after extracting the minimum element and performing bubble down, what will be the heap array?Solution
Step 1: Extract min and replace root
Remove 2 (root). Move last element 7 to root: heap becomes [7, 5, 3, 10].Step 2: Bubble down to restore min-heap
Compare 7 with children 5 and 3. Smallest child is 3 at index 2. Swap 7 and 3: heap becomes [3, 5, 7, 10].Final Answer:
[3, 5, 7, 10] -> Option AQuick Check:
After extract-min and bubble down heap = [3, 5, 7, 10] [OK]
- Not swapping with the smallest child
- Forgetting to remove the extracted element
- Swapping with the wrong child
def bubble_down(heap, index):
left = 2 * index + 1
right = 2 * index + 2
largest = index
if left < len(heap) and heap[left] > heap[largest]:
largest = left
if right < len(heap) and heap[right] > heap[largest]:
largest = right
if largest != index:
heap[index], heap[largest] = heap[largest], heap[index]
bubble_down(heap, largest)
What is the bug if the heap is empty when this function is called?Solution
Step 1: Trace execution on empty heap
For heap=[], index=0, len(heap)=0. left=1 < 0 is False, right=2 < 0 is False. largest remains 0. Due to short-circuit, no heap access.Step 2: No swap or recursion triggered
largest == index, so no swap executed and no recursive call. Function exits safely.Final Answer:
No bug, function handles empty heap correctly -> Option BQuick Check:
Short-circuit 'and' prevents invalid access [OK]
- Thinking heap[index] accessed causing IndexError
- Expecting infinite recursion
- Confusing IndexError with TypeError
[20, 18, 15, 10, 12, 9, 8]. After extracting the maximum element and performing bubble down, what is the resulting heap array?Solution
Step 1: Extract max and replace root
Remove 20 (root). Move last element 8 to root: heap becomes [8, 18, 15, 10, 12, 9].Step 2: Bubble down to restore max-heap
Compare 8 with children 18 and 15. Largest child is 18 at index 1. Swap 8 and 18: [18, 8, 15, 10, 12, 9].Step 3: Continue bubble down
Now at index 1, compare 8 with children 10 and 12. Largest child is 12 at index 4. Swap 8 and 12: [18, 12, 15, 10, 8, 9].Step 4: Check next level
Index 4 has no children, stop bubbling down.Final Answer:
[18, 12, 15, 10, 8, 9] -> Option AQuick Check:
Extract max + bubble down = [18, 12, 15, 10, 8, 9] [OK]
- Swapping with smaller child
- Stopping bubble down too early
- Forgetting to remove last element
Ready to prove it?
Pass the test and this pattern moves unknown
