Stop 10 · Data Structures & Algorithms in JavaTopics · 9/11

Heaps

Part of the Java Roadmap

In short

Whenever a problem says 'top k', 'closest k', 'next most urgent' or 'merge k sorted lists', reach for a heap. In Java that means PriorityQueue.

A heap is a tree-shaped structure that always gives quick access to the smallest or largest item. In Java, PriorityQueue is a min-heap by default and solves top-K, merging and scheduling problems.

The jaadu, dressed as a nurse, waves the most urgent patient forward from a waiting room bench.

Think of it like this

The hospital triage desk

In a hospital emergency room, patients are not seen in arrival order. The triage nurse always calls the most serious case next, and a new arrival with chest pain jumps ahead of a sprained ankle. The nurse doesn't fully sort the room, she just always knows who is most urgent. That is a heap.

Watch it happen

Top 3 numbers with a min-heap of size 3

7
0
2
1
9
2
4
3
11
4
5
5

1/5We keep a min-heap that never holds more than three numbers.

The big ideas

What you need to know

Heap property

In a min-heap every parent is smaller than its children, so the minimum is always at the root.

Costs

peek is O(1). offer and poll are O(log n). Building a heap from n items is O(n).

Min or max

new PriorityQueue<>() is a min-heap. new PriorityQueue<>(Comparator.reverseOrder()) is a max-heap.

Top-k trick

For the k largest, keep a min-heap of size k and drop the smallest whenever it grows past k. O(n log k).

See it in code

Walk through the code

java
1import java.util.Comparator;2import java.util.PriorityQueue;3 4public class HeapDemo {5    record Task(String name, int priority) {}6 7    // k largest numbers using a min-heap of size k: O(n log k)8    static PriorityQueue<Integer> topK(int[] nums, int k) {9        PriorityQueue<Integer> heap = new PriorityQueue<>();10        for (int n : nums) {11            heap.offer(n);12            if (heap.size() > k) heap.poll();   // drop the smallest13        }14        return heap;15    }16 17    public static void main(String[] args) {18        System.out.println(topK(new int[] {7, 2, 9, 4, 11, 5}, 3)); // 7, 9, 11 in heap order19 20        PriorityQueue<Task> tasks = new PriorityQueue<>(21                Comparator.comparingInt(Task::priority));22        tasks.offer(new Task("Reply to client", 2));23        tasks.offer(new Task("Fix payment bug", 1));24        tasks.offer(new Task("Update README", 3));25        while (!tasks.isEmpty()) {26            System.out.println(tasks.poll().name()); // bug, then client, then README27        }28 29        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());30    }31}

1/4Push every number, but pop the smallest whenever the heap grows past k.

A top-k helper, a priority task list ordered by a comparator, and how to make a max-heap.

Save yourself the pain

Common mistakes

Oops

Printing or iterating a PriorityQueue and expecting sorted output.

Do this instead

Only the head is guaranteed. Call poll() repeatedly to get items in order.

Oops

Sorting the whole array to find the top 3 of a million numbers.

Do this instead

That is O(n log n). A size-3 heap does it in O(n log 3), close to O(n).

Your mission

Heap problems

~45 min

Quick check

What does new PriorityQueue<Integer>() return first from poll() after adding 5, 1 and 8?

Go deeper

  1. 1Find the K largest numbers in an array with a PriorityQueue.
  2. 2Turn PriorityQueue into a max-heap with Comparator.reverseOrder().
  3. 3Solve merge K sorted lists and explain its time complexity.

Also part of these roadmaps

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge