Heap / Priority Queue - Introduction

How a heap keeps the smallest or largest value on top, and how to use one in Java.

Picture a hospital waiting room. Patients arrive in any order, yet the next one called in is always the most urgent. A heap does that job for numbers: you keep adding values, and at any moment you can take out the smallest one (or the largest) without sorting everything. It fits problems that keep asking "which one is smallest right now?" while new values keep arriving.

One small heap is enough to see how it all works: it receives the five numbers 5, 3, 8, 1 and 4, in that order.

The min-heap after adding 5, 3, 8, 1 and 4: root 1 with children 3 and 8, and 3 with children 5 and 4. Below it, the same heap as the array [1, 3, 8, 5, 4] with indexes 0 to 4.

The heap rule: smallest on top

Look at the picture above. It is the heap you get after adding 5, 3, 8, 1 and 4. Each circle holds one value, and a line joins a value to the one or two values hanging under it. The circle at the top, holding 1, is the root. The two circles under it, 3 and 8, are its children, and 1 is their parent. Under 3 hang two more children, 5 and 4.

Now compare each parent with its children. 1 is smaller than 3 and 8, and 3 is smaller than 5 and 4. That is the whole rule: every parent is less than or equal to its children. A heap that keeps this rule is a min-heap, and the rule pushes the smallest value up to the root, labelled "the top: the smallest value".

Notice what the rule leaves out. 8 sits higher than 5 and 4 although it is bigger, because 8 is not their parent. The heap is not a sorted list; it only promises the top.

Turn the rule around, so every parent is at least as big as its children, and you get a max-heap, with the largest value on top.

Why not keep a list?

A plain list could hold the five numbers too, but it is slow at one of the two jobs. Unsorted, adding is quick, yet finding the smallest means looking at all n values, so each removal costs O(n). Sorted, the smallest waits at the front, but adding is slow. When 1 arrives, the list is [3, 5, 8], and all three values shift right to make room. In the worst case every value shifts, so each add costs O(n).

A heap does both jobs in O(log n). The tree in the picture has three levels for five values, and adding or removing moves one value along a single path between top and bottom. A tree of this shape holding 1,000 values has only 10 levels.

A tree stored in an array

How does a program store the tree? Look at the row labelled "the same heap stored in an array" in the picture. Reading the tree level by level, left to right, gives [1, 3, 8, 5, 4]. The tree has no gaps: every level is full except the last, which fills from the left. A tree with that shape is called a complete binary tree, and the shape is what lets a heap live in a plain array with no links between values.

The positions follow a pattern. The value at index i has its children at indexes 2i + 1 and 2i + 2, and its parent at (i - 1) / 2, rounded down. Check it on the picture. 3 is at index 1, so its children are at indexes 3 and 4, which hold 5 and 4. Going back up, the parent of index 4 is (4 - 1) / 2 = 1, which is 3 again.

Adding a value: sift up

How does 1 reach the top when it arrives fourth? Just before it arrives, the heap holds [3, 5, 8]. Look at the left panel of the picture below, "1 goes into the first free slot". A new value always goes at the end of the array, here index 3, which in the tree is the left child of 5.

Sift up in three panels. 1 goes into the first free slot under 5, giving [3, 5, 8, 1]. After the first swap with its parent 5: [3, 1, 8, 5]. After the second swap with its parent 3: [1, 3, 8, 5], and 1 is at the top.

That breaks the rule, because the parent 5 is bigger than its child 1. So the two swap places, and the middle panel, "after the first swap", shows [3, 1, 8, 5]. The new parent of 1 is 3, still bigger, so they swap again. In the right panel, "after the second swap", 1 has reached index 0 with nothing above it, so it stops.

Moving a new value up, swapping it with its parent until the parent is no bigger, is called sifting up. An add never makes more swaps than the tree has levels. When 4 arrives next, it lands at index 4 under 3, which is smaller, so 4 stays where it is with no swap at all.

Removing the top: sift down

Taking the smallest value out leaves a hole at the root. Which value should fill it? Removing the top is usually called poll. Look at the left panel of the picture below, "poll takes 1 off the top", where the heap is [1, 3, 8, 5, 4].

Sift down in three panels. Poll takes 1 off the top of [1, 3, 8, 5, 4], and the last value 4 is marked to move up. 4 moves to the top: [4, 3, 8, 5]. After the swap with its smaller child 3: [3, 4, 8, 5], and 4 is smaller than its child 5, so it stops.

