Which scenario best fits using a Min Heap?
Think about which heap type keeps the smallest element at the top.
A Min Heap always keeps the smallest element at the root, making it ideal for quickly accessing the smallest item.
Which use case is best suited for a Max Heap?
Consider which heap type keeps the largest element at the top.
A Max Heap keeps the largest element at the root, making it perfect for quickly accessing the maximum value.
What is the printed state of the Min Heap after inserting these numbers in order: 10, 4, 15, 20, 0?
class MinHeap { constructor() { this.heap = []; } insert(num) { this.heap.push(num); this.bubbleUp(); } bubbleUp() { let index = this.heap.length - 1; while (index > 0) { let parentIndex = Math.floor((index - 1) / 2); if (this.heap[parentIndex] <= this.heap[index]) break; [this.heap[parentIndex], this.heap[index]] = [this.heap[index], this.heap[parentIndex]]; index = parentIndex; } } print() { return this.heap.join(' -> ') + ' -> null'; } } const heap = new MinHeap(); [10, 4, 15, 20, 0].forEach(n => heap.insert(n)); console.log(heap.print());
Remember that in a Min Heap, the smallest element is always at the root and the heap property must be maintained after each insertion.
After inserting all elements, the Min Heap arranges them so the smallest is at the root and parents are smaller than children. The final array representation is [0, 4, 15, 20, 10].
What is the printed state of the Max Heap after inserting these numbers in order: 3, 9, 5, 1, 12?
class MaxHeap { constructor() { this.heap = []; } insert(num) { this.heap.push(num); this.bubbleUp(); } bubbleUp() { let index = this.heap.length - 1; while (index > 0) { let parentIndex = Math.floor((index - 1) / 2); if (this.heap[parentIndex] >= this.heap[index]) break; [this.heap[parentIndex], this.heap[index]] = [this.heap[index], this.heap[parentIndex]]; index = parentIndex; } } print() { return this.heap.join(' -> ') + ' -> null'; } } const heap = new MaxHeap(); [3, 9, 5, 1, 12].forEach(n => heap.insert(n)); console.log(heap.print());
Remember that in a Max Heap, the largest element is always at the root and the heap property must be maintained after each insertion.
After inserting all elements, the Max Heap arranges them so the largest is at the root and parents are larger than children. The final array representation is [12, 9, 5, 1, 3].
You want to calculate the median of a stream of numbers in real-time. Which combination of heaps is best to maintain the median efficiently?
Think about splitting the data into two halves to quickly find the middle value.
Using a Max Heap for the lower half and a Min Heap for the upper half allows quick access to the largest of the lower half and smallest of the upper half, enabling efficient median calculation.