Back to Benchmark

Heap Insert - O(log n) Complexity

Understanding how binary heaps work and why insert operations are logarithmic time

What is a Heap?

A heap is a special type of binary tree that satisfies the heap property. In a min-heap, every parent node is smaller than or equal to its children. In a max-heap, every parent node is larger than or equal to its children.

Key Properties:

  • Complete Binary Tree: All levels are filled except possibly the last, which is filled from left to right
  • Heap Property: Parent nodes maintain order with their children
  • Array Representation: Heaps are typically stored in arrays for efficiency

Heaps are commonly used for priority queues, heap sort, and finding the minimum/maximum element efficiently.

Trees and Heaps

Binary Tree Structure

A binary tree is a tree data structure where each node has at most two children (left and right). In a heap:

  • Root is at index 0 in the array representation
  • For a node at index i:
    • Left child is at index 2i + 1
    • Right child is at index 2i + 2
    • Parent is at index ⌊(i-1)/2⌋

Min-Heap vs Max-Heap

Min-Heap

Parent ≤ Children
Root is the minimum value
Used for priority queues (smallest first)

Max-Heap

Parent ≥ Children
Root is the maximum value
Used for finding maximum efficiently

Array Representation

Heaps are stored in arrays for efficiency. The tree structure is implicit:

Array: [10, 20, 30, 40, 50, 60, 70]
Tree structure:
        10 (index 0)
      /    \
    20 (1)    30 (2)
   /   \   /   \
 40 (3) 50 (4) 60 (5) 70 (6)
How Does Heap Insert Work?

1. Add to the End

Insert the new element at the end of the array (maintaining the complete binary tree property).

2. Heapify Up (Bubble Up)

Compare the new element with its parent. If it violates the heap property, swap with the parent. Repeat until the heap property is satisfied or you reach the root.

3. Logarithmic Path

The element may need to bubble up from the bottom level to the root. In the worst case, this requires traversing the height of the tree, which is O(log n):

Height of complete binary tree with n nodes: ⌊log₂(n)⌋
For 8 nodes → height = 3 → max 3 swaps
For 16 nodes → height = 4 → max 4 swaps
For 1,000,000 nodes → height ≈ 20 → max 20 swaps!
Interactive Heap Visualization
Try inserting values into the min-heap below to see how heap insert works!

Heap Tree Structure

Heap is empty

Array Representation

Code Example:

// Min-heap insert with heapify up
function insert(heap, value) {
  heap.push(value); // Add to end - O(1)
  heapifyUp(heap, heap.length - 1); // Bubble up - O(log n)
}

function heapifyUp(heap, index) {
  while (index > 0) {
    const parent = Math.floor((index - 1) / 2);
    if (heap[parent] <= heap[index]) break;
    [heap[parent], heap[index]] = [heap[index], heap[parent]];
    index = parent;
  }
}
Built-in Functions for Heaps
Many programming languages provide built-in heap data structures and functions

Why is Heap Insert O(log n)?

1. Tree Height is Logarithmic

A complete binary tree with n nodes has height ⌊log₂(n)⌋. Since we insert at the bottom and may need to bubble up to the root, the worst case is traversing the entire height.

2. At Most One Swap Per Level

During heapify up, we compare with the parent and swap if needed. We move up one level at a time, so at most we do ⌊log₂(n)⌋ comparisons and swaps.

3. Comparison with Other Operations

Heap operations complexity:

Insert: O(log n) - Bubble up from bottom
Extract Min/Max: O(log n) - Bubble down from root
Peek (get min/max): O(1) - Just return root
Build Heap: O(n) - More efficient than n inserts!
Time Complexity Comparison
OperationHeapSorted ArrayUnsorted ArrayExplanation
InsertO(log n)O(n)O(1)Heap: bubble up. Sorted: shift elements. Unsorted: just append
Get Min/MaxO(1)O(1)O(n)Heap: root. Sorted: first/last. Unsorted: must search
Extract Min/MaxO(log n)O(n)O(n)Heap: bubble down. Others: remove and shift
Build from ArrayO(n)O(n log n)N/AHeap: efficient bottom-up. Sorted: need to sort
Real-World Examples

🎯 Priority Queues

Operating systems use heaps for task scheduling. High-priority tasks are processed first, and new tasks can be inserted efficiently.

🏥 Hospital Triage

Emergency rooms use priority queues (heaps) to determine which patients to treat first based on severity. New patients are inserted with their priority level.

📊 Event Scheduling

Calendar applications use heaps to manage events by time. The earliest event is always at the root, and new events are inserted efficiently.

🎮 Game AI

Pathfinding algorithms like A* use priority queues (heaps) to explore the most promising paths first, inserting new nodes as they're discovered.

📈 Heap Sort

Heap sort uses a heap to sort an array. It builds a heap (O(n)) then repeatedly extracts the minimum (O(log n) each), resulting in O(n log n) overall.

Key Takeaways
  • Heap insert is O(log n) - logarithmic time

    Inserting requires bubbling up through at most the height of the tree, which is logarithmic

  • Heaps maintain complete binary tree structure

    All levels are filled except possibly the last, filled left to right

  • Perfect for priority queues

    Heaps excel at maintaining min/max while allowing efficient insertions and removals

  • Array representation is efficient

    Storing heaps in arrays avoids pointer overhead and provides cache-friendly access patterns

Practice Exercises
Test your understanding of heap insert with these exercises. Try to solve them yourself before checking the answers!