Heaps - Data Structures
Heaps - Data Structures
Heaps
Definition
A Heap is a specialized tree-based data structure that satisfies the heap property. It is
commonly used in priority queues and efficient sorting algorithms.
Types of Heaps
Min-Heap: The value of the parent node is less than or equal to its children.
Max-Heap: The value of the parent node is greater than its children.
Properties of a Heap
Typically a Complete Binary Tree: All levels of the tree are filled except possibly
the last, which is filled from left to right.
Root Node:
In a Min-Heap, the smallest value is always at the root.
In a Max-Heap, the largest value is at the root.
Priority Queues
Heap Sort
Dijkstra’s Algorithm (for finding the shortest path in a graph)
Time Complexity
Operation Complexity
Insert O(log n)
file:///Users/varunj/Projects/notes/heap_queue.html 1/6
16/03/2025, 15:52 Heaps - Data Structures
Parent node: (i - 1) / 2
Left child: 2 * i + 1
Right child: 2 * i + 2
Heap Operations
Insert Operation
Python provides the heapq module for heap operations, which only supports Min-Heaps by
default.
import heapq
# Create a heap
data = [1, 2, 3, 4]
heapq.heapify(data) # Converts list into a valid heap
file:///Users/varunj/Projects/notes/heap_queue.html 2/6
16/03/2025, 15:52 Heaps - Data Structures
Parent node: (i - 1) / 2
Left child: 2 * i + 1
Right child: 2 * i + 2
Heap Operations
Insert Operation
Python provides the heapq module for heap operations, which only supports Min-Heaps by
default.
import heapq
# Create a heap
data = [1, 2, 3, 4]
heapq.heapify(data) # Converts list into a valid heap
file:///Users/varunj/Projects/notes/heap_queue.html 3/6
16/03/2025, 15:52 Heaps - Data Structures
Max-Heap in Python
Since heapq only provides a Min-Heap, we can simulate a Max-Heap by pushing negative
values.
import heapq
max_heap = []
heapq.heappush(max_heap, -10) # Insert -10 (simulates max-heap)
Tuples can be used in priority queues where the first element of the tuple determines the
order.
import heapq
If the first elements are equal, the next elements are compared.
Queues
Definition
A Queue is a FIFO (First In, First Out) data structure, where elements are added to the
rear and removed from the front.
Types of Queues
file:///Users/varunj/Projects/notes/heap_queue.html 4/6
16/03/2025, 15:52 Heaps - Data Structures
Deque (Double-Ended Queue) - Elements can be added and removed from both
ends.
Applications of Queues
Job Scheduling
Caching
Sliding Window Problems
Breadth-First Search (BFS) Traversal
Queue Operations
Operation Description
Performance Comparison
# Create a deque
d = deque()
file:///Users/varunj/Projects/notes/heap_queue.html 5/6
16/03/2025, 15:52 Heaps - Data Structures
d.popleft() # Removes 5 (left pop)
file:///Users/varunj/Projects/notes/heap_queue.html 6/6