Trees / Intermediate
Min-Heap Insert Visualizer
Add the new value at the end of the array, then let it bubble up while it is smaller than its parent.
Start the Min-Heap Insert simulation → Step forward and back, change the input, follow the code line by line in Java, Python, C++, C or JavaScript. Free, no sign-up.
Time and space complexity
| Best time | O(1) |
|---|---|
| Average time | O(log n) |
| Worst time | O(log n) |
| Extra space | O(n) |
Worked example, step by step
The same steps the simulator shows, on a small input.
- Insert the values one by one into an empty min-heap.
- Add 50 at the end, index 0.
- Add 30 at the end, index 1.
- Compare 30 with its parent 50.
- 30 is smaller, so it swaps up.
- 30 reached the root.
- Add 70 at the end, index 2.
- Compare 70 with its parent 30.
- 30 ≤ 70, so the heap is valid. Stop.
- Add 20 at the end, index 3.
- Compare 20 with its parent 50.
- 20 is smaller, so it swaps up.
- Compare 20 with its parent 30.
- 20 is smaller, so it swaps up.
- 20 reached the root.
- Add 40 at the end, index 4.
- Compare 40 with its parent 30.
- 30 ≤ 40, so the heap is valid. Stop.
- Add 60 at the end, index 5.
- Compare 60 with its parent 70.
- … 11 more steps …
- Add 65 at the end, index 8.
- Compare 65 with its parent 35.
- 35 ≤ 65, so the heap is valid. Stop.
- Done. The smallest value, 20, is at the root.
Min-heap insert in Java, Python, C++, C and JavaScript
void push(int val) {
heap.add(val);
int i = heap.size() - 1;
while (i > 0) {
int p = (i - 1) / 2;
if (heap.get(p) <= heap.get(i)) break;
swap(heap, i, p);
i = p;
}
}
def push(heap, val):
heap.append(val)
i = len(heap) - 1
while i > 0:
p = (i - 1) // 2
if heap[p] <= heap[i]:
break
heap[i], heap[p] = heap[p], heap[i]
i = p
void push(vector<int>& heap, int val) {
heap.push_back(val);
int i = heap.size() - 1;
while (i > 0) {
int p = (i - 1) / 2;
if (heap[p] <= heap[i]) break;
swap(heap[i], heap[p]);
i = p;
}
}
void push(int heap[], int* size, int val) {
heap[(*size)++] = val;
int i = *size - 1;
while (i > 0) {
int p = (i - 1) / 2;
if (heap[p] <= heap[i]) break;
int t = heap[i]; heap[i] = heap[p]; heap[p] = t;
i = p;
}
}
function push(heap, val) {
heap.push(val);
let i = heap.length - 1;
while (i > 0) {
const p = Math.floor((i - 1) / 2);
if (heap[p] <= heap[i]) break;
[heap[i], heap[p]] = [heap[p], heap[i]];
i = p;
}
}In an interview
Java’s PriorityQueue is a min-heap. It is the tool for "top k", "k-th largest" and "merge k sorted lists".