Imagine you have a list of numbers that you want to keep sorted. You can use a sorted array or a heap. Which reason best explains why heaps are better for frequent insertions?
Think about what happens when you add a new number to a sorted list.
Inserting into a sorted array requires shifting elements to keep order, which takes time proportional to the number of elements. A heap allows insertion in logarithmic time by adjusting only part of the structure.
What is the printed state of the min-heap after inserting the elements 5, 3, 8, 1 in that order?
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); System.out.println(minHeap); } }
Remember that Java's PriorityQueue prints elements in heap order, not sorted order.
The PriorityQueue stores elements so that the smallest is at the front. The internal order when printed shows the heap structure, where 1 is the root, followed by 3 and 8, then 5.
Consider a max-heap and a sorted array both containing the same numbers. Which statement best explains why finding the minimum element is slower in a max-heap?
Think about where the smallest number is located in a max-heap.
In a max-heap, the largest element is at the root. The smallest element can be anywhere among the leaves, so you must check many elements. In a sorted array, the smallest element is always at the first position.
What error will occur when running this Java code that inserts elements into a min-heap?
import java.util.PriorityQueue; public class HeapTest { public static void main(String[] args) { PriorityQueue<Integer> heap = new PriorityQueue<>(); heap.add(10); heap.add(20); heap.add(null); System.out.println(heap); } }
Think about whether null values are allowed in Java PriorityQueue.
Java's PriorityQueue does not allow null elements. Adding null causes a NullPointerException at runtime.
Which explanation best describes why a sorted array cannot efficiently support both fast insertion and fast minimum extraction?
Think about what happens when you add a new element to keep the array sorted.
Sorted arrays keep elements in order, so the minimum is always at the start and can be extracted quickly. However, inserting a new element requires shifting many elements to keep order, which is slow.
