Quick revision
The short answer
java.util.PriorityQueue is a binary min-heap stored in a plain Object array, where the children of index i sit at 2i+1 and 2i+2. offer and poll cost O(log n) because they sift one element up or down the tree, peek is O(1) because the smallest element is always at index 0, and remove(Object) and contains are O(n) because the heap has no index and must be scanned.
What to remember
In this answer, we saw that PriorityQueue is a binary min-heap kept in an array, with children of index i at 2i + 1 and 2i + 2. offer appends and sifts up and poll moves the last element to the root and sifts down, both O(log n), while peek just reads index 0 in O(1). contains and remove(Object) scan the array in O(n) because nothing indexes element positions. Iteration and toString follow the array, not the priority order. Finally, the class is not thread safe; PriorityBlockingQueue is the locked version, and DelayQueue uses a priority queue to release elements when their delay expires.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
java.util.PriorityQueue is a binary min-heap stored in a plain Object array, where the children of index i sit at 2i+1 and 2i+2. offer and poll cost O(log n) because they sift one element up or down the tree, peek is O(1) because the smallest element is always at index 0, and remove(Object) and contains are O(n) because the heap has no index and must be scanned.
Why this question is asked
PriorityQueue shows up in schedulers, top-k problems, Dijkstra's shortest path and event simulations, so we reach for it often. Interviewers ask about its internals because the costs are not uniform: two operations are logarithmic, one is constant and two are linear, and people who assume everything is fast get burned when a queue of a million elements starts calling remove(Object). In this answer, we will recap what a heap is, see how it fits into an array, walk through offer and poll step by step, explain why remove and contains are slow, look at the iteration-order surprise, and finish with thread safety and the concurrent relatives.
1A Quick Recap of the Binary Heap
A binary heap is a tree in which every parent is smaller than or equal to its children. That rule, called the heap property, says nothing about the order between siblings or between different branches. It only guarantees one thing: the smallest element is at the root. That is exactly what a priority queue needs, because it only ever promises to hand us the smallest element next.
The heap is also complete, which means every level is full except possibly the last, and the last level fills from left to right. A complete tree has no gaps, so it can be stored in an array without any pointers. PriorityQueue keeps its elements in a field called queue, an Object array, and a size counter. The root lives at index 0, and for any index i the left child is at 2i + 1, the right child at 2i + 2, and the parent at (i - 1) / 2, computed in the JDK as (i - 1) >>> 1.
Notice that the array is not sorted: 2 comes before 7 but after 3. Only the parent-child relation is ordered. Ordering comes from the natural order of the elements (they implement Comparable) or from a Comparator we pass to the constructor, which is how we build a max-heap with Comparator.reverseOrder().
2How offer Sifts an Element Up
When we call offer(e), PriorityQueue first grows the array if it is full. The growth policy roughly doubles a small queue and adds 50 percent to a larger one, and the copy is amortised over many inserts, so it does not change the average cost.
The new element is placed in the first free slot, at index size, which keeps the tree complete. That may break the heap property, so the queue runs siftUp: it compares the element with its parent and, if the element is smaller, moves the parent down into the hole and continues one level higher. It stops when the parent is smaller or when it reaches the root. The tree has about log2(n) levels, so for a million elements the loop runs at most about 20 times. That is why offer is O(log n).
- Grow the array if fullamortised O(1)
- Place 1 at index sizekeeps the tree complete
- Is 1 smaller than its parent?YesSwap with the parent and repeatNoStop: heap property holds
- Doneat most
log2(n)comparisons
4 steps in order. Play them, or step through them one at a time.
3How poll Sifts an Element Down
poll() must return the root, index 0. Removing it leaves a hole at the top, so the queue takes the last element of the array, shrinks size by one, and puts that last element at the root. Again the heap property may be broken, so it runs siftDown: it picks the smaller of the two children, and if that child is smaller than the element, moves the child up and continues one level lower. Each level costs two comparisons, and there are about log2(n) levels, so poll is O(log n).
peek() is different. It only reads queue[0] and returns it, or null when the queue is empty. Nothing moves, so it is O(1). The same applies to element(), which throws NoSuchElementException instead of returning null.
So, if we poll repeatedly until the queue is empty, we get the elements in sorted order. That is heap sort, O(n log n) in total.
4Why remove(Object) and contains Are Linear
The heap knows where the smallest element is, but it has no idea where any other element is. There is no hash table mapping elements to positions. So contains(o) has to walk the array from index 0 to size - 1 and call equals() on each element, which is O(n).
remove(o) does the same scan to find the index, which is O(n), and then fixes the heap at that index. It moves the last element into the hole and sifts it down, and if it did not move down, sifts it up. That repair is only O(log n), but the scan dominates. With 10 million elements, every remove(Object) can touch 10 million references, which is why code that cancels items in a large PriorityQueue becomes CPU bound.
| Operation | Cost | Why |
|---|---|---|
| offer / add | O(log n) | append at the end, then siftUp |
poll / remove() | O(log n) | last element to the root, then siftDown |
| peek / element | O(1) | read index 0 |
contains(o) | O(n) | linear scan with equals() |
remove(o) | O(n) | linear scan, then O(log n) repair |
new PriorityQueue(collection) | O(n) | heapify from the bottom up |
5Iteration and toString Are Not in Priority Order
A very common surprise is printing a priority queue and seeing an order that looks random. The iterator, toString(), toArray() and forEach all walk the backing array from index 0 upwards, and the array is a heap, not a sorted list. Only the first element is guaranteed to be the smallest.
If we need the elements in order without emptying the queue, we copy them and sort the copy, which is O(n log n). The iterator also does not support changing priorities: if we mutate a field that the comparator reads while the element sits in the heap, the heap property silently breaks and poll can return the wrong element. The correct way is to remove the element, change it, and offer it again.
6Thread Safety and the Concurrent Relatives
PriorityQueue is not thread safe. Two threads calling offer at the same time can corrupt the array or lose elements, and the iterator is fail-fast, throwing ConcurrentModificationException if the queue changes during iteration. It also rejects null elements, because poll uses null to mean empty.
For concurrent use, the JDK provides PriorityBlockingQueue, which is the same array-based heap protected by a single ReentrantLock, and which adds a blocking take() that waits until an element is available. It is unbounded, so producers never block. DelayQueue builds on a PriorityQueue internally: its elements implement Delayed, they are ordered by remaining delay, and take() only returns an element once its delay has expired. ScheduledThreadPoolExecutor uses its own similar heap, a DelayedWorkQueue, for scheduled tasks.
7Follow-up questions
Why is building a PriorityQueue from a collection O(n) and not O(n log n)?
The constructor that takes a collection copies the elements into the array and then heapifies from the bottom up: it calls siftDown on every parent, starting from the last parent and moving to the root. Most nodes are near the bottom and only sift down a level or two, and the sum of those small heights over the whole tree is linear. Offering the elements one by one would cost O(n log n) instead.
How do I make a max-heap?
Pass a comparator that reverses the order, for example new PriorityQueue<>(Comparator.reverseOrder()) for Comparable elements, or Comparator.comparingInt(Task::priority).reversed() for objects. Avoid writing the comparator as (a, b) -> b - a for ints, because the subtraction overflows for large values of opposite sign; Integer.compare(b, a) is safe.
Is PriorityQueue stable for equal priorities?
No. Elements that compare as equal can come out in any order, because sifting does not remember insertion order. If we need first-in first-out among equals, we add a sequence number from an AtomicLong or a counter to each element and compare by it as a tie breaker.
8Conclusion
In this answer, we saw that PriorityQueue is a binary min-heap kept in an array, with children of index i at 2i + 1 and 2i + 2. offer appends and sifts up and poll moves the last element to the root and sifts down, both O(log n), while peek just reads index 0 in O(1). contains and remove(Object) scan the array in O(n) because nothing indexes element positions. Iteration and toString follow the array, not the priority order. Finally, the class is not thread safe; PriorityBlockingQueue is the locked version, and DelayQueue uses a priority queue to release elements when their delay expires.
Open with
PriorityQueue is a binary min-heap stored in an Object array. The root at index zero is always the smallest element according to natural order or the comparator, and for index i the children are at 2i plus 1 and 2i plus 2, so no pointers are needed.
Then, if they want more
When I offer an element, it goes into the first free slot to keep the tree complete and then sifts up, swapping with its parent while it is smaller, which takes at most log n steps. Poll takes the root, moves the last element to the top and sifts it down by comparing with the smaller child, also O(log n).
Peek just reads index zero, so it is O(1). The catch is that the heap has no index of positions, so contains and remove of a specific object have to scan the whole array, which is O(n); remove then repairs the heap in log n, but the scan dominates. That is a real problem in schedulers that cancel many items.
I also remember that iterating or printing the queue shows heap order, not sorted order, so to get sorted output I poll repeatedly. It is not thread safe and does not accept nulls.
For concurrent code I would use PriorityBlockingQueue, which wraps the same heap in a lock and adds blocking take, and DelayQueue builds on a priority queue to hand out elements only when their delay has expired.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "How is java.util.PriorityQueue implemented, and what are the costs of offer, poll, peek...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/7e903adefe/