Hide sidebar

Introduction to Heaps

A Heap is a specialized tree-based data structure that satisfies the heap property. In a min-heap, for any given node, its value is less than or equal to the values of its children. In a max-heap, the value is greater than or equal. Heaps are commonly used to implement priority queues.

Interactive Heap Visualization

The visualization below demonstrates the structure and functionality of a Min-Heap. You can insert and extract the minimum value to see how the heap property is maintained.

10
20
15
30
40

Heap Data Structure

A Heap is a specialized tree-based data structure that satisfies the heap property. In a min-heap, for any given node, its value is less than or equal to the values of its children. In a max-heap, the value is greater than or equal. Heaps are commonly used to implement priority queues.

Key Operations

  • Insert: Add the new element to the end of the array, then "heapify-up" to restore the heap property.
  • Extract Min/Max: Remove the root element, replace it with the last element in the array, then "heapify-down" to restore the heap property.
  • Peek: Return the root element without removing it.
Heap Implementation

import heapq

# Min-heap implementation
class MinHeap:
    def __init__(self):
        self.heap = []

    def push(self, val):
        heapq.heappush(self.heap, val)

    def pop(self):
        return heapq.heappop(self.heap)

    def peek(self):
        return self.heap[0] if self.heap else None

# Max-heap (by negating values)
class MaxHeap:
    def __init__(self):
        self.heap = []

    def push(self, val):
        heapq.heappush(self.heap, -val)

    def pop(self):
        return -heapq.heappop(self.heap)

    def peek(self):
        return -self.heap[0] if self.heap else None