Command Palette

Search for a command to run...

Back to the lesson: Topic 9.8 — PriorityQueue
Core Java · Example 1 of 5

Heap order vs priority order

Offering one by one and heapifying give different (both valid) heaps for the same numbers.

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.

01

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}.

02

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.

03

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

01

How is PriorityQueue implemented, and what are the costs of offer, poll, peek, remove(Object) and contains?

02

Why doesn't printing a PriorityQueue show sorted order?

03

How do you find the k largest elements of a large array efficiently, and what is the complexity?

04

How do you make a max-heap in Java, and what's wrong with (a, b) -> b - a?

Heap order vs priority order
Sign in to run this example in your browser.

Expected output

printed (heap order): [1, 2, 5, 7, 3]
peek (the minimum):   1
polled one by one:    [1, 2, 3, 5, 7]
original untouched:   size 5
built by heapify:     [1, 2, 5, 3, 7]