Introduction
Imagine you want to quickly find the smallest or largest item in a collection without sorting everything every time. Min-heaps and max-heaps solve this problem by organizing data so you can access these items instantly.
Jump into concepts and practice - no test required
Imagine a tournament where players compete in matches arranged in a tree. In a min-heap style tournament, the weakest player always wins each match and moves up, so the overall weakest player is at the top. In a max-heap style, the strongest player always wins and reaches the top.
┌───────┐
│ Root │
│(Min or│
│ Max) │
└───┬───┘
│
┌───────┴───────┐
│ │
┌───┴───┐ ┌───┴───┐
│ Child │ │ Child │
│ 1 │ │ 2 │
└───────┘ └───────┘
Each parent node connects to two children, maintaining the min-heap or max-heap property.import heapq # Min-heap example min_heap = [] heapq.heappush(min_heap, 5) heapq.heappush(min_heap, 3) heapq.heappush(min_heap, 8) print('Min-heap root:', min_heap[0]) # Max-heap example using negative values max_heap = [] heapq.heappush(max_heap, -5) heapq.heappush(max_heap, -3) heapq.heappush(max_heap, -8) print('Max-heap root:', -max_heap[0])
[50, 30, 40, 10, 20], what is the root value after inserting 60 and reheapifying?[5, 3, 8, 10, 7].[4, 10, 15, 20, 30]. You want to replace the root with 25 and restore the min-heap property. What will be the new root after reheapifying?