Max Heap in Python
A Max-Heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. Mapping the elements of a heap into an array is trivial: if a node is stored a index k, then its left child is stored at index 2k + 1 and its right child at index 2k + 2.
How is Max Heap represented?
A max Heap is a Complete Binary Tree. A max heap is typically represented as an array. The root element will be at Arr. Below table shows indexes of other nodes for the ith node, i.e., Arr[i]:
- Arr[(i-1)/2] Returns the parent node.
- Arr[(2*i)+1] Returns the left child node.
- Arr[(2*i)+2] Returns the right child node.
Operations on Max Heap:
- getMax(): It returns the root element of Max Heap. Time Complexity of this operation is O(1).
- extractMax(): Removes the maximum element from MaxHeap. Time Complexity of this Operation is O(log n) as this operation needs to maintain the heap property (by calling heapify()) after removing the root.
- insert(): Inserting a new key takes O(log n) time. We add a new key at the end of the tree. If the new key is smaller than its parent, then we don’t need to do anything. Otherwise, we need to traverse up to fix the violated heap property.
Note: In the below implementation, we do indexing from index 1 to simplify the implementation.
The maxHeap is PARENT : 84LEFT CHILD : 22RIGHT CHILD : 19 PARENT : 22LEFT CHILD : 17RIGHT CHILD : 10 PARENT : 19LEFT CHILD : 5RIGHT CHILD : 6 PARENT : 17LEFT CHILD : 3RIGHT CHILD : 9 The Max val is 84
Using Library functions:
We use heapq class to implement Heap in Python. By default Min Heap is implemented by this class. But we multiply each value by -1 so that we can use it as MaxHeap.
Head value of heap : 400 The heap elements : 400 30 20 10 The heap elements : 30 10 20
Using Library functions with dunder method for Numbers, Strings, Tuples, Objects etc
We use heapq class to implement Heaps in Python. By default Min Heap is implemented by this class.
To implement MaxHeap not limiting to only numbers but any type of object(String, Tuple, Object etc) we should
- Create a Wrapper class for the item in the list.
- Override the __lt__ dunder method to give inverse result.
Following is the implementation of the method mentioned here.
Top of numbers are: 400 The string heap elements in order: wonderful this is code