PriorityQueue in Java

Learn how Java's PriorityQueue works as a min-heap, its time complexities, custom ordering, common pitfalls, and classic interview patterns.

PriorityQueue<E> is a queue implementation that orders elements by priority rather than by insertion order. It is backed by a binary min-heap: the element with the smallest value (according to natural ordering or a provided Comparator) is always at the head and is returned first by poll(). PriorityQueue is indispensable for algorithms such as Dijkstra's shortest path, A*, merge of sorted lists, and any problem that repeatedly needs the current minimum or maximum.

Internal Structure: Binary Min-Heap

A binary heap stores elements in a flat array such that for any element at index i, its children are at indices 2i+1 and 2i+2, and its parent is at (i-1)/2. PriorityQueue maintains the heap property: every parent is less than or equal to both its children (min-heap). When an element is added or removed, the heap re-establishes this property by "sifting up" or "sifting down".

Time Complexities

Operation Complexity Notes
offer(e) / add(e) O(log n) Sift up to restore heap property
poll() O(log n) Remove root, sift down last element
peek() O(1) Root is always the minimum
contains(o) O(n) Linear scan — heap is not sorted
remove(o) O(n) Linear scan + O(log n) sift
size() O(1) Field read

Important: PriorityQueue is not sorted when iterated. Iteration order is unspecified (it reflects the heap's internal array layout). To drain elements in priority order, use repeated poll() calls.

Natural Ordering vs. Custom Comparator

By default, PriorityQueue uses natural ordering (Comparable). To create a max-heap or custom ordering, pass a Comparator to the constructor.

// Min-heap (default): smallest number at the top
PriorityQueue<Integer> minHeap = new PriorityQueue<>();

// Max-heap: largest number at the top
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());

// Custom: sort strings by length, then alphabetically
PriorityQueue<String> byLength = new PriorityQueue<>(
    Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder())
);

Example 1: Basic PriorityQueue Operations

import java.util.PriorityQueue;

public class PQBasics {
    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();

        pq.offer(5);
        pq.offer(1);
        pq.offer(3);
        pq.offer(2);
        pq.offer(4);

        System.out.println("Peek (min): " + pq.peek()); // 1

        // Poll always removes the current minimum
        while (!pq.isEmpty()) {
            System.out.print(pq.poll() + " "); // 1 2 3 4 5 (sorted by poll)
        }
        System.out.println();

        // Max-heap using reverseOrder
        PriorityQueue<Integer> maxPQ = new PriorityQueue<>(java.util.Collections.reverseOrder());
        maxPQ.offer(5);
        maxPQ.offer(1);
        maxPQ.offer(3);
        System.out.println("Max-heap peek: " + maxPQ.peek()); // 5
    }
}

Example 2: Top-K Elements and Dijkstra's Pattern

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;

public class PQPatterns {

    // Find the k largest elements using a min-heap of size k
    public static int[] topKLargest(int[] nums, int k) {
        PriorityQueue<Integer> minHeap = new PriorityQueue<>(k);
        for (int n : nums) {
            minHeap.offer(n);
            if (minHeap.size() > k) {
                minHeap.poll(); // remove the smallest element
            }
        }
        // minHeap now contains the k largest elements
        return minHeap.stream().mapToInt(Integer::intValue).toArray();
    }

    // Merge k sorted lists into one sorted list
    public static List<Integer> mergeKSorted(List<List<Integer>> lists) {
        // Each entry: [value, listIndex, elementIndex]
        PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
        for (int i = 0; i < lists.size(); i++) {
            if (!lists.get(i).isEmpty()) {
                pq.offer(new int[]{lists.get(i).get(0), i, 0});
            }
        }
        List<Integer> result = new java.util.ArrayList<>();
        while (!pq.isEmpty()) {
            int[] top = pq.poll();
            result.add(top[0]);
            int li = top[1], ei = top[2] + 1;
            if (ei < lists.get(li).size()) {
                pq.offer(new int[]{lists.get(li).get(ei), li, ei});
            }
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(topKLargest(new int[]{3,1,5,12,2,11}, 3)));
        // [5, 11, 12] (order within top-k may vary)

        List<List<Integer>> sorted = List.of(
            List.of(1, 4, 7),
            List.of(2, 5, 8),
            List.of(3, 6, 9)
        );
        System.out.println(mergeKSorted(sorted)); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
    }
}

