Some problems keep asking the same question: what is the smallest (or largest) thing I have right now? The next job to run, the cheapest edge to take, the ten best scores out of a million, the median of numbers that are still arriving. Sorting everything again after each change answers it, but wastes almost all of the work. A heap answers it in constant time and repairs itself in logarithmic time, and in Java you already have one: java.util.PriorityQueue.
This article builds a heap in Java from a plain array, then moves to PriorityQueue in Java with comparators and its traps, then heap sort, then ten interview problems including top K elements, K-th largest, merge K sorted lists, running median and task scheduler. Every problem is checked against a slow brute-force answer on random input, and every console block below is copied from a file that a test wrote.
Versions. Compiled and run on Temurin JDK 25.0.5.1+2 (LTS) with JUnit 6.1.3. Code: java-interview-lab/heap (17 tests; ./scripts/run-all.sh regenerates every output file). Numbers of comparisons are exact for the stated seeds. They are not timings, and nothing in this article is a benchmark.
A heap in Java is a tree with one rule, stored in a plain array
A min-heap is a binary tree that obeys one rule: no child is smaller than its parent. That is all. Siblings are in no particular order, and the left side is not smaller than the right side (that would be a binary search tree, a different thing). The rule has one useful consequence: the smallest value is always at the root.
A heap also has a shape rule: the tree is complete, meaning every level is full except possibly the last, which fills from the left. A complete tree can be written level by level into an array with no gaps, so we never need node objects.
The picture below shows the same six numbers both ways. Follow the amber node at index 1: its children sit at indexes 3 and 4, and the arithmetic on the right finds them without any stored links.
Do not confuse the two heaps. The JVM memory area called “the heap” (where objects live) has nothing to do with this data structure. They share only a name.
Why (i – 1) / 2 gives the parent of both children
The children of i are 2i+1 and 2i+2. Subtract 1 and you get 2i and 2i+1; integer division by 2 maps both back to i. The same formulas appear in the JDK: the field comment in java.util.PriorityQueue says the two children of queue[n] are queue[2*n+1] and queue[2*(n+1)]. If you prefer a 1-based array (common in textbooks), the formulas become i/2, 2i and 2i+1. Mixing the two conventions is the most common bug in a hand-written heap.
Going deeper
- Source of the int heap built in the next two sections: IntMinHeap.java
- Binary tree traversals in Java: level order is exactly the order in which a heap is stored
- Java Collections Framework: choosing the right data structure
offer(): put the value at the end and let it climb (sift up)
To insert, write the new value into the next free array slot. The shape rule still holds, but the new value may be smaller than its parent. So compare it with the parent and swap while the parent is larger. This is called sift up (also bubble up or swim).
Here is what happens when 5 arrives in a heap that already holds 10, 20, 50, 35 and 40. Two swaps carry it from the last slot to the root.
From IntMinHeap.java:
public void offer(int value) {
if (size == a.length) a = Arrays.copyOf(a, size * 2);
a[size] = value; // 1. put it in the next free slot (keeps the tree complete)
siftUp(size++); // 2. let it climb until its parent is not larger
}
private void siftUp(int i) {
while (i > 0) {
int parent = (i - 1) / 2;
if (a[parent] <= a[i]) return;
swap(i, parent);
i = parent;
}
}
HeapDryRun.java runs the same steps and writes down every comparison. This is the dry run for offering 35, 20, 50, 10, 40, 5, which is worth reproducing on paper once before an exam:
Real output (output/01-dry-run-sift-up.txt):
offer(35) placed at index 0 [35]
reached the root [35]
offer(20) placed at index 1 [35, 20]
parent a[0]=35 > 20 swap 1 <-> 0
reached the root [20, 35]
offer(50) placed at index 2 [20, 35, 50]
parent a[0]=20 <= 50 stop
offer(10) placed at index 3 [20, 35, 50, 10]
parent a[1]=35 > 10 swap 3 <-> 1
parent a[0]=20 > 10 swap 1 <-> 0
reached the root [10, 20, 50, 35]
offer(40) placed at index 4 [10, 20, 50, 35, 40]
parent a[1]=20 <= 40 stop
offer(5) placed at index 5 [10, 20, 50, 35, 40, 5]
parent a[2]=50 > 5 swap 5 <-> 2
parent a[0]=10 > 5 swap 2 <-> 0
reached the root [5, 20, 10, 35, 40, 50]
final array : [5, 20, 10, 35, 40, 50]
java.util.PriorityQueue shows: [5, 20, 10, 35, 40, 50]
The last two lines of that file matter: after the same six calls, PriorityQueue.toString() shows the identical array. This was not a coincidence of one input. A test ran 100,000 random offer/poll operations and compared the backing arrays of the int heap, a generic heap and the JDK class after every single one:
The comparison (output/03-same-array-as-jdk.txt):
random offer/poll operations compared : 100000
backing array identical after every one: IntMinHeap, BinaryHeap and PriorityQueue
bottom-up builds compared : 500
BinaryHeap.heapify(list) and new PriorityQueue<>(list) produced the same array every time
How the JDK writes the same loop (and when its array grows)
The JDK does not swap. It holds the new element aside, moves larger parents down into the hole, and writes the element once at the end. The result is the same array with fewer writes. These lines are read from the lib/src.zip of the JDK used here:
From the JDK source (output/23-jdk-source.txt):
291 private void grow(int minCapacity) {
292 int oldCapacity = queue.length;
293 // Double size if small; else grow by 50%
294 int newCapacity = ArraysSupport.newLength(oldCapacity,
295 minCapacity - oldCapacity, /* minimum growth */
296 oldCapacity < 64 ? oldCapacity + 2 : oldCapacity >> 1
297 /* preferred growth */);
298 queue = Arrays.copyOf(queue, newCapacity);
299 }
323 public boolean offer(E e) {
324 if (e == null)
325 throw new NullPointerException();
326 modCount++;
327 int i = size;
328 if (i >= queue.length)
329 grow(i + 1);
330 siftUp(i, e);
331 size = i + 1;
332 return true;
333 }
642 private static <T> void siftUpComparable(int k, T x, Object[] es) {
643 Comparable<? super T> key = (Comparable<? super T>) x;
644 while (k > 0) {
645 int parent = (k - 1) >>> 1;
646 Object e = es[parent];
647 if (key.compareTo((T) e) >= 0)
648 break;
649 es[k] = e;
650 k = parent;
651 }
652 es[k] = key;
653 }
725 private void heapify() {
726 final Object[] es = queue;
727 int n = size, i = (n >>> 1) - 1;
728 final Comparator<? super E> cmp;
729 if ((cmp = comparator) == null)
730 for (; i >= 0; i--)
731 siftDownComparable(i, (E) es[i], es, n);
732 else
733 for (; i >= 0; i--)
734 siftDownUsingComparator(i, (E) es[i], es, n, cmp);
735 }
The array starts at capacity 11. When it is full it roughly doubles while it is small (below 64) and grows by half after that. The Javadoc says the growth policy is unspecified, so do not depend on it; if you know the final size, pass it to the constructor.
Going deeper
- Test that writes both transcripts: HeapBasicsTest.java
- PriorityQueue Javadoc, JDK 25
poll(): take the root, move the last value up, let it sink (sift down)
Removing the minimum would leave a hole at the root. Filling it with a child just moves the hole around. The trick is to take the last element of the array, put it in the root, and push it down: compare it with the smaller of its two children and swap while that child is smaller. This is sift down.
The figure shows the first poll() on our heap. Note which child wins the swap.
From IntMinHeap.java:
public int poll() {
int min = peek();
a[0] = a[--size]; // 1. move the last value into the root
siftDown(0); // 2. let it sink below any smaller child
return min;
}
private void siftDown(int i) {
while (true) {
int left = 2 * i + 1;
if (left >= size) return; // a leaf: nowhere to go
int child = left;
int right = left + 1;
if (right < size && a[right] < a[left]) child = right; // the SMALLER child
if (a[i] <= a[child]) return;
swap(i, child);
i = child;
}
}
Two removals, step by step (output/02-dry-run-sift-down.txt):
poll() returns 5; last value moved to root [50, 20, 10, 35, 40]
smaller child a[2]=10 < 50 swap 0 <-> 2
reached a leaf [10, 20, 50, 35, 40]
poll() returns 10; last value moved to root [40, 20, 50, 35]
smaller child a[1]=20 < 40 swap 0 <-> 1
smaller child a[3]=35 < 40 swap 1 <-> 3
reached a leaf [20, 35, 50, 40]
final array : [20, 35, 50, 40]
java.util.PriorityQueue shows: [20, 35, 50, 40]
Both loops walk one root-to-leaf path, so both cost O(log n). peek() only reads index 0. Searching for an arbitrary value is different: the heap rule says nothing about left versus right, so every element may have to be checked. On a queue of a million elements the difference looks like this:
Method calls counted (output/05-operation-costs.txt):
call compareTo equals
peek() 0 0
offer(new smallest) 19 0
poll() 37 0
contains(absent) 0 1,000,000
remove(absent) 0 1,000,000
So a heap is not a fast general-purpose set. If you need contains often, keep a HashSet beside it, or use a TreeSet.
Removing from the middle: remove(Object)
The JDK finds the element with a linear scan, moves the last element into that position, sifts it down, and if it did not move, sifts it up. That repair is O(log n); finding the element is the O(n) part. Calling remove(x) inside a loop over many items quietly makes an algorithm quadratic. The usual alternative is lazy deletion: leave the stale entry in the queue and skip it when it reaches the head. The Dijkstra article does exactly that.
Going deeper
- Dry-run recorder: HeapDryRun.java
- Top 40 Java Collections interview questions
Max-heap in Java, and building a heap from existing data in O(n)
A max-heap flips the rule: no child is larger than its parent. Do not write the code twice. Write it once against a Comparator, and a max-heap is the same class given Comparator.reverseOrder().
When the data already exists, there is a better method than n calls to offer: copy it into the array as it is, then sift down every non-leaf, starting from the last parent and ending at the root. This is bottom-up construction, often credited to Floyd.
From BinaryHeap.java:
/** Bottom-up build (Floyd): O(n), unlike n separate offers which are O(n log n) in the worst case. */
public static <E> BinaryHeap<E> heapify(Collection<? extends E> items, Comparator<? super E> cmp) {
BinaryHeap<E> h = new BinaryHeap<>(cmp);
h.a.addAll(items);
for (int i = h.a.size() / 2 - 1; i >= 0; i--) h.siftDown(i); // from the last parent back to the root
return h;
}
private void siftDown(int i) {
int n = a.size();
E x = a.get(i);
while (2 * i + 1 < n) {
int child = 2 * i + 1;
if (child + 1 < n && cmp.compare(a.get(child + 1), a.get(child)) < 0) child++;
if (cmp.compare(x, a.get(child)) <= 0) break;
a.set(i, a.get(child)); // move the smaller child up into the hole
i = child;
}
a.set(i, x);
}
The next figure is the whole argument for why it is linear: the many nodes near the bottom have almost nowhere to sink, and only the single root can travel the full height.
Measured on a million keys, the gap depends entirely on the input order. Descending input is the worst case for repeated offer into a min-heap, because every new key climbs to the root:
Comparisons counted (output/04-heapify-vs-offer.txt):
input my offer() x n my heapify PriorityQueue.addAll new PriorityQueue(list)
random 2,279,262 1,881,044 2,279,262 1,881,044
ascending 999,999 999,999 999,999 999,999
descending 17,951,445 1,999,974 17,951,445 1,999,974
An easy win that is easy to miss.new PriorityQueue<>(list)heapifies (O(n));queue.addAll(list)is n separate insertions. On descending input that is about 9 times the comparisons. On random input the difference is small (about 21% more), so do not expect a miracle.
The catch: the collection constructor takes no comparator. For a plain list it uses natural ordering. A(Collection, Comparator)constructor has been proposed as JDK-8336686, which was unresolved when checked for this article, and it does not exist in JDK 25.
The O(n) proof in four lines
In a heap of n nodes about n/2 are leaves (sink 0 levels), n/4 sit one level up (at most 1), n/8 two levels up (at most 2), and so on. The total is at most n × (1/4 + 2/8 + 3/16 + …) = n × 1. Each level of sinking costs two comparisons (pick the smaller child, then compare with it), so under 2n comparisons. The descending row above, 1,999,974 for n = 1,000,000, sits right at that bound.
Going deeper
- Generic heap: BinaryHeap.java
- NIST DADS: heapsort, with the 1964 Williams and Floyd references
java.util.PriorityQueue in Java: a min-heap unless you say otherwise
In real code, use the JDK class. It is a binary heap on an array, ordered by natural ordering or by the comparator you pass. The head (what peek and poll return) is the least element, so numbers come out smallest first. For a max-heap pass Collections.reverseOrder().
| Call | What it does | Cost | On an empty queue |
|---|---|---|---|
offer(e) / add(e) | insert | O(log n) | n/a |
peek() | read the head | O(1) | returns null |
element() | read the head | O(1) | throws |
poll() | remove the head | O(log n) | returns null |
remove() | remove the head | O(log n) | throws |
remove(o), contains(o) | search | O(n) | false |
size() | count | O(1) | 0 |
For objects, describe the order with Comparator.comparing... and keep adding tie-breakers until two different objects can never compare as equal by accident. The example orders tasks by priority (highest first), then by duration, then by name.
From PriorityQueueTour.java:
public static List<String> run() {
List<String> out = new ArrayList<>();
Queue<Integer> min = new PriorityQueue<>(); // smallest first
Queue<Integer> max = new PriorityQueue<>(Collections.reverseOrder()); // largest first
for (int v : new int[] {35, 20, 50, 10, 40, 5}) {
min.offer(v);
max.offer(v);
}
out.add("min.peek() = " + min.peek());
out.add("max.peek() = " + max.peek());
out.add("min drained = " + drain(min));
out.add("max drained = " + drain(max));
// Objects: build the ordering with Comparator.comparing, never with subtraction
Comparator<Task> byUrgency = Comparator
.comparingInt(Task::priority).reversed() // higher priority first
.thenComparingInt(Task::minutes) // then the shorter job
.thenComparing(Task::name); // then alphabetical: no ambiguity left
Queue<Task> tasks = new PriorityQueue<>(byUrgency);
tasks.add(new Task("write-report", 2, 60));
tasks.add(new Task("fix-prod-bug", 5, 90));
tasks.add(new Task("reply-email", 2, 5));
tasks.add(new Task("deploy", 5, 15));
tasks.add(new Task("code-review", 3, 30));
while (!tasks.isEmpty()) {
Task t = tasks.poll();
out.add("poll -> " + t.name() + " (priority " + t.priority() + ", " + t.minutes() + " min)");
}
Queue<Integer> empty = new PriorityQueue<>();
out.add("empty.peek() = " + empty.peek());
out.add("empty.poll() = " + empty.poll());
try {
empty.element();
} catch (RuntimeException e) {
out.add("empty.element() throws " + e.getClass().getSimpleName());
}
return out;
}
What it prints (output/06-priorityqueue-tour.txt):
min.peek() = 5
max.peek() = 50
min drained = [5, 10, 20, 35, 40, 50]
max drained = [50, 40, 35, 20, 10, 5]
poll -> deploy (priority 5, 15 min)
poll -> fix-prod-bug (priority 5, 90 min)
poll -> code-review (priority 3, 30 min)
poll -> reply-email (priority 2, 5 min)
poll -> write-report (priority 2, 60 min)
empty.peek() = null
empty.poll() = null
empty.element() throws NoSuchElementException
deploy and fix-prod-bug both have priority 5; the second comparator key (15 minutes before 90) decides. Note that reversed() was applied right after the first key. Written at the end of the chain, it would have reversed all three keys.
Thread safety, bounded size and delayed elements
PriorityQueue is not synchronized, and it has no capacity limit. If several threads share one, use PriorityBlockingQueue, which is also unbounded but blocks take() while empty. If elements should only become available after a time, look at DelayQueue. A bounded “keep the best K” queue does not exist as a class; you get it by polling after offering, as the top-K section shows.
Going deeper
- Tour source: PriorityQueueTour.java
- Sort a HashMap by value, including a JMH comparison of top-N with a PriorityQueue against sort-and-limit
PriorityQueue traps that give wrong answers without an error
Trap 1: iteration is not sorted. Only the head is guaranteed. toString, for-each and stream() walk the array in storage order, and two queues with the same content can store it differently:
Every way of looking at the same queue (output/07-iteration-order.txt):
built by add() x 6 : [5, 20, 10, 35, 40, 50]
toString() : [5, 10, 35, 20, 40, 50]
for-each : [5, 10, 35, 20, 40, 50]
stream().toList() : [5, 10, 35, 20, 40, 50]
sorted toArray() : [5, 10, 20, 35, 40, 50]
stream().sorted() : [5, 10, 20, 35, 40, 50]
repeated poll() : [5, 10, 20, 35, 40, 50] (size is now 0)
To read in order, either poll until empty (which consumes the queue) or sort a copy. The Javadoc suggests Arrays.sort(pq.toArray()); with a custom comparator, use pq.stream().sorted(pq.comparator()) instead.
Trap 2: a comparator written with subtraction. (x, y) -> x - y overflows when the values are far apart, and the sign flips:
From Pitfalls.java:
public static List<String> subtractionComparator() {
List<String> out = new ArrayList<>();
int[] values = {1, Integer.MIN_VALUE, 100};
PriorityQueue<Integer> bad = new PriorityQueue<>((x, y) -> x - y);
PriorityQueue<Integer> good = new PriorityQueue<>(Integer::compare);
for (int v : values) {
bad.add(v);
good.add(v);
}
out.add("input : " + Arrays.toString(values));
out.add("(x, y) -> x - y head : " + bad.peek());
out.add("Integer::compare head : " + good.peek());
out.add("1 - Integer.MIN_VALUE = " + (1 - Integer.MIN_VALUE) + " (negative, so 1 'sorts before' MIN_VALUE)");
PriorityQueue<Integer> badMax = new PriorityQueue<>((x, y) -> y - x);
badMax.add(Integer.MIN_VALUE);
badMax.add(7);
out.add("(x, y) -> y - x max-heap of [MIN_VALUE, 7], head: " + badMax.peek());
return out;
}
Real output (output/08-subtraction-comparator.txt):
input : [1, -2147483648, 100]
(x, y) -> x - y head : 1
Integer::compare head : -2147483648
1 - Integer.MIN_VALUE = -2147483647 (negative, so 1 'sorts before' MIN_VALUE)
(x, y) -> y - x max-heap of [MIN_VALUE, 7], head: -2147483648
In the last line the “max-heap” built with y - x returns Integer.MIN_VALUE as its maximum. Use Integer.compare, Comparator.comparingInt or Collections.reverseOrder().
Trap 3: changing an element while it is inside. The heap only reorganizes during its own operations. Change a field that the comparator reads and the element stays where it was. Trap 4: ties are not first-in, first-out.
From Pitfalls.java:
public static List<String> mutationAfterInsert() {
List<String> out = new ArrayList<>();
PriorityQueue<Job> q = new PriorityQueue<>(Comparator.comparingInt((Job j) -> j.cost));
Job a = new Job("A", 10), b = new Job("B", 20), c = new Job("C", 30);
q.add(a);
q.add(b);
q.add(c);
c.cost = 1; // the queue is not told
out.add("after c.cost = 1, peek() : " + q.peek());
out.add("polled in order : " + q.poll() + ", " + q.poll() + ", " + q.poll());
PriorityQueue<Job> r = new PriorityQueue<>(Comparator.comparingInt((Job j) -> j.cost));
Job x = new Job("A", 10), y = new Job("B", 20), z = new Job("C", 30);
r.add(x);
r.add(y);
r.add(z);
r.remove(z); // take it out ...
z.cost = 1; // ... change it ...
r.add(z); // ... put it back
out.add("remove, change, add, polled : " + r.poll() + ", " + r.poll() + ", " + r.poll());
return out;
}
Real output (output/09-mutation-and-ties.txt):
after c.cost = 1, peek() : A:10
polled in order : A:10, C:1, B:20
remove, change, add, polled : C:1, A:10, B:20
equal priority, comparator on priority only : [first, fifth, fourth, third, second]
with a sequence number as the tie-breaker : [first, second, third, fourth, fifth]
After c.cost = 1 the queue still reports A as the smallest, and then hands out C before B: not merely stale, but out of order. Remove, change and re-add. For ties, the Javadoc says they are broken arbitrarily; if arrival order matters, store a sequence number and compare it last.
Traps 5 to 7 at least fail loudly: null is rejected, an object that is not Comparable (with no comparator) is rejected even as the first element, a capacity of 0 is rejected, and modifying the queue inside a for-each over it fails fast.
The exceptions (output/10-exceptions.txt):
add(null) : NullPointerException
add(new Object()) to an empty queue : ClassCastException
new PriorityQueue<>(0) : IllegalArgumentException
add while iterating : ConcurrentModificationException
Fingerprint of a heap bug. If a priority-based program is “mostly right” and occasionally processes something too early or too late, check in this order: a subtraction comparator, a mutated element, a missing tie-breaker, and code that assumed iteration was sorted.
Going deeper
- All seven reproductions: Pitfalls.java
- HashMap vs ConcurrentHashMap, for the same fail-fast versus thread-safe distinction on maps
Heap sort in Java: a max-heap that sorts the array it lives in
Heap sort is two things you already have. First turn the array into a max-heap with bottom-up construction. Then repeatedly swap the maximum (index 0) with the last slot of the heap, shrink the heap by one, and sift the new root down. Use a max-heap for ascending order: the largest element has to leave first because it belongs at the end.
From HeapSort.java:
public static void sort(int[] a) {
int n = a.length;
for (int i = n / 2 - 1; i >= 0; i--) siftDown(a, i, n); // phase 1: heapify, O(n)
for (int end = n - 1; end > 0; end--) { // phase 2: n-1 removals, O(n log n)
int t = a[0];
a[0] = a[end];
a[end] = t;
siftDown(a, 0, end); // the heap is now a[0..end-1]
}
}
private static void siftDown(int[] a, int i, int n) {
int x = a[i];
while (2 * i + 1 < n) {
int child = 2 * i + 1;
if (child + 1 < n && a[child + 1] > a[child]) child++; // the LARGER child: max-heap
if (x >= a[child]) break;
a[i] = a[child];
i = child;
}
a[i] = x;
}
The trace, plus 20,000 random arrays checked against Arrays.sort (output/11-heap-sort.txt):
after phase 1 (max-heap) : [50, 40, 35, 10, 20, 5]
heap [40, 20, 35, 10, 5] | sorted [50]
heap [35, 20, 5, 10] | sorted [40, 50]
heap [20, 10, 5] | sorted [35, 40, 50]
heap [10, 5] | sorted [20, 35, 40, 50]
heap [5] | sorted [10, 20, 35, 40, 50]
result : [5, 10, 20, 35, 40, 50]
random arrays (seed 11) compared with Arrays.sort : 20000, disagreements: 0
Heap sort is O(n log n) in every case and needs no extra array, which sounds ideal. Counted against the JDK sort for objects, it is less flattering:
Comparisons (output/12-heap-sort-vs-arrays-sort.txt):
input HeapSort Arrays.sort (TimSort)
random 3,020,038 1,534,840
ascending 3,112,517 99,999
descending 2,926,640 99,999
TimSort spots already ordered data and finishes after n − 1 comparisons; heap sort cannot benefit from order, because building the heap destroys it. Heap sort is also not stable:
Equal marks, different order (output/13-heap-sort-not-stable.txt):
input : [Asha:70, Bala:90, Chitra:70, Dev:90, Esha:70]
HeapSort : [Esha:70, Chitra:70, Asha:70, Dev:90, Bala:90]
Arrays.sort : [Asha:70, Chitra:70, Esha:70, Bala:90, Dev:90]
Where heap sort is really used. As a safety net.Arrays.sort(int[])uses a dual-pivot quicksort, and when recursion gets too deep it calls aheapSortmethod inDualPivotQuicksort, so that bad input cannot make it quadratic. The Quick Sort article quotes those lines.
Going deeper
- Source: HeapSort.java
- Merge sort in Java, the stable O(n log n) alternative
- Bubble, selection and insertion sort: heap sort is selection sort with a faster way to find the maximum
Top K elements in Java: keep a small heap of the opposite kind (problems 1 and 2)
Problem 1, K-th largest element (LeetCode 215). The tempting solution is a max-heap holding everything. The better idea is a min-heap holding only the K largest seen so far. Its head is the weakest of the current winners, so it is both the gatekeeper and, at the end, the answer.
From KthLargest.java:
public static int find(int[] nums, int k) {
if (k < 1 || k > nums.length) throw new IllegalArgumentException("k out of range: " + k);
PriorityQueue<Integer> top = new PriorityQueue<>(k);
for (int x : nums) {
if (top.size() < k) {
top.offer(x);
} else if (x > top.peek()) { // beats the weakest of the current top k
top.poll();
top.offer(x);
}
}
return top.peek(); // the weakest of the top k IS the k-th largest
}
Problem 2, K-th largest in a stream (LeetCode 703) is the same heap kept alive between calls. Offer, and if the size went past K, poll. Memory stays at K however long the stream runs.
From KthLargestStream.java:
/** Adds a value; returns the k-th largest so far, or null while fewer than k values have arrived. */
public Integer add(int value) {
top.offer(value);
if (top.size() > k) top.poll();
return top.size() == k ? top.peek() : null;
}
Real output (output/14-kth-largest.txt):
array [3, 2, 3, 1, 2, 4, 5, 5, 6] k = 4 -> 4
stream, k = 3, starting with [4, 5, 8, 2]:
add(3)=4 add(5)=5 add(10)=5 add(9)=8 add(4)=8
The usual claim is that O(n log k) beats sorting. Count it before believing it. The table compares sorting everything, the size-K min-heap, and heapifying all n into a max-heap and polling K times (O(n + k log n)):
A million distinct integers (output/15-top-k-comparisons.txt):
input k sort everything min-heap of size k max-heap all, poll k
random 10 18,641,233 1,000,758 1,882,132
ascending 10 999,999 6,937,439 2,000,353
descending 10 999,999 1,000,009 1,000,379
random 1,000 18,641,233 1,131,903 1,919,594
ascending 1,000 999,999 19,934,399 2,037,781
descending 1,000 999,999 1,006,987 1,037,851
random 500,000 18,641,233 14,144,364 20,315,500
ascending 500,000 999,999 19,451,423 20,856,134
descending 500,000 999,999 8,975,732 19,421,238
On random input with K = 10 the small heap needs about one comparison per element and wins by a factor of 18 over sorting. On ascending input every element beats the head and goes in, while TimSort needs only n − 1 comparisons, so sorting wins. At K = n/2 on random data the small heap saves only about a quarter of the comparisons, and heapify-and-poll does worse than sorting.
How to answer “which approach?” Data arrives as a stream or does not fit in memory: size-K min-heap. Data is already in an array, K is small, order unknown: size-K heap or heapify-and-poll. K close to n: sort. And if you may reorder the array and want average O(n), mention quickselect, which reuses the partition step from quick sort (it was not measured here).
Variations an interviewer may ask
K smallest instead: a max-heap of size K. K very close to n: look for the (n − k + 1)-th smallest with a max-heap of that size. Duplicates: “K-th largest” counts duplicates separately; “K-th largest distinct” needs a set beside the heap or a TreeSet. K larger than n: decide whether to throw (as KthLargest does) or return nothing (the stream version returns null).
Going deeper
- Counting code: ProblemsTest.java
- Top-N from a map, with timings from JMH
Top K frequent elements, and the tie-break that flips (problem 3)
Problem 3 (LeetCode 347): count with a HashMap, then run the same size-K pattern on the entries, ordered by count. Because the head must be the worst kept entry, the comparator is “worst first”. If ties are broken by “smaller value wins”, then inside the heap the larger value must count as worse, so the tie-breaker is reversed.
From TopKFrequent.java:
/** Count, then a size-k heap whose head is the WORST of the kept entries. O(n + d log k), d = distinct values. */
public static List<Integer> byHeap(int[] nums, int k) {
Map<Integer, Integer> count = count(nums);
// worst first: fewer occurrences, and among equals the LARGER value (it loses the tie)
Comparator<Map.Entry<Integer, Integer>> worstFirst = Comparator
.<Map.Entry<Integer, Integer>>comparingInt(Map.Entry::getValue)
.thenComparing(Map.Entry::getKey, Comparator.reverseOrder());
PriorityQueue<Map.Entry<Integer, Integer>> heap = new PriorityQueue<>(worstFirst);
for (Map.Entry<Integer, Integer> e : count.entrySet()) {
heap.offer(e);
if (heap.size() > k) heap.poll();
}
LinkedList<Integer> answer = new LinkedList<>();
while (!heap.isEmpty()) answer.addFirst(heap.poll().getKey()); // worst comes out first
return answer;
}
There is also an O(n) answer without a heap: a value can occur at most n times, so use the count as an array index (bucket sort). It is the follow-up interviewers like.
From TopKFrequent.java:
/** Bucket sort on the count: a value can occur at most n times, so index buckets by count. O(n) plus tie sorting. */
public static List<Integer> byBuckets(int[] nums, int k) {
Map<Integer, Integer> count = count(nums);
List<List<Integer>> bucket = new ArrayList<>();
for (int i = 0; i <= nums.length; i++) bucket.add(new ArrayList<>());
count.forEach((value, c) -> bucket.get(c).add(value));
List<Integer> answer = new ArrayList<>();
for (int c = nums.length; c > 0 && answer.size() < k; c--) {
bucket.get(c).sort(null);
for (int v : bucket.get(c)) {
if (answer.size() == k) break;
answer.add(v);
}
}
return answer;
}
The word variant (LeetCode 692) asks for ties in alphabetical order, which is where the reversal gets forgotten. The buggy comparator differs by one word, naturalOrder where reverseOrder is needed:
From TopKFrequent.java:
private static List<String> topWords(String[] words, int k, Comparator<String> tieInHeap) {
Map<String, Integer> count = new HashMap<>();
for (String w : words) count.merge(w, 1, Integer::sum);
PriorityQueue<String> heap = new PriorityQueue<>(
Comparator.<String>comparingInt(count::get).thenComparing(tieInHeap));
for (String w : count.keySet()) {
heap.offer(w);
if (heap.size() > k) heap.poll();
}
LinkedList<String> answer = new LinkedList<>();
while (!heap.isEmpty()) answer.addFirst(heap.poll());
return answer;
}
Real output (output/16-top-k-frequent.txt):
nums [1, 1, 1, 2, 2, 3, 4, 4, 4, 4] k = 2
heap : [4, 1]
buckets : [4, 1]
words [java, heap, queue, java, heap, tree, queue, array] k = 2 (java, heap and queue all occur twice)
tie-break reversed inside the worst-first heap : [heap, java]
tie-break NOT reversed (the bug) : [queue, java]
The bug returns queue instead of heap: it threw away the alphabetically first word among the tied ones. Tests without ties never notice.
Complexity, with d = number of distinct values
Heap version: O(n) to count, O(d log k) for the heap, O(d) extra space for the map. Bucket version: O(n) time plus the sorting of tied values inside a bucket (needed only because this version promises a deterministic order), O(n) space. Note that topWords reads counts through count::get; that is safe because the map does not change while the heap is alive.
Going deeper
- Source: TopKFrequent.java
- How HashMap works internally, for the counting half of the problem
K closest points and last stone weight (problems 4 and 5)
Problem 4, K closest points to the origin (LeetCode 973), is top-K with the direction flipped: you want the K smallest distances, so keep a max-heap of size K and discard the farthest. Compare squared distances; the square root changes no ordering. Do the multiplication in long.
From KClosestPoints.java:
/** Squared distance in long arithmetic: no square roots and no int overflow. */
public static long distance(int[] p) {
return (long) p[0] * p[0] + (long) p[1] * p[1];
}
public static List<int[]> find(int[][] points, int k) {
Comparator<int[]> farthestFirst = Comparator.comparingLong(KClosestPoints::distance).reversed();
PriorityQueue<int[]> heap = new PriorityQueue<>(farthestFirst);
for (int[] p : points) {
heap.offer(p);
if (heap.size() > k) heap.poll(); // throw away the farthest
}
return new ArrayList<>(heap); // "any order" is allowed by the problem
}
Problem 5, last stone weight (LeetCode 1046), needs the largest two items repeatedly while new items appear. That is a plain max-heap.
From LastStoneWeight.java:
public static int solve(int[] stones) {
PriorityQueue<Integer> heap = new PriorityQueue<>(Collections.reverseOrder());
for (int s : stones) heap.offer(s);
while (heap.size() > 1) {
int y = heap.poll();
int x = heap.poll();
if (y > x) heap.offer(y - x);
}
return heap.isEmpty() ? 0 : heap.peek();
}
Real output (output/17-closest-points-and-stones.txt):
points [3,3] [5,-1] [-2,4], k = 2 -> [[-2, 4], [3, 3]]
point (50000, 0): squared distance in int = -1794967296
point (50000, 0): squared distance in long = 2500000000
stones [2, 7, 4, 1, 8, 1] -> last stone weight 1
The overflow is silent. 50,000 squared is 2.5 billion, past the int limit of about 2.147 billion. The int result is negative, so a far point would sort as the closest one. Casting one operand to long before multiplying fixes it.
Going deeper
- Sources: KClosestPoints.java, LastStoneWeight.java
- Both are O(n log k) or O(n log n) in time; the first uses O(k) space, the second O(n)
Merge K sorted lists: one node per list in the heap (problem 6)
Problem 6 (LeetCode 23). The next output node must be the smallest among the current heads of the K lists. Put those K heads in a min-heap, poll the smallest, append it, and offer its successor.
From MergeKSortedLists.java:
public static Node merge(Node[] lists, Comparator<Node> order) {
PriorityQueue<Node> heads = new PriorityQueue<>(order);
for (Node n : lists) if (n != null) heads.offer(n); // PriorityQueue rejects null
Node dummy = new Node(0), tail = dummy;
while (!heads.isEmpty()) {
Node smallest = heads.poll();
tail.next = smallest;
tail = smallest;
if (smallest.next != null) heads.offer(smallest.next);
}
return dummy.next;
}
The null check in the first loop is not optional: an empty input list has a null head, and PriorityQueue rejects it. The same transcript compares the heap with two other strategies, merging the lists one after another, and merging them in pairs the way merge sort does:
Real output (output/18-merge-k-sorted-lists.txt):
[1,4,5] [1,3,4] [2,6] [] -> [1, 1, 2, 3, 4, 4, 5, 6]
offering the head of an empty list (null) without the check: NullPointerException
comparisons, each list holding 1,000 random values (seed 5):
k N heap of heads merge one by one merge in pairs
2 2,000 1,998 1,998 1,998
10 10,000 61,857 53,944 35,983
100 100,000 1,270,358 5,045,132 687,813
1,000 1,000,000 18,739,107 500,034,011 9,982,020
One-by-one merging is O(Nk) and falls apart: 500 million comparisons at K = 1,000. Pairwise merging is O(N log K) like the heap and, measured here, needs roughly half the comparisons, because a sift down spends two comparisons per level. At K = 10 even one-by-one merging used fewer comparisons than the heap. The heap still earns its place when the inputs are streams that you cannot revisit, or when K sources deliver items lazily: it holds one item from each.
Going deeper
- All three versions: MergeKSortedLists.java
- Linked lists in Java
- Merge sort, whose merge step is reused here
Running median of a stream: two heaps facing each other (problem 7)
Problem 7 (LeetCode 295). Numbers arrive one at a time and you must report the median after each. Split them into a lower half in a max-heap and an upper half in a min-heap. The two heads are the two middle values.
Each insert goes to the side it belongs to, and then at most one element is moved across to restore the size rule.
From RunningMedian.java:
public void add(int x) { // O(log n)
if (lower.isEmpty() || x <= lower.peek()) lower.offer(x);
else upper.offer(x);
if (lower.size() > upper.size() + 1) upper.offer(lower.poll());
else if (upper.size() > lower.size()) lower.offer(upper.poll());
}
public double median() { // O(1)
if (lower.isEmpty()) throw new IllegalStateException("no values yet");
if (lower.size() > upper.size()) return lower.peek();
return ((long) lower.peek() + upper.peek()) / 2.0; // widen BEFORE adding
}
Real output (output/19-running-median.txt):
add( 5) lower(max-heap)=[5] upper(min-heap)=[] median=5.0
add(15) lower(max-heap)=[5] upper(min-heap)=[15] median=10.0
add( 1) lower(max-heap)=[1, 5] upper(min-heap)=[15] median=5.0
add( 3) lower(max-heap)=[1, 3] upper(min-heap)=[5, 15] median=4.0
add( 8) lower(max-heap)=[1, 3, 5] upper(min-heap)=[8, 15] median=5.0
add( 7) lower(max-heap)=[1, 3, 5] upper(min-heap)=[7, 8, 15] median=6.0
values 2147483647 and 2147483645:
(a + b) / 2.0 in int arithmetic : -2.0
((long) a + b) / 2.0 : 2147483646.0
The lower half is printed sorted for readability; inside the queue it is a max-heap. The final two lines show the other overflow: adding two large ints before dividing gives -2.0.
Follow-ups: sliding-window median, bounded values
Median of the last W values: elements must also leave. remove(Object) does it correctly but costs O(W) per step; lazy deletion (count what should be gone and discard it when it reaches a head) gets back to logarithmic time, at the price of tracking the logical sizes yourself. Values in a small range (say 0 to 100): keep a count array and walk it; no heap needed. Neither variation is implemented in the companion module.
Going deeper
Task scheduler: a heap for ready work and a waiting line for cooling work (problem 8)
Problem 8 (LeetCode 621). Tasks are letters, each takes one time unit, and two runs of the same letter need at least n units between them. Find the shortest timeline. The greedy rule: at every unit, run the ready letter with the most copies left.
Letters that just ran are not ready, so they leave the heap and wait in a FIFO queue until their time comes. In the timelines below, a dash is an idle unit.
From TaskScheduler.java:
/** Returns the timeline, one character per time unit, '.' for idle. Its length is the answer. */
public static String schedule(String tasks, int n) {
int[] count = new int[26];
for (char c : tasks.toCharArray()) count[c - 'A']++;
PriorityQueue<Pending> ready = new PriorityQueue<>(
Comparator.<Pending>comparingInt(p -> p.left).reversed().thenComparingInt(p -> p.name));
for (int i = 0; i < 26; i++) if (count[i] > 0) ready.offer(new Pending((char) ('A' + i), count[i]));
ArrayDeque<Pending> cooling = new ArrayDeque<>(); // FIFO is enough: readyAt only increases
StringBuilder timeline = new StringBuilder();
for (int time = 0; !ready.isEmpty() || !cooling.isEmpty(); time++) {
if (!cooling.isEmpty() && cooling.peek().readyAt <= time) ready.offer(cooling.poll());
Pending p = ready.poll();
if (p == null) {
timeline.append('.');
continue;
}
timeline.append(p.name);
if (--p.left > 0) {
p.readyAt = time + n + 1; // safe to mutate: p is OUTSIDE the heap now
cooling.add(p);
}
}
return timeline.toString();
}
Notice that p.left and p.readyAt are mutated, which was trap 3 above. It is safe here because the object has been polled and is outside the heap while it changes.
If only the length is wanted, there is a counting formula: the most frequent letter (say max copies, shared by atMax letters) forms a frame of (max - 1) * (n + 1) + atMax units, and the answer is that or the number of tasks, whichever is larger.
From TaskScheduler.java:
/** The O(N) counting formula for the length only. */
public static int formula(String tasks, int n) {
int[] count = new int[26];
for (char c : tasks.toCharArray()) count[c - 'A']++;
int max = 0, atMax = 0;
for (int c : count) {
if (c > max) {
max = c;
atMax = 1;
} else if (c == max) {
atMax++;
}
}
if (max == 0) return 0;
return Math.max(tasks.length(), (max - 1) * (n + 1) + atMax);
}
Real output (output/20-task-scheduler.txt):
tasks=AAABBB n=2 timeline=AB.AB.AB length=8 formula=8
tasks=AAABBB n=0 timeline=ABABAB length=6 formula=6
tasks=AAAAAABCDEFG n=2 timeline=ABCADEAFGA..A..A length=16 formula=16
tasks=AAABBBCCCDD n=2 timeline=ABCABCDABCD length=11 formula=11
Greedy rules deserve suspicion, so both versions were compared with an exhaustive search that tries every choice, including idling, on 1,500 random inputs of up to eight tasks. No disagreement, and each timeline was also checked to respect the cooldown.
Going deeper
- Scheduler: TaskScheduler.java; exhaustive search: BruteForce.java
- The heap version runs one step per time unit; the formula is O(number of tasks)
Meeting rooms and connecting ropes (problems 9 and 10)
Problem 9, meeting rooms (LeetCode 253). Sort meetings by start. Keep the end times of occupied rooms in a min-heap. If the earliest end is not after the new start, that room is free: reuse it.
From MeetingRooms.java:
public static int minRooms(int[][] meetings) {
int[][] byStart = meetings.clone();
Arrays.sort(byStart, Comparator.comparingInt(m -> m[0]));
PriorityQueue<Integer> endTimes = new PriorityQueue<>();
for (int[] m : byStart) {
if (!endTimes.isEmpty() && endTimes.peek() <= m[0]) endTimes.poll(); // reuse that room
endTimes.offer(m[1]);
}
return endTimes.size();
}
Problem 10, connect ropes (also known as “minimum cost to connect sticks”). Joining two ropes costs their combined length. Always join the two shortest. This is the core step of Huffman coding.
From ConnectRopes.java:
public static long minCost(int[] ropes) {
PriorityQueue<Long> heap = new PriorityQueue<>();
for (int r : ropes) heap.offer((long) r);
long cost = 0;
while (heap.size() > 1) {
long joined = heap.poll() + heap.poll(); // always the two shortest, INCLUDING joined ropes
cost += joined;
heap.offer(joined);
}
return cost;
}
/** Looks right, is wrong: sorting once forgets that a joined rope has to compete with the others. */
public static long sortOnceAndFold(int[] ropes) {
int[] s = ropes.clone();
Arrays.sort(s);
long length = s.length == 0 ? 0 : s[0], cost = 0;
for (int i = 1; i < s.length; i++) {
length += s[i];
cost += length;
}
return cost;
}
The second method is the tempting shortcut that needs no heap. Four equal ropes are enough to break it:
Real output (output/21-meeting-rooms-and-ropes.txt):
meetings [0,30) [5,10) [15,20) -> rooms 2
meetings [9,10) [10,11) [11,12) -> rooms 1
ropes [4, 3, 2, 6] heap: 29 sort once and fold: 29
ropes [4, 4, 4, 4] heap: 32 sort once and fold: 36
Check the boundary in the problem statement. The code treats meetings as half-open,[start, end), so a meeting ending at 10 and one starting at 10 share a room (<=). If the statement says a room needs the meeting to have strictly ended, use<, and the touching example needs more rooms.
Going deeper
- Sources: MeetingRooms.java, ConnectRopes.java
- Dijkstra and Prim: the other classic priority-queue algorithms
Brute-force cross-checks and a heap complexity cheat sheet
Each problem has a deliberately naive solution in BruteForce.java (sort everything, rescan, try every pairing). The heap solution must match it on seeded random input, including small value ranges that force many ties:
Real output (output/22-brute-force-cross-checks.txt):
problem trials disagreements
1 k-th largest 5000 0
2 k-th largest in a stream 2000 0
3 top k frequent (heap, buckets) 5000 0
4 k closest points 5000 0
5 last stone weight 5000 0
6 merge k sorted lists 3000 0
7 running median 1000 0
8 task scheduler (vs search) 1500 0
9 meeting rooms 5000 0
10 connect ropes (vs all pairings) 1000 0
the sort-once-and-fold shortcut was wrong on 375 of those 1000 rope sets
| # | Problem | Heap idea | Time | Extra space |
|---|---|---|---|---|
| 1 | K-th largest | min-heap of size k | O(n log k) | O(k) |
| 2 | K-th largest in a stream | same heap, kept | O(log k) per value | O(k) |
| 3 | Top K frequent | count, then size-k heap | O(n + d log k) | O(d + k) |
| 4 | K closest points | max-heap of size k | O(n log k) | O(k) |
| 5 | Last stone weight | max-heap | O(n log n) | O(n) |
| 6 | Merge K sorted lists | heap of list heads | O(N log k) | O(k) |
| 7 | Running median | max-heap + min-heap | O(log n) add, O(1) read | O(n) |
| 8 | Task scheduler | max-heap + FIFO queue | O(L log d), L = timeline length | O(d) |
| 9 | Meeting rooms | min-heap of end times | O(n log n) | O(n) |
| 10 | Connect ropes | min-heap, merge two | O(n log n) | O(n) |
Quick viva questions (click to open)
Is a sorted array a min-heap? Yes: every parent comes before its children, so no child is smaller. A heap is usually not sorted.
Where is the maximum of a min-heap? At one of the leaves, which are the second half of the array. Finding it is O(n).
Where is the second smallest? One of the root’s two children.
Height of a heap with n nodes? floor(log2 n).
Why not build a priority queue on a linked list? Either insertion or removal of the minimum becomes O(n).
PriorityQueue or TreeMap? TreeMap gives both ends, ordered iteration and O(log n) removal by key; PriorityQueue is a flat array with no per-entry node objects and accepts duplicates directly.
When a heap is the wrong tool
Should you use a PriorityQueue at all? Not if you need the data fully sorted once: callsort. Not if you need the minimum once: a single loop is O(n) with no allocation. Not if you need to search, delete arbitrary items or walk in order: use aTreeMaporTreeSet. Not if priorities are a handful of small integers: an array of queues does it in O(1). A heap pays off when items keep arriving or changing between requests for the best one.
Further reading
- Companion module: java-interview-lab/heap and its README
- java.util.PriorityQueue (JDK 25 API)
- NIST Dictionary of Algorithms: heapsort
- PriorityBlockingQueue in Java
- Graph algorithms in Java: Dijkstra, topological sort, union-find
- Stack and queue problems in Java
- Dynamic programming in Java for beginners
No Comments yet!