The last value in the array, the teal 4, moves into the hole. Taking it from the end keeps the tree complete, with no gap in the middle. In the middle panel, "4 moves to the top", the array is [4, 3, 8, 5], and the rule is broken: 4 is bigger than its child 3.

So 4 swaps with its smaller child, 3. It must be the smaller one. Had 4 swapped with 8, then 8 would sit above 3, and the rule would be broken at the root instead.

In the right panel, "after the swap", 4 is at index 1 with one child, 5. Since 4 is smaller than 5, it stops. The heap is [3, 4, 8, 5], with the new smallest value, 3, on top. Moving a value down this way is called sifting down, and it also makes at most one swap per level.

Min-heap or max-heap with PriorityQueue

Java code seldom needs a heap written by hand. The class java.util.PriorityQueue is a ready-made heap. It names the operations offer (add a value), poll (remove the top) and peek (read the top without removing it).

Which way round does it order things? A PriorityQueue built with no arguments is a min-heap. For a max-heap, give the constructor a Comparator, which tells the heap which of two numbers belongs nearer the top. Comparator.reverseOrder() puts larger values first:

Java
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());

Given 5, 3, 8, 1 and 4, minHeap.peek() returns 1 and maxHeap.peek() returns 8.

When the values are arrays or objects, the comparator says which part to compare. Points stored as {x, y} pairs and ordered by x need this one, where Integer.compare(a[0], b[0]) is negative when point a has the smaller x:

Java
PriorityQueue<int[]> byX = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));

Keeping only the k largest

Suppose you want the k largest of many values, without sorting them all. Which heap fits? Perhaps surprisingly, a min-heap. Keep at most k values in it. Each new value goes in, and if the heap now holds k + 1 values, poll throws out the smallest. The values left at the end are the k largest, and the top of the heap is the kth largest.

Follow it on the five numbers with k = 2. After 5 and 3, the heap holds 3 and 5. When 8 arrives it holds three values, so poll drops 3, leaving 5 and 8. Then 1 and 4 each go in and come straight back out, because each is the smallest of the three. The heap ends with 5 and 8, and its top, 5, is the second largest.

The heap never holds more than k + 1 values, so each step costs O(log k) rather than O(log n).

A complete program

The program below has the hand-written heap from the pictures, then sends the same five numbers through PriorityQueue as a min-heap, as a max-heap and as a top-2 heap. Its parts:

  • The class IntMinHeap: the values in an array data, with size counting the filled slots. Its offer writes at data[size] and calls siftUp; its poll moves the last value to data[0] and calls siftDown, which swaps with the smaller child.
  • Its peek throws NoSuchElementException on an empty heap, and poll calls peek first. When data is full, offer doubles it with Arrays.copyOf.
  • The method largestK: the top-k heap, printing what it keeps after each value.
  • The helper drain: polls a PriorityQueue until it is empty and lists the values in the order they came out.

Besides the five numbers, main tries duplicates, an empty heap and 1,000 random values from a fixed seed, enough to make the 16-slot array grow several times.

Java
import java.util.*;

public class HeapIntro {

    // A min-heap of ints stored in an array: the children of index i are 2i + 1 and 2i + 2.
    static class IntMinHeap {
        private int[] data = new int[16];
        private int size = 0;

        void offer(int x) {
            if (size == data.length) data = Arrays.copyOf(data, size * 2);
            data[size] = x;  // put the new value in the first free slot
            siftUp(size++);  // then move it up while it is smaller than its parent
        }

        int peek() {
            if (size == 0) throw new NoSuchElementException("heap is empty");
            return data[0];
        }

        int poll() {
            int top = peek();
            data[0] = data[--size]; // move the last value to the root
            siftDown(0);            // then move it down while a child is smaller
            return top;
        }

        int size() { return size; }

        private void siftUp(int i) {
            while (i > 0) {
                int parent = (i - 1) / 2;
                if (data[parent] <= data[i]) break;
                swap(i, parent);
                i = parent;
            }
        }

        private void siftDown(int i) {
            while (true) {
                int left = 2 * i + 1, right = left + 1, smallest = i;
                if (left < size && data[left] < data[smallest]) smallest = left;
                if (right < size && data[right] < data[smallest]) smallest = right;
                if (smallest == i) return;
                swap(i, smallest);
                i = smallest;
            }
        }

        private void swap(int i, int j) {
            int t = data[i];
            data[i] = data[j];
            data[j] = t;
        }

        public String toString() {
            return Arrays.toString(Arrays.copyOf(data, size));
        }
    }

