Bird
Raised Fist0
DSA Javascriptprogramming

Min Heap vs Max Heap When to Use Which in DSA Javascript - Trade-offs & Analysis

Choose your learning style10 modes available
Mental Model
A min heap keeps the smallest item on top, while a max heap keeps the largest item on top. This helps quickly find the smallest or largest value.
Analogy: Think of a min heap like a line where the shortest person is always at the front, and a max heap like a line where the tallest person is always at the front.
Min Heap (smallest on top):
      1
     / \
    3   5
   / \
  7   9

Max Heap (largest on top):
      9
     / \
    7   5
   / \
  3   1
Dry Run Walkthrough
Input: array: [5, 3, 9, 1, 7], build min heap and max heap
Goal: Show how min heap and max heap organize the same numbers differently to quickly access smallest or largest
Step 1: Insert 5 as root in both heaps
Min Heap: 5 -> null
Max Heap: 5 -> null
Why: Start with first element as root
Step 2: Insert 3, compare with root, swap in min heap; compare and no swap in max heap
Min Heap: 3 -> 5 -> null
Max Heap: 5 -> 3 -> null
Why: Min heap keeps smallest on top, max heap keeps largest on top
Step 3: Insert 9, no swap in min heap; swap with root in max heap
Min Heap: 3 -> 5 -> 9 -> null
Max Heap: 9 -> 3 -> 5 -> null
Why: Min heap root is smallest, max heap root is largest
Step 4: Insert 1, swap up to root in min heap; no swap in max heap
Min Heap: 1 -> 3 -> 9 -> 5 -> null
Max Heap: 9 -> 3 -> 5 -> 1 -> null
Why: 1 is smallest, so min heap moves it to top
Step 5: Insert 7, no swap in min heap; swap with 3 in max heap
Min Heap: 1 -> 3 -> 9 -> 5 -> 7 -> null
Max Heap: 9 -> 7 -> 5 -> 1 -> 3 -> null
Why: Max heap moves larger 7 up to keep largest on top
Result:
Min Heap final: 1 -> 3 -> 9 -> 5 -> 7 -> null
Max Heap final: 9 -> 7 -> 5 -> 1 -> 3 -> null
Annotated Code
DSA Javascript
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; // move up to parent
      } else {
        break; // heap property satisfied
      }
    }
  }

  toString() {
    return this.data.join(' -> ') + ' -> null';
  }
}

// Min heap: smaller value has higher priority
const minHeap = new Heap((a, b) => a < b);
// Max heap: larger value has higher priority
const maxHeap = new Heap((a, b) => a > b);

const values = [5, 3, 9, 1, 7];
for (const val of values) {
  minHeap.insert(val);
  maxHeap.insert(val);
}

