Top-k largest with a size-k min-heap
PriorityQueue always hands out the smallest element first (or the largest, with a reversed comparator). It's a binary heap stored in an array: peek is O(1), offer and poll are O(log n), and its iteration order is not sorted.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Merge the sorted arrays {1, 4, 7}, {2, 5, 8} and {3, 6, 9} into one sorted list using a PriorityQueue<int[]> holding {value, arrayIndex, elementIndex}.
Return the 2 most frequent words in ["tea", "cake", "tea", "chai", "cake", "tea"], using a HashMap for counts and a PriorityQueue for the top 2.
Simulate a meeting-room scheduler: given meetings {0, 30}, {5, 10} and {15, 20} (start, end), compute the minimum number of rooms needed using a min-heap of end times.
Explain it without notes
How is PriorityQueue implemented, and what are the costs of offer, poll, peek, remove(Object) and contains?
Why doesn't printing a PriorityQueue show sorted order?
How do you find the k largest elements of a large array efficiently, and what is the complexity?
How do you make a max-heap in Java, and what's wrong with (a, b) -> b - a?
Expected output
top 3: [980, 760, 410]
top 1: [980]
4th largest is the root: 300