Heaps and Priority Queues

How a binary heap implements a priority queue, how to find the top k items in O(n log k), and what interviewers ask about heaps.

17 minLesson 4 of 6
On this page
  1. How a binary heap works
  2. The code
  3. Cost
  4. Variants and related uses
  5. Common mistakes with heaps
  6. In the interview
  7. What to practise next

A priority queue is a container that always gives you the item with the highest priority next, no matter what order the items arrived in. It supports three operations: add an item, look at the best item, and remove the best item. You reach for one whenever a problem keeps asking for the smallest, largest or most urgent item while new items keep arriving.

The usual implementation is a binary heap. Without it you have two simple options, and both are slow. If you keep the items unsorted, adding is instant but finding the best item means scanning all of them, which costs O(n). If you keep them sorted, the best item is at one end, but every insert has to shift other items to make room, which also costs O(n). A heap makes both adding and removing O(log n), and looking at the best item O(1).

How a binary heap works

A heap is a binary tree stored in an array, as described in Heap Sort. The children of index i are at 2i + 1 and 2i + 2, and the parent of index i is at (i - 1) / 2, rounded down. The tree is filled level by level from left to right, so n items occupy only about log₂ n levels.

In a min-heap, every parent is less than or equal to its children, so the smallest item is always at the root, heap[0]. The rule only relates a parent to its children. Two siblings can be in either order, so a heap is not a sorted array. That loose rule is the reason it is cheap to maintain: after any change, only the items on one path from the root to a leaf may need to move.

Push: add at the end and sift up

To add an item, place it in the next free slot at the end of the array, which keeps the tree complete. It may now be smaller than its parent, so sift it up: while it is smaller than its parent, swap the two. It stops when its parent is smaller or when it reaches the root.

Pop: move the last item to the root and sift down

The smallest item is the root. To remove it without leaving a hole, take the last item in the array, put it at the root and shorten the array by one. That item is probably too large for its new position, so sift it down: swap it with its smaller child until it is no larger than both of its children. It has to swap with the smaller child, because the smaller child will become the parent of the other one.

The tracer below starts with a heap of orders due in 2, 4, 5, 7, 8 and 9 minutes, adds an order due in 3, and then removes the most urgent order.

Push 3, then pop the smallestUse the arrows or ← → keys
push(x):  add x at the end  while x < its parent: swap thempop():  top = heap[0]  move the last item to index 0  while it > its smaller child: swap them  return top
  1. heap
    02
    15
    24
    39
    47
    58
    254978

    1This is a valid min-heap. The smallest value, 2, is at the root.

  2. heap
    02
    15
    24
    39
    47
    58
    63i
    2549783

    2Push 3 into the next free slot, index 6. Its parent is at (6 − 1) / 2 = 2.5, rounded down to 2, which holds 4.

  3. heap
    02
    15
    23i
    39
    47
    58
    64
    2539784

    33 is smaller than its parent 4, so they swap and 3 moves up to index 2.

  4. heap
    02
    15
    23i
    39
    47
    58
    64
    2539784
    swaps
    1

    4The new parent of 3 is the root, 2. Since 3 is not smaller than 2, it stops. The push took one swap.

  5. heap
    04i
    15
    23
    39
    47
    58
    453978
    popped
    2

    5Pop returns the root, 2. The last item, 4, moves to the root. It is now larger than its child 3, which breaks the rule.

  6. heap
    03
    15
    24i
    39
    47
    58
    354978
    popped
    2

    64 swaps with its smaller child, 3. It has to be the smaller child: 3 can sit above 5, but 5 could not sit above 3.

  7. heap
    03
    15
    24
    39
    47
    58
    354978
    popped
    2
    swaps
    1

    7At index 2, the only child of 4 is 8, which is larger, so 4 stops. The heap is valid again, with 3 at the root.

1 / 7

The code

Push
// heap is a plain array kept in min-heap order.
function heapPush(heap, x) {
  heap.push(x); // add at the end of the bottom level
  let i = heap.length - 1;
  while (i > 0) {
    const parent = Math.floor((i - 1) / 2);
    if (heap[parent] <= heap[i]) break; // parent is smaller: done
    [heap[parent], heap[i]] = [heap[i], heap[parent]];
    i = parent; // keep climbing
  }
}
# heap is a plain list kept in min-heap order.
def heap_push(heap, x):
    heap.append(x)  # add at the end of the bottom level
    i = len(heap) - 1
    while i > 0:
        parent = (i - 1) // 2
        if heap[parent] <= heap[i]:  # parent is smaller: done
            break
        heap[parent], heap[i] = heap[i], heap[parent]
        i = parent  # keep climbing
