Heap Concept Structure and Properties in DSA Javascript - Time & Space Complexity
We want to understand how the time to work with a heap changes as the heap grows.
Specifically, how fast can we add or remove items in a heap as it gets bigger?
Analyze the time complexity of inserting an element into a heap.
function insert(heap, value) {
heap.push(value);
let index = heap.length - 1;
while (index > 0) {
let parentIndex = Math.floor((index - 1) / 2);
if (heap[parentIndex] <= heap[index]) break;
[heap[parentIndex], heap[index]] = [heap[index], heap[parentIndex]];
index = parentIndex;
}
}
This code adds a new value to a min-heap and moves it up to keep the heap property.
Look for loops or repeated steps that happen as the heap changes.
- Primary operation: The while loop that moves the new value up the heap.
- How many times: At most, it moves up the height of the heap, which depends on the number of elements.
As the heap grows, the height grows slowly compared to the number of elements.
| Input Size (n) | Approx. Operations (moves up) |
|---|---|
| 10 | About 3 or 4 |
| 100 | About 6 or 7 |
| 1000 | About 9 or 10 |
Pattern observation: The number of steps grows slowly, roughly with the height of the heap, which is much smaller than the total elements.
Time Complexity: O(log n)
This means adding an element takes time proportional to the heap's height, which grows slowly as the heap gets bigger.
[X] Wrong: "Inserting into a heap takes the same time as scanning all elements, so it is O(n)."
[OK] Correct: The heap keeps elements in a tree shape, so we only move up the height, not through all elements.
Knowing heap operations run in logarithmic time shows you understand efficient data structures, a key skill in many coding challenges.
"What if we changed the heap to a linked list? How would the time complexity of insertion change?"
Practice
Solution
Step 1: Understand max heap property
A max heap requires that each parent node is greater than or equal to its children.Step 2: Compare options with max heap definition
Every parent node is greater than or equal to its child nodes matches the max heap property exactly, others describe min heap or incorrect properties.Final Answer:
Every parent node is greater than or equal to its child nodes -> Option AQuick Check:
Max heap = parent ≥ children [OK]
- Confusing max heap with min heap property
- Thinking leaf nodes must be bigger than root
- Ignoring the complete binary tree requirement
Solution
Step 1: Recall array indexing for heap
In zero-based arrays, left child index = 2*i + 1, right child index = 2*i + 2.Step 2: Match options with formula
Parent at index i, left child at 2*i + 1, right child at 2*i + 2 matches the correct formula for zero-based indexing heaps.Final Answer:
Parent at index i, left child at 2*i + 1, right child at 2*i + 2 -> Option BQuick Check:
Heap array indexing = 2*i+1, 2*i+2 [OK]
- Using one-based indexing formulas incorrectly
- Swapping left and right child indices
- Using i+1 or i+2 which is wrong for heap
const arr = [3, 9, 2, 1, 4, 5];
function maxHeapify(arr, i, n) {
let largest = i;
let left = 2 * i + 1;
let right = 2 * i + 2;
if (left < n && arr[left] > arr[largest]) largest = left;
if (right < n && arr[right] > arr[largest]) largest = right;
if (largest !== i) {
[arr[i], arr[largest]] = [arr[largest], arr[i]];
maxHeapify(arr, largest, n);
}
}
function buildMaxHeap(arr) {
let n = arr.length;
for (let i = Math.floor(n / 2) - 1; i >= 0; i--) {
maxHeapify(arr, i, n);
}
}
buildMaxHeap(arr);
console.log(arr);
What is the output printed?Solution
Step 1: Understand buildMaxHeap process
Start heapifying from last non-leaf node at index 2 (value 2), then index 1 (value 9), then index 0 (value 3).Step 2: Trace heapify calls
Initial: [3,9,2,1,4,5]
Heapify i=2: left=5 (5>2), largest=5, swap 2-5: [3,9,5,1,4,2]. Heapify 5: no children.
Heapify i=1: left=3(1<9), right=4(4<9), no swap.
Heapify i=0: left=1(9>3), largest=1; right=2(5<9), swap 0-1: [9,3,5,1,4,2]. Heapify 1 (val=3): left=3(1<3), right=4(4>3), largest=4, swap 1-4: [9,4,5,1,3,2]. Heapify 4: no children.Final Answer:
[9, 4, 5, 1, 3, 2] -> Option DQuick Check:
Max heap array after build = [9,4,5,1,3,2] [OK]
- Not heapifying recursively after swap
- Confusing indices for children
- Assuming original array order remains
function insertHeap(arr, value) {
arr.push(value);
let i = arr.length - 1;
while (i > 0) {
let parent = Math.floor(i / 2);
if (arr[parent] < arr[i]) {
[arr[parent], arr[i]] = [arr[i], arr[parent]];
i = parent;
} else {
break;
}
}
}Solution
Step 1: Check parent index formula in zero-based heap
In zero-based arrays, parent index = Math.floor((i - 1) / 2), not Math.floor(i / 2).Step 2: Understand impact of wrong parent index
Using Math.floor(i / 2) causes incorrect parent calculation, breaking heap property restoration.Final Answer:
Parent index calculation should be Math.floor((i - 1) / 2) -> Option AQuick Check:
Parent index = (i-1)//2 in zero-based heap [OK]
- Using i/2 instead of (i-1)/2 for parent
- Loop condition allowing i=0 to cause errors
- Swapping when parent is larger, not smaller
[2, 5, 8, 10, 15, 20]. You want to insert the value 1 and maintain the min heap property. Which sequence of array states correctly shows the heap after each step of insertion and heapify up?Solution
Step 1: Insert value at end
Insert 1 at the end: [2, 5, 8, 10, 15, 20, 1]Step 2: Heapify up swaps
Compare 1 with parent at index 2 (value 8), swap: [2, 5, 1, 10, 15, 20, 8]
Compare 1 with new parent at index 0 (value 2), swap: [1, 5, 2, 10, 15, 20, 8]Step 3: Final heap state
Heap property restored with 1 at root.Final Answer:
[2, 5, 8, 10, 15, 20, 1] -> [2, 5, 1, 10, 15, 20, 8] -> [1, 5, 2, 10, 15, 20, 8] -> Option CQuick Check:
Heapify up swaps child with parent until order restored [OK]
- Not swapping with correct parent index
- Stopping heapify too early
- Incorrect final heap array after swaps
Ready to prove it?
Pass the test and this pattern moves unknown
