Which scenario best fits using a Min Heap?
Think about which heap type gives quick access to the smallest element.
A Min Heap always keeps the smallest element at the top, making it ideal for priority queues where the smallest value is most important.
Which use case is best suited for a Max Heap?
Consider which heap type keeps the largest element easily accessible.
A Max Heap keeps the largest element at the root, making it perfect for priority queues where the highest value is most important.
What is the printed state of the Min Heap after inserting these elements in order: 5, 3, 8, 1?
import java.util.PriorityQueue; public class MinHeapExample { public static void main(String[] args) { PriorityQueue<Integer> minHeap = new PriorityQueue<>(); minHeap.add(5); minHeap.add(3); minHeap.add(8); minHeap.add(1); while (!minHeap.isEmpty()) { System.out.print(minHeap.poll() + " -> "); } System.out.print("null"); } }
Remember that a Min Heap always returns the smallest element first.
The PriorityQueue in Java is a Min Heap by default. Polling removes elements from smallest to largest.
What is the printed state of the Max Heap after inserting these elements in order: 2, 7, 4, 9?
import java.util.PriorityQueue; import java.util.Collections; public class MaxHeapExample { public static void main(String[] args) { PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder()); maxHeap.add(2); maxHeap.add(7); maxHeap.add(4); maxHeap.add(9); while (!maxHeap.isEmpty()) { System.out.print(maxHeap.poll() + " -> "); } System.out.print("null"); } }
Max Heap returns the largest element first when polling.
Using Collections.reverseOrder() creates a Max Heap. Polling removes elements from largest to smallest.
You want to maintain the median of a stream of numbers efficiently. Which heap combination is best?
Think about how to keep track of both halves of the data to find the median quickly.
Using a Max Heap for the lower half and a Min Heap for the upper half allows quick access to the middle values, enabling efficient median calculation.
