Question
Consider the following Java code snippet: Â Â
import java.util.PriorityQueue; Â Â public class HeapQuestion1 { Â Â Â Â public static void main(String[] args) { Â Â Â Â Â Â PriorityQueue minHeap = new PriorityQueue(); Â Â Â Â Â Â minHeap.add(10); Â Â Â Â Â Â minHeap.add(5); Â Â Â Â Â Â minHeap.add(20); Â Â Â Â Â Â minHeap.add(3); Â Â Â Â Â Â minHeap.add(15); Â Â Â Â Â Â System.out.println(minHeap.poll()); Â Â Â Â Â Â System.out.println(minHeap.peek()); Â Â Â Â Â Â System.out.println(minHeap.poll()); Â Â Â Â } Â Â } Â Â What will be the output of this program?Solution
A PriorityQueue in Java is by default a min-heap, meaning the smallest element has the highest priority.   1. minHeap.add(10); minHeap.add(5); minHeap.add(20); minHeap.add(3); minHeap.add(15);     After these additions, the heap contains {3, 5, 10, 15, 20} (not necessarily in this order internally, but 3 is at the root).   2. System.out.println(minHeap.poll());     poll() removes and returns the smallest element. So, 3 is removed and printed. The heap now contains {5, 10, 15, 20}.   3. System.out.println(minHeap.peek());     peek() retrieves the smallest element *without removing it*. The smallest element is now 5. So, 5 is printed. The heap still contains {5, 10, 15, 20}.   4. System.out.println(minHeap.poll());     poll() removes and returns the smallest element again. So, 5 is removed and printed. The heap now contains {10, 15, 20}.   Therefore, the output is 3, 5, 5.
A boat takes 3 hours to travel 30 km downstream and 5 hours to travel the same distance upstream. What is the speed of the boat in still water?
Two boats X and Y start towards each other from two places, 76 km apart. Speed of the boat X and Y in still water are 8 km/hr and 11 km/hr respectively....
Speed of a boat in still water to speed of boat in upstream is 7:5. If the boat can travel 360 km in downstream in 5 hours, then find the time taken by ...
A boat's speed in still water is 12 km/hr, and the current’s speed is 4 km/hr. If the boat takes a total of 18 hours to travel ‘x’ km each in both...
Speed of the boat in still water and the downstream speed of the boat are in the ratio of 5:6 respectively. The boat covers 80 km upstream and 72 km dow...
Speed of a boat in still water is 4 times more than the speed of stream. If boat covers 108 km in downstream in 9 hours, then find the time taken by the...
If the sum of upstream and downstream speed is 20 km/hr and the speed of the current is 5 km/hr. Then find time taken to cover 45 km in downward?
A boat travels 140 km with the flow in 7 hours. For the upstream journey over the same distance, the time taken is 7 hours more. Determine the speed of ...
Motor boat covers a certain distance downstream in 5 hours. It covers the same distance upstream in 7(1/2) hour. If the speed of the water is 4.5 km/hr,...
Speed of a boat in still water is 6 times more than the speed of stream. If boat covers 112 km in downstream in 8 hours, then find the time taken by the...