Common Mistakes

  • Assuming iteration is in sorted order. Iterating over a PriorityQueue with for-each does NOT yield elements in priority order. Use repeated poll() calls to drain elements in order.
  • Using PriorityQueue where FIFO ordering is needed. PriorityQueue is not a FIFO queue. If you need insertion-order processing, use ArrayDeque.
  • Modifying an element already in the queue. PriorityQueue does not automatically re-heapify when you mutate an object that is already stored. You must remove the element, mutate it, and re-offer it to maintain the heap property.
  • Adding null to PriorityQueue. null is not allowed; offer(null) throws NullPointerException. Unlike ArrayList and LinkedList, PriorityQueue requires all elements to be comparable.
  • Confusing min-heap and max-heap. By default, PriorityQueue is a min-heap. To get a max-heap, pass Comparator.reverseOrder() to the constructor. Forgetting this and calling poll() to get the maximum will instead return the minimum.

Best Practices

  • When building a max-heap, use new PriorityQueue<>(Comparator.reverseOrder()) rather than negating values — it is clearer and works for any comparable type.
  • Pre-size the PriorityQueue with new PriorityQueue<>(initialCapacity) when you have a good estimate of the final size.
  • For the "top-K" pattern, use a min-heap of size K: keep only the K largest by evicting the current minimum when size exceeds K.
  • To drain a PriorityQueue in sorted order without destroying it, copy it first: new PriorityQueue<>(original) creates a new heap with the same elements.
  • Use PriorityQueue in algorithm problems involving greedy strategies, Dijkstra's algorithm, Huffman encoding, and scheduling.

Interview Questions

1. How does PriorityQueue work internally?

PriorityQueue is backed by a binary min-heap stored as a flat array. The smallest element is always at index 0 (the root). offer appends to the end and sifts up in O(log n); poll removes the root, moves the last element to the root, and sifts down in O(log n). peek reads the root in O(1).

2. What is the iteration order of PriorityQueue?

Iteration order (via for-each or iterator) is not sorted order. It reflects the heap's internal array layout, which does not guarantee any particular sequence. To iterate in priority order, you must repeatedly call poll() until the queue is empty.

3. How do you create a max-heap in Java?

Pass Comparator.reverseOrder() to the constructor: new PriorityQueue<>(Comparator.reverseOrder()). For custom objects, use a lambda or method reference that reverses the comparison: new PriorityQueue<>((a, b) -> b.compareTo(a)) or Comparator.comparingInt(MyClass::getValue).reversed().

4. What is the time complexity of contains on a PriorityQueue?

O(n). The heap structure does not support efficient search; contains must scan the underlying array linearly. If you need O(1) membership testing, maintain a separate HashSet in parallel with the PriorityQueue.

5. How would you find the k-th largest element using a PriorityQueue?

Use a min-heap of size k. Iterate through all elements; for each one, offer it to the heap. If the heap size exceeds k, poll the minimum. After processing all elements, peek returns the k-th largest. Time: O(n log k); Space: O(k).

6. What happens if you add non-Comparable objects to a PriorityQueue without a Comparator?

PriorityQueue uses natural ordering by default. If the element type does not implement Comparable and no Comparator was supplied, the offer/add call throws ClassCastException when the heap tries to compare the new element to existing ones.

7. Is PriorityQueue thread-safe?

No. PriorityQueue is not synchronised. For thread-safe priority queuing, use PriorityBlockingQueue from java.util.concurrent, which provides blocking put/take semantics and is fully thread-safe.

Summary

  • PriorityQueue is a min-heap; peek and poll always operate on the smallest element.
  • offer/poll are O(log n); peek is O(1); contains is O(n).
  • Iteration order is NOT sorted — drain with repeated poll() for sorted output.
  • Use Comparator.reverseOrder() for a max-heap.
  • Top-K and merge-K-sorted-lists are classic PriorityQueue interview patterns.

Continue Learning

Previous: Deque | Next: Set

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.