Code
import heapq
nums = [5, 8, 2, 9]
heapq.heapify(nums)
heapq.heappush(nums, 1)
print(heapq.heappop(nums))
print(heapq.heappop(nums))
Explanation:
๐น 1. Import the heapq Module
import heapq
✅ Explanation
Python imports the heapq module.
It provides functions to create and manage a Min Heap.
A Min Heap always keeps the smallest value at the top, making it easy to retrieve.
Think of it like a priority queue in a hospital.
Priority Queue
Emergency (1) ← Served First
Normal (2)
General (5)
Regular (9)
The smallest priority number is always served first.
๐น 2. Create a Normal List
nums = [5, 8, 2, 9]
✅ Explanation
Initially, this is just a normal list.
Index
0 1 2 3
│ │ │ │
5 8 2 9
Python has no idea that this list should behave like a heap.
๐น 3. Convert List into a Min Heap
heapq.heapify(nums)
✅ Explanation
heapify() doesn't sort the list completely.
Instead, it rearranges elements so that every parent is smaller than its children.
Before:
[5, 8, 2, 9]
After:
[2, 8, 5, 9]
Tree representation:
2
/ \
8 5
/
9
Notice something interesting:
8 > 5
Yet this is still a valid heap.
Why?
Because the heap only checks the relationship between a parent and its children, not between sibling nodes.
๐น 4. Insert a New Value
heapq.heappush(nums, 1)
✅ Explanation
Python first inserts 1 at the end.
Temporary heap:
[2, 8, 5, 9, 1]
Now the heap rule is broken because:
1 < 8
So Python starts moving 1 upward.
Step 1:
2
/ \
8 5
/ \
9 1
Swap with parent (8):
2
/ \
1 5
/ \
9 8
Still,
1 < 2
Swap again:
1
/ \
2 5
/ \
9 8
Final heap:
[1, 2, 5, 9, 8]
This upward movement is called Heapify Up (or Bubble Up).
๐น 5. First heappop()
print(heapq.heappop(nums))
✅ Explanation
Python removes the root because it is the smallest.
Current heap:
1
/ \
2 5
/ \
9 8
Output:
1
But removing the root creates an empty space.
Python moves the last element (8) to the root.
Temporary heap:
8
/ \
2 5
/
9
Heap rule is broken.
Since:
8 > 2
Swap:
2
/ \
8 5
/
9
Heap property restored.
Current heap:
[2, 8, 5, 9]
๐น 6. Second heappop()
print(heapq.heappop(nums))
✅ Explanation
Again, Python removes the root.
Current heap:
2
/ \
8 5
/
9
Output:
2
Move last element (9) to the top.
Temporary:
9
/ \
8 5
Compare with children.
Smallest child is:
5
Swap:
5
/ \
8 9
Heap restored.
Remaining heap:
[5, 8, 9]
๐ฏ Final Output
1
2

0 Comments:
Post a Comment