    // Keeps the k largest values seen: a min-heap that drops its smallest once it holds k + 1.
    static List<Integer> largestK(int[] values, int k) {
        PriorityQueue<Integer> kept = new PriorityQueue<>();
        for (int v : values) {
            kept.offer(v);
            if (kept.size() > k) kept.poll();
            System.out.println("  after " + v + " the heap keeps " + kept);
        }
        List<Integer> result = new ArrayList<>();
        while (!kept.isEmpty()) result.add(kept.poll());
        return result;
    }

    static List<Integer> drain(PriorityQueue<Integer> pq) {
        List<Integer> out = new ArrayList<>();
        while (!pq.isEmpty()) out.add(pq.poll());
        return out;
    }

    public static void main(String[] args) {
        int[] values = {5, 3, 8, 1, 4};

        IntMinHeap heap = new IntMinHeap();
        for (int v : values) {
            heap.offer(v);
            System.out.println("offer " + v + " -> " + heap);
        }
        System.out.println("poll returns " + heap.poll() + " -> " + heap);
        List<Integer> rest = new ArrayList<>();
        while (heap.size() > 0) rest.add(heap.poll());
        System.out.println("then poll gives " + rest);

        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
        for (int v : values) {
            minHeap.offer(v);
            maxHeap.offer(v);
        }
        System.out.println("min-heap peek " + minHeap.peek() + ", order " + drain(minHeap));
        System.out.println("max-heap peek " + maxHeap.peek() + ", order " + drain(maxHeap));

        System.out.println("2 largest: " + largestK(values, 2));

        // Edge cases: duplicates, an empty heap, and growing past 16 slots.
        IntMinHeap dup = new IntMinHeap();
        for (int v : new int[] {2, 2, 1, 2}) dup.offer(v);
        List<Integer> dupOrder = new ArrayList<>();
        while (dup.size() > 0) dupOrder.add(dup.poll());
        System.out.println("duplicates: " + dupOrder);

        try {
            new IntMinHeap().peek();
        } catch (NoSuchElementException e) {
            System.out.println("empty heap: " + e.getMessage());
        }

        IntMinHeap big = new IntMinHeap();
        Random random = new Random(42);
        for (int i = 0; i < 1000; i++) big.offer(random.nextInt(1000000));
        int previous = Integer.MIN_VALUE;
        boolean sorted = true;
        while (big.size() > 0) {
            int next = big.poll();
            if (next < previous) sorted = false;
            previous = next;
        }
        System.out.println("1000 random values come out sorted: " + sorted);
    }
}

Running it prints:

Output
offer 5 -> [5]
offer 3 -> [3, 5]
offer 8 -> [3, 5, 8]
offer 1 -> [1, 3, 8, 5]
offer 4 -> [1, 3, 8, 5, 4]
poll returns 1 -> [3, 4, 8, 5]
then poll gives [3, 4, 5, 8]
min-heap peek 1, order [1, 3, 4, 5, 8]
max-heap peek 8, order [8, 5, 4, 3, 1]
  after 5 the heap keeps [5]
  after 3 the heap keeps [3, 5]
  after 8 the heap keeps [5, 8]
  after 1 the heap keeps [5, 8]
  after 4 the heap keeps [5, 8]
2 largest: [5, 8]
duplicates: [1, 2, 2, 2]
empty heap: heap is empty
1000 random values come out sorted: true

The first five lines replay the pictures. After offer 1 the array is [1, 3, 8, 5], the right panel of the sift-up picture, and offer 4 leaves [1, 3, 8, 5, 4], the array in the first picture. The line poll returns 1 -> [3, 4, 8, 5] is the last panel of the sift-down picture.

Look at the line then poll gives [3, 4, 5, 8]. The array was never sorted, yet polling one value at a time hands the numbers back smallest first. In the two PriorityQueue lines, the min-heap peeks 1, the max-heap peeks 8, and draining them gives opposite orders.

The lines that start with "after" trace the top-2 heap, which holds [5, 8] from the arrival of 8 onward, and 2 largest: [5, 8] is its result. In the last three lines, the values 2, 2, 1, 2 come out as [1, 2, 2, 2], so equal values are no problem. Calling peek on an empty heap throws with the message "heap is empty", and the 1,000 random values all come out in order.

What each operation costs