console.log('Min Heap final:', minHeap.toString());
console.log('Max Heap final:', maxHeap.toString());
if (this.compare(this.data[index], this.data[parentIndex])) {
compare current node with parent to decide if swap needed
[this.data[index], this.data[parentIndex]] = [this.data[parentIndex], this.data[index]];
swap current node with parent to maintain heap property
index = parentIndex; // move up to parent
advance index upward to continue checking heap property
OutputSuccess
Min Heap final: 1 -> 3 -> 9 -> 5 -> 7 -> null Max Heap final: 9 -> 7 -> 5 -> 1 -> 3 -> null
Complexity Analysis
Time: O(n log n) because each insert may bubble up through the heap height which is log n, repeated n times
Space: O(n) because we store all elements in the heap array
vs Alternative: Compared to sorting the array which is O(n log n), heaps allow quick access to min or max without full sort
Edge Cases
empty input array
heap remains empty, no errors
DSA Javascript
for (const val of values) { ... } handles empty array by skipping loop
all elements equal
heap structure still valid, order of equal elements maintained by insertion order
DSA Javascript
if (this.compare(this.data[index], this.data[parentIndex])) { ... } no swap if equal
single element
heap contains one element, no bubbling needed
DSA Javascript
while (index > 0) { ... } loop skipped if index is 0
When to Use This Pattern
When a problem asks for quick access to the smallest or largest element repeatedly, use a min heap or max heap respectively to efficiently track that value.
Common Mistakes
Mistake: Using the wrong comparison function causing min heap to behave like max heap or vice versa
Fix: Ensure the compare function correctly returns true when the child should move up (a < b for min heap, a > b for max heap)
Summary
Min heap keeps smallest element on top; max heap keeps largest element on top.
Use min heap when you need quick access to smallest values, max heap for largest values.
The key is the comparison function that decides which element moves up to maintain heap order.

Practice

(1/5)
1. Which heap type is best suited when you need to quickly find the smallest element in a collection?
easy
A. Binary Search Tree
B. Min Heap
C. Max Heap
D. Hash Table

Solution

  1. Step 1: Understand the heap types

    A Min Heap always keeps the smallest element at the root, making it easy to access.
  2. Step 2: Match the requirement with heap property

    Since we want quick access to the smallest element, Min Heap is the best choice.
  3. Final Answer:

    Min Heap -> Option B
  4. Quick Check:

    Smallest element = Min Heap [OK]
Hint: Smallest element? Use Min Heap [OK]
Common Mistakes:
  • Confusing Min Heap with Max Heap
  • Choosing data structures unrelated to heaps
  • Thinking Max Heap gives smallest element
2. Which of the following is the correct way to insert an element into a Max Heap in JavaScript?
easy
A. Add element at the end and heapify down
B. Add element at root and heapify down
C. Add element at the end and heapify up
D. Add element at root and heapify up

Solution

  1. Step 1: Recall Max Heap insertion process

    New elements are added at the end (bottom level) to maintain complete tree property.
  2. Step 2: Restore heap property by heapifying up

    After insertion, heapify up swaps the new element with parents if larger, to maintain Max Heap.
  3. Final Answer:

    Add element at the end and heapify up -> Option C
  4. Quick Check:

    Insert = end + heapify up [OK]
Hint: Insert at end, then heapify up for Max Heap [OK]
Common Mistakes:
  • Heapifying down after insertion
  • Inserting at root directly
  • Confusing heapify direction
3. Consider the following JavaScript code using a Min Heap implementation:
const minHeap = new MinHeap();
minHeap.insert(10);
minHeap.insert(5);
minHeap.insert(20);
minHeap.insert(3);
console.log(minHeap.extract());
What will be printed?
medium
A. 20
B. 10
C. 5
D. 3

Solution

  1. Step 1: Insert elements into Min Heap

    Elements 10, 5, 20, 3 are inserted. Min Heap keeps smallest element at root.
  2. Step 2: Extract removes and returns the smallest element

    Extract returns the root, which is the smallest: 3.
  3. Final Answer:

    3 -> Option D
  4. Quick Check:

    Min Heap extract = smallest element [OK]
Hint: Extract from Min Heap returns smallest [OK]
Common Mistakes:
  • Thinking extract returns largest
  • Confusing Min Heap with Max Heap
  • Ignoring heap property after insertions
4. You have a Max Heap implementation but notice that after inserting a new element, the heap property is violated. Which of the following is the most likely cause?
medium
A. Heapify down was called instead of heapify up after insertion
B. Element was inserted at the root instead of the end
C. Heapify up was called twice
D. Heapify down was not called after extraction

Solution

  1. Step 1: Understand insertion in Max Heap

    Insertion adds element at the end and restores heap by heapifying up.
  2. Step 2: Identify error from heapify direction

    Calling heapify down after insertion won't fix the heap property properly, causing violation.
  3. Final Answer:

    Heapify down was called instead of heapify up after insertion -> Option A
  4. Quick Check:

    Insert needs heapify up, not down [OK]
Hint: Insertion needs heapify up, not down [OK]
Common Mistakes:
  • Inserting at root directly
  • Confusing heapify directions
  • Ignoring heapify after insertion
5. You need to design a system that always returns the median of a stream of numbers efficiently. Which combination of heaps is best to use and why?
hard
A. One Max Heap for lower half and one Min Heap for upper half
B. Two Max Heaps to store all numbers
C. One Min Heap for lower half and one Max Heap for upper half
D. Two Min Heaps to store all numbers

Solution

  1. Step 1: Understand median calculation from stream

    Median splits data into lower half and upper half; median is middle value(s).
  2. 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.
  3. Final Answer:

    One Max Heap for lower half and one Min Heap for upper half -> Option A
  4. Quick Check:

    Median = Max Heap (low) + Min Heap (high) [OK]
Hint: Median needs Max Heap low + Min Heap high [OK]
Common Mistakes:
  • Using two heaps of same type
  • Mixing heap roles incorrectly
  • Not balancing heaps sizes
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard