Hide sidebar

Introduction to Heaps & Priority Queues

A Heap is a specialized tree-based data structure that satisfies the heap property. In a Min Heap, for any given node C, if P is a parent node of C, then the key (the value) of P is less than or equal to the key of C. In a Max Heap, the key of P is greater than or equal to the key of C.

Heaps are commonly used to implement Priority Queues, which are abstract data types that are like a regular queue or stack, but where each element has a "priority".

Key Concepts

  • Min Heap: The smallest element is always at the root.
  • Max Heap: The largest element is always at the root.
  • Insert: Adds a new element to the heap while maintaining the heap property.
  • Extract-Min/Max: Removes the root element and re-balances the heap.

Interactive Heap Visualization

The visualization below demonstrates the basic operations of a Min Heap.

Min Heap Visualization

Current Step
1 of 11
Last Operation
Ready to start
Heap Size
6
Heap operations will appear here...

Binary Heap Tree Structure

10[0]20[1]15[2]30[3]25[4]40[5]

Array Representation

[
0
10
,
1
20
,
2
15
,
3
30
,
4
25
,
5
40
]
Root (min): 10 | Parent of i: ⌊(i-1)/2⌋ | Children of i: 2i+1, 2i+2
Min Heap Property
Every parent node ≤ its children
Root contains the minimum element
Complete Binary Tree
All levels filled except possibly last
Last level filled left to right
+
INSERT
Add element, heapify up | O(log n)
EXTRACT MAX
Remove root, heapify down | O(log n)
Heap: A complete binary tree satisfying the heap property. Max heaps keep the largest element at root. Insert adds at end and heapifies up. Extract-max removes root, moves last element to root, and heapifies down. Perfect for priority queues and heap sort!