Every cost comes back to the height of the tree. A complete tree of n values has about log2 n levels, because each level holds twice as many values as the one above it.

  • Reading the top with peek: O(1), because the smallest value always sits at index 0, so reading it needs no search.
  • Adding with offer: O(log n), because sifting up climbs one level per swap and stops at the root at the latest. The occasional doubling of the array adds O(1) per add on average.
  • Removing the top with poll: O(log n), because sifting down drops one level per swap, comparing two children at each level.
  • Finding or removing any other value: O(n), because values side by side are in no order, so the heap has to scan its array. The PriorityQueue documentation lists these same costs.
  • Space: O(n), because the heap is one array of the n values, and doubling keeps the array less than twice as long as needed once it has grown past 16 slots.

Adding n values and polling all of them costs O(n log n), and it returns them sorted, as the 1,000-value line shows. The same idea, done inside the input array, is the sorting method called heap sort.

Traps to watch for

Three mistakes with PriorityQueue are easy to make. This short program shows each one:

Java
import java.util.*;

public class HeapTraps {
    public static void main(String[] args) {
        // Trap 1: printing or looping over a PriorityQueue shows the array, not sorted order.
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        for (int v : new int[] {5, 3, 8, 1, 4}) pq.offer(v);
        System.out.println("printed: " + pq);

        // Trap 2: a comparator written as a - b overflows for far-apart values.
        int[] values = {5, Integer.MIN_VALUE, 3};
        PriorityQueue<Integer> bySubtraction = new PriorityQueue<>((a, b) -> a - b);
        PriorityQueue<Integer> byCompare = new PriorityQueue<>((a, b) -> Integer.compare(a, b));
        for (int v : values) {
            bySubtraction.offer(v);
            byCompare.offer(v);
        }
        System.out.println("a - b peek: " + bySubtraction.peek());
        System.out.println("Integer.compare peek: " + byCompare.peek());

        // Trap 3: poll on an empty queue returns null, and unboxing null throws.
        PriorityQueue<Integer> empty = new PriorityQueue<>();
        System.out.println("poll on empty: " + empty.poll());
        try {
            int x = empty.poll();
            System.out.println(x);
        } catch (NullPointerException e) {
            System.out.println("int x = empty.poll() throws NullPointerException");
        }
    }
}

Running it prints:

Output
printed: [1, 3, 8, 5, 4]
a - b peek: 3
Integer.compare peek: -2147483648
poll on empty: null
int x = empty.poll() throws NullPointerException

Look at the first line, printed: [1, 3, 8, 5, 4]. Printing a PriorityQueue shows its array, the same one as in the first picture, not the values in sorted order. Its documentation says a loop over it is not in any particular order either. To get the values in order, poll them one by one.

The next two lines come from the same three values, 5, the smallest int (-2,147,483,648) and 3. The comparator a - b says 3 is the smallest, which is wrong. It computes 3 minus -2,147,483,648, and the true answer, 2,147,483,651, does not fit in an int, so it wraps around to a negative number. The comparator then reads 3 as coming first. Integer.compare gets it right, and its heap peeks the smallest int.

The last two lines show that poll on an empty PriorityQueue returns null instead of throwing, unlike IntMinHeap. Storing that null in an int throws NullPointerException, so check isEmpty() before polling.

Spotting a heap problem

How do you tell that a problem wants a heap? These are the usual signs:

  • Values keep arriving, and you keep needing the smallest or largest one so far.
  • The problem asks for the k largest, the k closest or the kth smallest. A heap capped at k values, like the top-2 heap above, keeps just those.
  • Several lists are each sorted and must be merged. Put the front value of each list in a min-heap; its top is the next value overall.
  • The problem asks for a running median. Two heaps split the values: a max-heap for the smaller half and a min-heap for the larger half, so both middle values sit on top.
  • You take items as they come and sometimes have to give one back. A heap of the items taken so far keeps the worst one on top, ready to drop.

A heap is not needed when you want the smallest value only once (one scan is enough), or when all values are known up front and never change (sort them once).

Where to go next

A heap capped at k values

Taking the top again and again

  • Last Stone Weight polls the two heaviest stones from a max-heap and puts back what is left.
  • Reorganize String keeps letter counts in a max-heap and writes the two letters with the most copies left in each round.

Two heaps

Merging and greedy choices

  • Merge K Sorted Lists keeps the front node of each list in a min-heap.
  • IPO sorts projects by the capital they need and pushes the profit of each one it can afford into a max-heap, then takes the biggest.
  • Course Schedule III takes courses in order of last day and, when the plan runs late, drops the longest one from a max-heap of durations.