Heaps & Priority Queues¶
- Min Heap: A binary tree where each parent node is less than or equal to its children, ensuring that the minimum element is always at the root.
- Max Heap: A binary tree where each parent node is greater than or equal to its children, ensuring that the maximum element is always at the root.
- Heapfy: The process of converting an unordered array into a heap data structure, which can be done in O(n) time using the "sift down" method.
graph TD
N0[-4]
N1[3]
N2[1]
N3[0]
N4[2]
N5[5]
N6[10]
N7[8]
N8[12]
N9[9]
N0 --> N1
N0 --> N2
N1 --> N3
N1 --> N4
N2 --> N5
N2 --> N6
N3 --> N7
N3 --> N8
N4 --> N9
- left(i) = 2*i + 1
- right(i) = 2*i + 2
- parent(i)= (i-1)//2
Create a heap
Heap push - insert an element into the heap while maintaining the heap property.
- Time complexity: O(log n)
- Space complexity: O(1)
Heap pop - remove and return the root element (minimum for min heap, maximum for max heap) while maintaining the heap property.
- Time complexity: O(log n)
- Space complexity: O(1)