Pop
function heapPop(heap) {
  const top = heap[0];
  const last = heap.pop(); // remove the last item
  if (heap.length === 0) return top; // it was the only one
  heap[0] = last; // move it to the root and sift down
  let i = 0;
  while (true) {
    const left = 2 * i + 1, right = 2 * i + 2;
    let small = i;
    if (left < heap.length && heap[left] < heap[small]) small = left;
    if (right < heap.length && heap[right] < heap[small]) small = right;
    if (small === i) break; // smaller than both children: done
    [heap[i], heap[small]] = [heap[small], heap[i]];
    i = small;
  }
  return top;
}
 
const heap = [2, 5, 4, 9, 7, 8];
heapPush(heap, 3); // [2, 5, 3, 9, 7, 8, 4]
heapPop(heap);     // 2, heap is now [3, 5, 4, 9, 7, 8]
def heap_pop(heap):
    top = heap[0]
    last = heap.pop()  # remove the last item
    if not heap:  # it was the only one
        return top
    heap[0] = last  # move it to the root and sift down
    i = 0
    while True:
        left, right = 2 * i + 1, 2 * i + 2
        small = i
        if left < len(heap) and heap[left] < heap[small]:
            small = left
        if right < len(heap) and heap[right] < heap[small]:
            small = right
        if small == i:  # smaller than both children: done
            break
        heap[i], heap[small] = heap[small], heap[i]
        i = small
    return top
 
heap = [2, 5, 4, 9, 7, 8]
heap_push(heap, 3)  # [2, 5, 3, 9, 7, 8, 4]
heap_pop(heap)      # 2, heap is now [3, 5, 4, 9, 7, 8]

Python's heapq module provides heappush(heap, x) and heappop(heap), which work on a plain list exactly like the functions above, and heapify(list), which turns a list into a heap in place. JavaScript has no built-in heap, so in an interview you either write these two functions or ask the interviewer whether you may assume one exists.

Cost

ApproachTimeSpaceWhy
Unsorted arraypush O(1), pop O(n)O(n)Each pop scans every item.
Sorted arraypush O(n), pop O(1)O(n)Each push shifts items to make room.
Binary heappush O(log n), pop O(log n)O(n)Sifting follows one path of about log₂ n levels. Peek is O(1).

Max-heap

A max-heap keeps the largest item at the root, so the comparisons in the code above are reversed. Python's heapq only provides a min-heap, so the standard workaround is to push the negated value and negate it again after popping. In JavaScript you write the comparison yourself, so a max-heap is a one-character change. The common bug in Python is forgetting the second negation, which returns negative numbers.

Heaps of pairs and custom priorities

Most problems need to carry data along with the priority, such as a task name or a node id. In Python, push a tuple like (priority, item). Tuples compare by their first element and then by the second, so if two priorities are equal, Python compares the items, which fails if the items cannot be compared with <, for example dictionaries or custom objects. Put a unique counter in the middle, as in (priority, counter, item), to avoid that. In JavaScript, store [priority, item] and compare heap[i][0] in the sift loops.

Building a heap from n items with heapify

Pushing n items one at a time costs O(n log n). Building a heap directly from an existing array is faster: start at the last parent, index n / 2 - 1 rounded down, and sift each node down, moving back to index 0. This is O(n), because half of the nodes are leaves that need no work, a quarter can move at most one level, and so on, so the total number of swaps adds up to a constant multiple of n. This is what heapq.heapify does, and it is the first phase of heap sort.

Top k items

To find the k largest values among n, keep a min-heap that holds the best k seen so far. Its root is the weakest of them, which is the value a new item has to beat. Push each new value, and if the heap now has k + 1 items, pop the smallest. When the input ends, the heap holds the k largest values. A max-heap does not work here, because the item you need to throw away is the smallest of the current best, and a max-heap cannot give you that.

77 88 95 root: the bar to beat 63 63 < 77: popped right away 90 90 > 77: stays, 77 is popped heap size never goes above k + 1 = 4
The min-heap holds the best 3 scores so far. A new score below the root is removed again at once, and a higher one replaces the root.
// Uses heapPush and heapPop from above.
function topK(nums, k) {
  const heap = [];
  for (const x of nums) {
    heapPush(heap, x);
    if (heap.length > k) heapPop(heap); // drop the smallest
  }
  return heap.sort((a, b) => a - b);
}
 
