Heap and priority queue pattern for coding interviews

A heap, used as a priority queue, gives you the smallest (or largest) item in O(1) and lets you add or remove items in O(log n), without keeping everything fully sorted. Reach for it when a problem repeatedly needs "the next smallest", "the k largest", "the earliest to finish" or "the cheapest so far", especially when items keep arriving. Most heap questions are one of four shapes: top k, merging sorted streams, two heaps for a median, and scheduling.

By Published 8 min read

What a heap gives you

A binary heap is an array arranged as a tree in which every parent is no larger than its children (for a min-heap). The smallest item is always at index 0. Adding an item puts it at the end and swaps it upward; removing the smallest moves the last item to the top and swaps it downward. Each costs O(log n). Turning an existing array into a heap costs O(n). What a heap does not give you is fast search or sorted iteration: finding an arbitrary item is O(n). That trade is the point. When you only ever need the extreme, sorting everything is wasted work.

Heap or something else?
NeedBest fit
The k largest of a fixed list, onceHeap of size k, or quickselect for average O(n)
The k largest as values stream inHeap of size k
Repeatedly the smallest, with inserts in betweenHeap
Smallest and largest, plus deletes of any itemA balanced tree or sorted container
Max of a sliding windowMonotonic deque, see the monotonic stack pattern
Heap or something else?. Scroll sideways on a small screen.

Shape 1: the k-th largest and top k

Keep a min-heap holding the k largest values seen so far. Its root is the smallest of them, which is exactly the k-th largest. A new value only matters if it beats the root, in which case it replaces it. For the values [7, 2, 9, 4, 9, 1] and k = 2, the heap ends holding [9, 9] and the answer is 9, since duplicates count separately. Counting first and then keeping the top k by count is the approach in Top K Frequent Elements.

import heapq

def kth_largest(values, k):
    heap = []                      # min-heap of the k largest so far
    for v in values:
        if len(heap) < k:
            heapq.heappush(heap, v)
        elif v > heap[0]:
            heapq.heapreplace(heap, v)
    return heap[0]
Python: k-th largest in O(n log k) time and O(k) space.
class MinHeap {
  constructor() { this.a = []; }
  get size() { return this.a.length; }
  peek() { return this.a[0]; }
  push(x) {
    const a = this.a;
    a.push(x);
    let i = a.length - 1;
    while (i > 0) {
      const p = (i - 1) >> 1;
      if (a[p] <= a[i]) break;
      [a[p], a[i]] = [a[i], a[p]];
      i = p;
    }
  }
  pop() {
    const a = this.a, top = a[0], last = a.pop();
    if (a.length > 0) {
      a[0] = last;
      let i = 0;
      for (;;) {
        const l = 2 * i + 1, r = l + 1;
        let m = i;
        if (l < a.length && a[l] < a[m]) m = l;
        if (r < a.length && a[r] < a[m]) m = r;
        if (m === i) break;
        [a[m], a[i]] = [a[i], a[m]];
        i = m;
      }
    }
    return top;
  }
}

function kthLargest(values, k) {
  const heap = new MinHeap();
  for (const v of values) {
    if (heap.size < k) heap.push(v);
    else if (v > heap.peek()) { heap.pop(); heap.push(v); }
  }
  return heap.peek();
}
JavaScript: a minimal MinHeap, then the same algorithm.

In an interview, ask whether you may assume a heap exists. Many interviewers let you say "assume a priority queue with push and pop" in JavaScript; others want to see one written. Knowing the sift-up and sift-down loops above covers both.

Shape 2: merging k sorted lists

To merge several sorted lists, the next output value is always one of the lists' current front items. Keep exactly those in a heap, with a note of which list each came from. Pop the smallest, output it, and push the next item from the same list. With N items in total, that is O(N log k), much better than concatenating and sorting when k is small. Storing (value, list index, position) also breaks ties without comparing anything else.

import heapq

def merge_sorted_lists(lists):
    heap = [(lst[0], i, 0) for i, lst in enumerate(lists) if lst]
    heapq.heapify(heap)
    out = []
    while heap:
        value, i, j = heapq.heappop(heap)
        out.append(value)
        if j + 1 < len(lists[i]):
            heapq.heappush(heap, (lists[i][j + 1], i, j + 1))
    return out
Merge k sorted lists with a heap of at most k entries.

Shape 3: two heaps for a running median

Numbers arrive one at a time and you must report the median after each. Split the values into a lower half, kept in a max-heap, and an upper half, kept in a min-heap, with the lower half allowed one extra item. Each new value goes into the lower half, the largest of the lower half moves up, and if the upper half becomes bigger, its smallest moves back down. The median is then the top of the lower half, or the average of both tops. Python's heapq is a min-heap only, so store negated values for the max-heap.

