Min Heap vs Max Heap When to Use Which in DSA Javascript - Complexity Comparison
We want to understand how fast operations run in Min Heaps and Max Heaps.
Which heap is better depends on what we want to do with the data.
Analyze the time complexity of inserting and removing elements in Min and Max Heaps.
class Heap {
constructor(compare) {
this.data = [];
this.compare = compare;
}
insert(value) {
this.data.push(value);
this.bubbleUp();
}
bubbleUp() {
let index = this.data.length - 1;
while (index > 0) {
let parentIndex = Math.floor((index - 1) / 2);
if (this.compare(this.data[index], this.data[parentIndex])) {
[this.data[index], this.data[parentIndex]] = [this.data[parentIndex], this.data[index]];
index = parentIndex;
} else {
break;
}
}
}
remove() {
if (this.data.length === 0) return null;
const root = this.data[0];
const end = this.data.pop();
if (this.data.length > 0) {
this.data[0] = end;
this.bubbleDown();
}
return root;
}
bubbleDown() {
let index = 0;
const length = this.data.length;
const element = this.data[0];
while (true) {
let leftChildIndex = 2 * index + 1;
let rightChildIndex = 2 * index + 2;
let swapIndex = null;
if (leftChildIndex < length) {
if (this.compare(this.data[leftChildIndex], element)) {
swapIndex = leftChildIndex;
}
}
if (rightChildIndex < length) {
if (
(swapIndex === null && this.compare(this.data[rightChildIndex], element)) ||
(swapIndex !== null && this.compare(this.data[rightChildIndex], this.data[leftChildIndex]))
) {
swapIndex = rightChildIndex;
}
}
if (swapIndex === null) break;
[this.data[index], this.data[swapIndex]] = [this.data[swapIndex], this.data[index]];
index = swapIndex;
}
}
}
// Min Heap: compare = (a, b) => a < b
// Max Heap: compare = (a, b) => a > b
This code shows how insertion and removal work in both Min and Max Heaps using a comparison function.
We look at the main repeated steps in the code.
- Primary operation: The
bubbleUpandbubbleDownloops that move elements up or down the tree. - How many times: At most, they run once per level of the heap, which is about log of the number of elements.
As the heap grows, the number of levels increases slowly.
| Input Size (n) | Approx. Operations (bubbleUp or bubbleDown steps) |
|---|---|
| 10 | About 3 to 4 steps |
| 100 | About 6 to 7 steps |
| 1000 | About 9 to 10 steps |
Pattern observation: The steps grow slowly, roughly adding one step each time the input size multiplies by 2.
Time Complexity: O(log n)
This means inserting or removing an element takes time that grows slowly as the heap gets bigger.
[X] Wrong: "Min Heap and Max Heap have different time complexities for insert and remove."
[OK] Correct: Both heaps use the same structure and operations, so their time complexities are the same; only the comparison direction changes.
Knowing when to use Min or Max Heap and understanding their time costs helps you solve problems efficiently and explain your choices clearly.
What if we changed the heap to a balanced binary search tree? How would the time complexity for insert and remove compare?
Practice
Solution
Step 1: Understand the heap types
A Min Heap always keeps the smallest element at the root, making it easy to access.Step 2: Match the requirement with heap property
Since we want quick access to the smallest element, Min Heap is the best choice.Final Answer:
Min Heap -> Option BQuick Check:
Smallest element = Min Heap [OK]
- Confusing Min Heap with Max Heap
- Choosing data structures unrelated to heaps
- Thinking Max Heap gives smallest element
Solution
Step 1: Recall Max Heap insertion process
New elements are added at the end (bottom level) to maintain complete tree property.Step 2: Restore heap property by heapifying up
After insertion, heapify up swaps the new element with parents if larger, to maintain Max Heap.Final Answer:
Add element at the end and heapify up -> Option CQuick Check:
Insert = end + heapify up [OK]
- Heapifying down after insertion
- Inserting at root directly
- Confusing heapify direction
const minHeap = new MinHeap(); minHeap.insert(10); minHeap.insert(5); minHeap.insert(20); minHeap.insert(3); console.log(minHeap.extract());What will be printed?
Solution
Step 1: Insert elements into Min Heap
Elements 10, 5, 20, 3 are inserted. Min Heap keeps smallest element at root.Step 2: Extract removes and returns the smallest element
Extract returns the root, which is the smallest: 3.Final Answer:
3 -> Option DQuick Check:
Min Heap extract = smallest element [OK]
- Thinking extract returns largest
- Confusing Min Heap with Max Heap
- Ignoring heap property after insertions
Solution
Step 1: Understand insertion in Max Heap
Insertion adds element at the end and restores heap by heapifying up.Step 2: Identify error from heapify direction
Calling heapify down after insertion won't fix the heap property properly, causing violation.Final Answer:
Heapify down was called instead of heapify up after insertion -> Option AQuick Check:
Insert needs heapify up, not down [OK]
- Inserting at root directly
- Confusing heapify directions
- Ignoring heapify after insertion
Solution
Step 1: Understand median calculation from stream
Median splits data into lower half and upper half; median is middle value(s).Step 2: Use Max Heap for lower half and Min Heap for upper half
Max Heap keeps largest of lower half, Min Heap keeps smallest of upper half, enabling quick median calculation.Final Answer:
One Max Heap for lower half and one Min Heap for upper half -> Option AQuick Check:
Median = Max Heap (low) + Min Heap (high) [OK]
- Using two heaps of same type
- Mixing heap roles incorrectly
- Not balancing heaps sizes
Ready to prove it?
Pass the test and this pattern moves unknown
