A Max-Heap is a Data Structure with the following properties:
- It is a Complete Binary Tree.
- The value of the root node must be the largest among all its descendant nodes, and the same thing must be done for its left and right sub-tree also.
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[0]. 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.
Python
import sys
class MaxHeap:
def __init__(self, cap):
self.cap = cap
self.n = 0
self.a = [0] * (cap + 1)
self.a[0] = sys.maxsize
self.root = 1
def parent(self, i):
return i // 2
def left(self, i):
return 2 * i
def right(self, i):
return 2 * i + 1
def isLeaf(self, i):
return i > (self.n // 2) and i <= self.n
def swap(self, i, j):
self.a[i], self.a[j] = self.a[j], self.a[i]
def maxHeapify(self, i):
if not self.isLeaf(i):
largest = i
if self.left(i) <= self.n and self.a[i] < self.a[self.left(i)]:
largest = self.left(i)
if self.right(i) <= self.n and self.a[largest] < self.a[self.right(i)]:
largest = self.right(i)
if largest != i:
self.swap(i, largest)
self.maxHeapify(largest)
def insert(self, val):
if self.n >= self.cap:
return
self.n += 1
self.a[self.n] = val
i = self.n
while self.a[i] > self.a[self.parent(i)]:
self.swap(i, self.parent(i))
i = self.parent(i)
def extractMax(self):
if self.n == 0:
return None
max_val = self.a[self.root]
self.a[self.root] = self.a[self.n]
self.n -= 1
self.maxHeapify(self.root)
return max_val
def printHeap(self):
for i in range(1, (self.n // 2) + 1):
print(f"PARENT: {self.a[i]}", end=" ")
if self.left(i) <= self.n:
print(f"LEFT: {self.a[self.left(i)]}", end=" ")
if self.right(i) <= self.n:
print(f"RIGHT: {self.a[self.right(i)]}", end=" ")
print()
# Example
if __name__ == "__main__":
print("The maxHeap is:")
h = MaxHeap(15)
vals = [5, 3, 17, 10, 84, 19, 6, 22, 9]
for val in vals:
h.insert(val)
h.printHeap()
print("The Max val is", h.extractMax())
Output:
The maxHeap is
PARENT : 84 LEFT CHILD : 22 RIGHT CHILD : 19
PARENT : 22 LEFT CHILD : 17 RIGHT CHILD : 10
PARENT : 19 LEFT CHILD : 5 RIGHT CHILD : 6
PARENT : 17 LEFT CHILD : 3 RIGHT 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.
Python
# Python3 program to demonstrate heapq (Max Heap)
from heapq import heappop, heappush, heapify
# Create an empty heap
h = []
heapify(h)
# Add elements (multiplying by -1 to simulate Max Heap)
heappush(h, -10)
heappush(h, -30)
heappush(h, -20)
heappush(h, -400)
# Print max element
print("Max:", -h[0])
# Print heap elements
print("Heap:", [-i for i in h])
# Pop max element
heappop(h)
# Print heap after removal
print("Heap after pop:", [-i for i in h])
OutputMax: 400
Heap: [400, 30, 20, 10]
Heap after pop: [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.
Python
"""
Python3 program to implement MaxHeap using heapq
for Strings, Numbers, and Objects
"""
from functools import total_ordering
import heapq
@total_ordering
class Wrap:
def __init__(self, v):
self.v = v
def __lt__(self, o):
return self.v > o.v # Reverse for Max Heap
def __eq__(self, o):
return self.v == o.v
# Max Heap for numbers
h = [10, 20, 400, 30]
wh = list(map(Wrap, h))
heapq.heapify(wh)
print("Max:", heapq.heappop(wh).v)
# Max Heap for strings
h = ["this", "code", "is", "wonderful"]
wh = list(map(Wrap, h))
heapq.heapify(wh)
print("Heap:", end=" ")
while wh:
print(heapq.heappop(wh).v, end=" ")
OutputMax: 400
Heap: wonderful this is code
Using internal functions used in the heapq library
This is by far the most simple and convenient way to apply max heap in python.
DISCLAIMER - In Python, there's no strict concept of private identifiers like in C++ or Java. Python trusts developers and allows access to so-called "private" identifiers. However, since these identifiers are intended for internal use within the module, they are not officially part of the public API and may change or be removed in the future.
Following is the implementation.
Python
from heapq import _heapify_max, _heappop_max, _siftdown_max
# Implementing heappush for max heap
def hpush(h, v):
h.append(v)
_siftdown_max(h, 0, len(h)-1)
def maxh(a):
c = a.copy() # Copy for later use
_heapify_max(a) # Convert to max heap
while a:
print(_heappop_max(a)) # Pop elements
a = c # Restore array
h = []
for v in a:
hpush(h, v) # Insert elements back into heap
print("Max Heap Ready!")
while h:
print(_heappop_max(h)) # Pop elements
# Example
a = [6, 8, 9, 2, 1, 5]
maxh(a)
Output9
8
6
5
2
1
Max Heap Ready!
9
8
6
5
2
1
Using Priority Queue
Python
from queue import PriorityQueue
q = PriorityQueue()
# Insert elements into the queue (negate values to simulate Max Heap)
q.put(-10)
q.put(-20)
q.put(-5)
# Remove and return the highest priority item (convert back to positive)
print(-q.get()) # 20 (highest value)
print(-q.get()) # 10
# Check queue size
print('Items in queue:', q.qsize())
# Check if queue is empty
print('Is queue empty:', q.empty())
# Check if queue is full
print('Is queue full:', q.full())
Output20
10
Items in queue: 1
Is queue empty: False
Is queue full: False
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read