Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Collections, From the Inside

    PriorityQueue, Inside Out

    A PriorityQueue<E> always gives you the smallest element first (by natural order or a comparator) — a min-heap by default.

    Chapter 9 of 117 min readOften asked in interviews

    The Plain Picture#

    A hospital emergency room. Patients aren't seen in arrival order — the most urgent is always seen next. When a new patient arrives, the nurse doesn't re-sort the whole waiting room; she only needs to know who's most urgent right now.

    The Real Names#

    • A PriorityQueue<E> always gives you the smallest element first (by natural order or a comparator) — a min-heap by default.

    • Inside is a binary heap stored in an array: a complete binary tree where every parent is ≤ its children. The smallest element is always at index 0.

    • Array positions: for the node at index i, its children are at 2i + 1 and 2i + 2, and its parent is at (i − 1) / 2 (integer division). No node objects, no references — just arithmetic on an array (Java Basics Ch 8).

    OperationCost
    peek()O(1) — it's at index 0
    offer(e)O(log n) — "sift up"
    poll()O(log n) — "sift down"
    remove(Object), containsO(n)
    building from a whole collectionO(n) ("heapify")

    Under the Hood — watching it work (real output)#

    Java
    PriorityQueue<Integer> pq = new PriorityQueue<>();
    
    for (int x : new int[] { 50, 20, 40, 10, 30 }) {
        pq.offer(x);
        System.out.println("offer " + x + " -> " + pq);
    }
    Output
    offer 50 -> [50]
    offer 20 -> [20, 50]
    offer 40 -> [20, 50, 40]
    offer 10 -> [10, 20, 40, 50]
    offer 30 -> [10, 20, 40, 50, 30]
    peek 10
    after poll -> [20, 30, 40, 50]

    (Printing a PriorityQueue shows its internal array — which is not sorted.)

    Sift up — offer 10 into [20, 50, 40]:

    Output
      put 10 at the end (index 3)        parent of 3 is (3−1)/2 = 1 → 50 > 10 → swap      parent of 1 is 0 → 20 > 10 → swap
              20                                  20                                             10
            /    \                              /    \                                         /    \
          50      40                          10      40                                     20      40
         /                                   /                                              /
       10                                  50                                             50
      [20, 50, 40, 10]                    [20, 10, 40, 50]                               [10, 20, 40, 50]  ✔

    At most one swap per level, and a complete binary tree of n nodes has about log n levels → O(log n).

    Sift down — poll() from [10, 20, 40, 50, 30]: remove the root (10), move the last element (30) to the root, then swap it with its smaller child while it's bigger than that child:

    Output
      [30, 20, 40, 50]  → children of 30 are 20 and 40; smaller is 20 < 30 → swap → [20, 30, 40, 50]
                        → children of 30 (index 1) are index 3 (50); 30 < 50 → stop                    ✔

    Max-heap: pass a reversed comparator.

    Java
    PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
    
    maxHeap.addAll(List.of(40, 10, 30));
    
    maxHeap.peek(); // 40

    The top-K pattern (Part 0's problem 6)#

    "The 3 highest scores" — keep a min-heap of size K. Its root is the smallest of the best K so far; anything smaller than it can't be in the top K.

    Java
    int[] all = { 72, 95, 60, 88, 100, 45, 99 };
    
    int k = 3;
    
    PriorityQueue<Integer> topK = new PriorityQueue<>(); // MIN-heap
    
    for (int x : all) {
        topK.offer(x);
        if (topK.size() > k) topK.poll(); // drop the smallest → keep only the best k
    }
    // top 3: [100, 99, 95]

    O(n log k) time and O(k) space — versus O(n log n) to sort everything. For a million scores and k = 10, log k ≈ 3 while log n ≈ 20, and you never hold more than 10 items. This pattern appears constantly: top-K frequent words, K closest points, K-th largest element (Heaps and Priority Queues (coming soon)).

    Heaps of arrays — the standard shape for Dijkstra's shortest path (Graphs II (coming soon)):

    Java
    PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0])); // [distance, node]
    
    pq.offer(new int[] { 7, 1 });
    
    pq.offer(new int[] { 2, 5 });
    
    pq.offer(new int[] { 4, 3 });
    
    int[] first = pq.poll(); // closest: dist=2 node=5

    Gotchas

    • Iterating a PriorityQueue (or printing it) is not in sorted order. Only repeated poll() gives sorted output.

    • Changing an element's priority after inserting it breaks the heap — remove it and re-insert, or insert a new entry and skip stale ones when polled (the usual trick in Dijkstra).

    • Min-heap for top-K largest, max-heap for top-K smallest — it feels backwards, so reason it out each time: the heap's root is the one you throw away.

    Check yourself

    4 questions
    1

    For the node at index 4 in a heap array, where are its parent and children?

    Show answer

    Parent (4−1)/2 = 1; children 9 and 10.

    2

    Why are offer and poll O(log n)?

    Show answer

    Each sifts an element up or down at most one level per step, and the heap has about log n levels.

    3

    Why use a min-heap of size k to find the k largest numbers? What's the complexity?

    Show answer

    The root is the smallest of the current best k, so anything smaller can be discarded; O(n log k) time, O(k) space.

    4

    Why doesn't printing a PriorityQueue show sorted order?

    Show answer

    It shows the internal array, which only guarantees each parent ≤ its children, not full sorting.