topK([40, 95, 12, 77, 63, 88], 3); // [77, 88, 95]
import heapq
 
def top_k(nums, k):
    heap = []
    for x in nums:
        heapq.heappush(heap, x)
        if len(heap) > k:
            heapq.heappop(heap)  # drop the smallest
    return sorted(heap)
 
top_k([40, 95, 12, 77, 63, 88], 3)  # [77, 88, 95]

The heap never holds more than k + 1 items, so each push and pop costs O(log k). The total is O(n log k) time and O(k) extra space. Sorting everything would cost O(n log n) and needs all n items in memory, which matters when the numbers arrive as a stream. The k-th largest value alone is simply the root of this heap at the end.

Two heaps for a running median

To track the median of a stream, keep the smaller half of the numbers in a max-heap and the larger half in a min-heap, and keep their sizes equal or off by one. The median is the root of the larger heap, or the average of both roots when the sizes are equal. Each new number goes into one heap and, if the sizes become uneven or the roots are in the wrong order, one item is moved across. Every update costs O(log n), and reading the median costs O(1).

Merging k sorted lists

Put the first element of each of the k lists into a min-heap, together with the list it came from. Pop the smallest, append it to the output, and push the next element from the same list. The heap never holds more than k items, so merging n elements in total costs O(n log k).

When a heap is the wrong tool

A heap can only give you the extreme item cheaply. Finding an arbitrary value takes O(n), because the rest of the array has no useful order. Removing or changing the priority of an item that is not at the root is also awkward, because you first have to find it. If you need ordered traversal, range queries or "the next larger value after x", use a balanced search tree or a sorted structure instead.

Common mistakes with heaps

In the interview

How to recognise a heap problem

Look for these signals in the problem statement:

  • The statement asks for the "k largest", "k smallest", "k most frequent", "k closest" or the "k-th largest" item.
  • The statement needs the minimum or maximum again and again while items are added, removed or changed, as in task scheduling, event simulation or picking the next cheapest edge.
  • The statement asks you to merge several sorted sequences or to find the median of a stream.

If the data is fixed and fully available, ask whether a single sort or a scan is enough before reaching for a heap.

Follow-up questions

  • "Why a min-heap for the k largest elements?" The heap has to tell you which of the current k candidates to discard next, and that is the smallest one. A min-heap of size k keeps that item at the root, so each new element is compared against it in O(1) and replaces it in O(log k).
  • "What is the time complexity of building a heap from n elements?" It is O(n) with heapify and O(n log n) with n separate pushes. Heapify is faster because most nodes are near the bottom and can only move a few levels.
  • "Heap or sort for the top k?" Sorting costs O(n log n) time and holds everything in memory. The heap costs O(n log k) and O(k) memory, so it wins when k is much smaller than n or when the data is a stream. If k is close to n, sorting is just as good and simpler.
  • "Can you do better than O(n log k)?" Quickselect finds the k-th largest in O(n) on average, but it needs the whole array in memory, changes the order of the array, and has an O(n²) worst case. The heap is the safer answer for streams, and quickselect is the answer when everything fits in memory and average speed matters.
  • "How do you find or remove an arbitrary item?" A plain heap cannot do it quickly, because finding the item is O(n). Either use lazy deletion, as described above, or keep a map from each item to its index in the array so you can find it in O(1) and sift it in O(log n).
  • "How do you find the k most frequent elements?" Count the occurrences with a hash map, then run the top k method on the counts, keeping a min-heap of size k that holds (count, element) pairs. This costs O(n) for counting and O(m log k) for the heap, where m is the number of distinct elements.
  • "How would you track the median of a stream?" Describe the two heaps: a max-heap for the lower half and a min-heap for the upper half, kept within one element of each other in size. Insertion is O(log n) and reading the median is O(1).
Quick check

You push 1 into the min-heap [2, 5, 4, 9, 7, 8]. How many swaps does sift up make?

You need the 10 largest values in a stream of a million numbers, using little memory. What do you keep?

When you pop, why do you move the last item to the root instead of promoting the root's smaller child?

What to practise next

Solve Kth Fastest Finisher and Live Median House Price to use a heap and two heaps. Then read Tries for prefix searches, or Dijkstra's algorithm to see a priority queue drive a shortest-path search.