import heapq

class RunningMedian:
    def __init__(self):
        self.low = []    # max-heap via negated values: the smaller half
        self.high = []   # min-heap: the larger half

    def add(self, x):
        heapq.heappush(self.low, -x)
        heapq.heappush(self.high, -heapq.heappop(self.low))
        if len(self.high) > len(self.low):
            heapq.heappush(self.low, -heapq.heappop(self.high))

    def median(self):
        if len(self.low) > len(self.high):
            return -self.low[0]
        return (-self.low[0] + self.high[0]) / 2
Running median: O(log n) per insert, O(1) per query.

Shape 4: scheduling by what frees up first

How many rooms do these meetings need? Sort meetings by start time and keep a min-heap of end times for meetings in progress. If the earliest end is at or before the next start, that room is free and can be reused; otherwise open a new room. The heap's size at the end is the answer. For meetings 9 to 10, 9 to 12, 11 to 13 and 12 to 14, two rooms are enough. Sorting by start is the same first step as in Merge Intervals; the heap adds "which one ends first".

import heapq

def rooms_needed(meetings):
    ends = []                      # end times of meetings in progress
    for start, end in sorted(meetings):
        if ends and ends[0] <= start:
            heapq.heapreplace(ends, end)   # reuse the room freed first
        else:
            heapq.heappush(ends, end)
    return len(ends)
Minimum rooms for a set of (start, end) meetings, O(n log n).

Example problems to practice

  • [Top K Frequent Elements](/coding-problems/top-k-frequent-elements). Count, then a size-k heap keyed by count, or buckets.
  • K closest points to a location. A size-k max-heap keyed by distance; compare squared distances to avoid square roots.
  • Merge k sorted lists or files. Shape 2; the same idea merges sorted log files too big for memory.
  • Median of a stream. Shape 3.
  • Meeting rooms and task scheduling. Shape 4, or a cooldown variant where the heap holds the most frequent remaining task.
  • Cheapest route with weighted edges. Dijkstra: a heap of (distance, node), skipping stale entries; it extends the BFS in the graph traversal patterns guide to weighted graphs.

Complexity

n items, k kept or merged, N total items across lists
Operation or problemTimeExtra space
Push or popO(log n)-
Peek at the smallestO(1)-
Build a heap from a list (heapify)O(n)O(1) in place
k-th largest with a size-k heapO(n log k)O(k)
Merge k sorted listsO(N log k)O(k) plus the output
Running median per insertO(log n)O(n)
Meeting roomsO(n log n)O(n)
n items, k kept or merged, N total items across lists. Scroll sideways on a small screen.

Common mistakes

  • Using a max-heap of everything for top k. It works but costs O(n log n) time and O(n) space; a size-k min-heap is the expected answer.
  • Forgetting Python's heapq is a min-heap. Negate values for a max-heap, and remember to negate back when reading.
  • Tuples that cannot be compared. If two entries tie on the first field, Python compares the second; put an index there, not an object without ordering.
  • Treating the heap array as sorted. Only index 0 is guaranteed; the rest is partially ordered.
  • JavaScript's sort as a heap. Sorting after every insert is O(n log n) per step, which interviewers will notice.

How to explain it out loud

Fictional example

Justifying a size-k heap
Candidate
Sorting all scores and taking the k-th is n log n. I only care about the k largest at any time, so I'll keep a min-heap of size k.
Candidate
The root is the smallest of my current top k. A new score either loses to it and is ignored, or replaces it. Each replacement is log k.
Candidate
So n log k time and k extra space, and it also works if the scores arrive as a stream.

Heaps often work alongside other patterns: dynamic programming for costs that build up step by step, and graph search when edges have weights. The rest of the set is on the coding problems hub.

Practicing with Natively

In practice, Natively can read a heap problem from a screenshot on Mac or Windows and suggest which of these shapes it is, with code in the language you are using, so you can check your choice of heap size and key. A transcript of a mock round shows whether you stated the log k cost clearly. More on AI help for coding interviews.

Questions people ask

When should you use a heap in a coding interview?

When you repeatedly need the smallest or largest item while items are added or removed: top k, k closest, merging sorted lists, a running median, scheduling by earliest end, or Dijkstra's shortest paths.

Why use a min-heap to find the k largest elements?

A min-heap of size k keeps the k largest values seen so far with the smallest of them at the root. Any new value only needs comparing with the root, giving O(n log k) time and O(k) space.

Does JavaScript have a built-in priority queue?

No. Interviewers often let you assume one, but be ready to write a small array-based MinHeap with sift-up on push and sift-down on pop.

How do two heaps find a running median?

A max-heap holds the lower half and a min-heap the upper half, kept balanced in size. The median is the top of the larger heap, or the average of both tops when they are equal in size.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP