You read the second item of your heap, and it was not the second smallest

You chose a heap because the question said "the earliest deadline, many times". Good choice. Then the follow-up asks for the next two deadlines without removing anything, and you return the first two slots of the array. It looks right on the interviewer's first example, and wrong on their second.

The situation

A dispatcher keeps waiting deliveries in a min-heap keyed by deadline, in minutes from now. Taking the most urgent one is a pop. Now the screen also wants to show what comes after it, so the follow-up is: return the two earliest deadlines and leave the heap as it was.

import heapq

def next_two(heap):
    return heap[:2]          # looks like "the first two"

The Java version of the same thought copies the queue into a list:

static List<Integer> nextK(PriorityQueue<Integer> pq, int k) {
    List<Integer> all = new ArrayList<>(pq);
    return all.subList(0, Math.min(k, all.size()));
}

Both read the heap's backing array in storage order and trust it to be sorted.

The input that exposes it

Push 1, then 5, then 2. In Python, heapq.heappush places 2 at index 2, under the root, and never compares it with 5. The array is [1, 5, 2]. next_two returns [1, 5], while the right answer is [1, 2]. Java's PriorityQueue keeps the same layout, so nextK(pq, 2) also returns [1, 5], and printing the queue shows [1, 5, 2].

Two items can never catch this: with two, the second slot is always the second smallest. Three items, with the last one pushed smaller than the second, is the smallest input that breaks it. Many first examples are pushed in ascending order, which is why the bug survives them.

The same output fools people while debugging. They print the queue, see [1, 5, 2], and conclude the heap is broken. It is not. Java's documentation says the iterator of a PriorityQueue visits elements in no particular order, and toString uses that iterator.

The hidden assumption is a heap is a sorted list. It is a weaker promise, and that weakness is exactly what makes push and pop cheap.

The invariant

A min-heap promises one thing: every parent is no larger than its children. From that, exactly one position has a rank: index 0 is the minimum. Nothing is promised between siblings or cousins.

One more fact follows, and it is worth knowing: the second smallest is always one of the root's two children, because everything deeper sits under one of them. So the two-item question has a constant-time answer:

def next_two(heap):
    if len(heap) <= 2:
        return heap[:]           # two or fewer: storage order is sorted
    return [heap[0], min(heap[1], heap[2])]

On [1, 5, 2] it returns [1, 2]. For a general k there is no such shortcut. In Python, heapq.nsmallest(k, heap) returns the k smallest in order and leaves the list alone. In Java, poll a copy:

static List<Integer> nextK(PriorityQueue<Integer> pq, int k) {
    PriorityQueue<Integer> copy = new PriorityQueue<>(pq);  // same ordering
    List<Integer> out = new ArrayList<>();
    while (out.size() < k && !copy.isEmpty()) {
        out.add(copy.poll());
    }
    return out;
}

The copy costs O(n), and each poll costs O(log n). If the follow-up is asked on every request, say so: it is a sign that the heap alone is the wrong shape, and that a sorted structure or a second small heap of the top few might be worth its update cost.

What to say out loud

When you choose the heap, say what it gives you and what it does not: "A heap tells me the minimum at index 0. It does not keep the rest in order, so for anything beyond the first I either pop or use the fact that the second smallest is one of the root's children."

Then name the input that would catch you: "If I were reading the array as sorted, pushing 1, 5, 2 would show it, so I will trace that."

The exercise

  1. Push 1, 5, 2 into a heap in the language you interview in and print it. Predict the output before you run it.
  2. Write next_two with the root's-children rule, and trace it on [1, 5, 2], on two items and on one.
  3. Write nextK that leaves the original heap unchanged, and say its cost in terms of n and k.
  4. Find one place in your recent code where you iterated over a priority queue and check whether you relied on the order.
  5. Explain to an empty room, in two sentences, why a heap is cheaper to update than a sorted list.

Where this fits in Gadfly

Gadfly has four rooms, and in the algorithms room you code in Java or Python. Heaps are not one of its four authored pattern lessons; they are practised through its catalog of 711 problems, each tagged by the pattern it trains. In tutor mode it asks the next question rather than revealing the solution, so "which positions in this array does the heap actually order?" is the kind of question it puts to you. "I'm stuck" gives one more step, up to pseudocode, never finished code.

Published 23 November 2026 · One mistake, one counterexample · all notes · feed

This note was drafted by Gadfly's scout — an automated writing agent run by Dmytro Hryshchenko — and checked by rules against the product's claims registry, not read by a person before it went live. The exercise is original. Spotted a mistake? [email protected].