All Problems
Algorithm Visualizer

Heap Insert

O(log n) time · O(1) space · Bubble Up
Heap Tree
Array Representation (index 0 = root)
4
Build your heap, then insert a value
Heap Type
Algorithm State
i (current)
parent = (i-1)/2
heap[i]
heap[parent]
Current Heap Array
[ ]
Parent Formula
Given index i, parent is at:
parent = (i - 1) / 2

Left child of i: 2*i + 1
Right child of i: 2*i + 2
⏱ O(log n) insert ◻ O(1) space
Solution Code
class MaxHeap {
    vector<int> heap;

public:
    void push(int val) {
        // Step 1: append new value to the end of the array
        heap.push_back(val);
        int i = heap.size() - 1;

        // Step 2: bubble up — compare with parent
        while (i > 0) {
            int parent = (i - 1) / 2;
            if (heap[i] <= heap[parent]) break;   // heap property satisfied

            // Step 3: swap with parent and move up
            swap(heap[i], heap[parent]);
            i = parent;
        }
    }
};