Skip to content

Software interviews

Heaps and priority queues for coding interviews, worked

A heap keeps the smallest item (or the largest) at the top, and it lets you add an item or remove the top in about log n steps. Reach for one when a problem keeps asking for the best item so far, the k best, or the next item from several sorted sources. This page gives the costs from the Python documentation and the Open Data Structures text, three patterns with worked examples, the edge cases that get tested and four original problems with checked answers.

Your first hour with George Li (60 minutes by video, $250) ends with a written plan within one working day.

Book your first hour ($250)

What a heap is and what it costs

A min-heap is a binary tree in which every parent is less than or equal to its children. The Python documentation for heapq calls this condition the heap invariant, and states the consequence: the smallest element is always the root, heap[0]. The module stores the tree in an ordinary list, so heap[0] is the smallest item, and it provides push, pop and heapify functions that keep the invariant. Popping from an empty heap raises an error, and to look at the smallest item without removing it you read heap[0].

The textbook Open Data Structures explains how a list can hold a tree. Its first heap implementation uses an array to simulate a complete binary tree, where the node at index i has its left child at 2i + 1 and its right child at 2i + 2, and its parent at (i - 1) / 2 rounded down. The book states that both adding an element and removing the smallest run in O(log n) time, because the tree is at most about log n levels tall and each operation swaps along one path from a leaf to the root or back. The Python documentation adds that heapify transforms a list into a heap in place, in linear time.

What the heap operations cost, as the sources state them
OperationPython callCost
Look at the smallest itemheap[0]O(1)
Add an itemheappushO(log n)
Remove and return the smallestheappopO(log n)
Turn a list into a heapheapifyO(n), linear time
Top k of n items with a heap of size kpush and pop n timesO(n log k), our own count

The same page has two practical notes. For the n largest or smallest items, nlargest and nsmallest are equivalent to sorting and slicing, they perform best for smaller values of n, and for larger values it is more efficient to use sorted, and for n equal to 1 it is more efficient to use min or max. And the heap holds tuples, so you can store a priority beside a record, as in (priority, task). When two entries tie on priority, Python compares the next field, which can fail for items that cannot be compared. The documentation suggests adding an entry count as a tie-breaker so that equal priorities come out in the order added.

The problem signals that call for a heap

Read the statement for the word best, with a repeated update. If the data changes and you keep asking for the best, a heap fits. If the data is fixed and you ask once, sorting is simpler.

Signals in a problem statement and the technique each calls for
Signal in the statementWhat it usually meansTechnique
"The k largest" or "k-th largest"You need rank, not full orderMin-heap of size k
"Merge k sorted lists or streams"The next item is the smallest front itemHeap of one front item per list
"Always take the smallest" or "cheapest first"A greedy choice that changes as items are addedHeap as a priority queue
"Median so far" or "running statistic"Two halves of the data, each with a boundary itemA max-heap and a min-heap
"Next event in time order"Process by earliest timeHeap keyed by time
"Schedule by priority"Highest priority first, ties by order addedHeap of (priority, count, task)

Pattern 1: keep the k best in a heap of size k

To find the k-th largest value in a stream, keep a min-heap that holds at most k values: the k largest seen so far. The top of that heap is the smallest of the k, which is the k-th largest overall. When a new value arrives, compare it with the top. If it is larger, replace the top with it; if not, ignore it. Each of n values costs at most O(log k), so the whole pass is O(n log k), which beats sorting everything when k is small. Notice that the heap is a min-heap even though the question is about the largest, because you need to know which kept value to throw away. Problem 1 is this problem on a stream of twelve values.

Pattern 2: merge sorted sources

To merge k sorted lists, put the first item of each list in a heap, tagged with which list it came from. Take the smallest, which is the next item of the merged order, and push the next item from the same list. The heap never holds more than k entries, so each of the n items costs O(log k), and the merge costs O(n log k). The same module offers a merge function that assumes each input is already sorted, and the documentation gives merging timestamped entries from several log files as its example use. Problem 2 asks for the 7th smallest value across three sorted lists, which needs only seven pops and not a full merge.

Pattern 3: always take the smallest, and two heaps for a median

Some problems repeat one step: take the smallest, do something, put a result back. Problem 3 joins ropes two at a time, where each join costs the sum of the two lengths. Joining the two shortest first is cheapest, because a rope joined early is counted again at every later join. A heap gives you the two shortest in O(log n) each time, and the whole job is O(n log n).

A running median uses two heaps. Keep the smaller half of the values in a max-heap and the larger half in a min-heap, and let the smaller half hold one value more when the count is odd. The median is then the top of the max-heap, which is the middle value for an odd count and the smaller of the two middle values for an even count, the definition problem 4 uses. After each new value, put it in the right heap, then move one value across if the sizes are out of balance. Each arrival costs O(log n) and reading the median costs O(1).

Edge cases interviewers probe

  • An empty heap. Popping raises an error in Python, so check the length first.
  • k larger than the number of items. Say what you return, and keep the heap size at the smaller of the two.
  • Ties in priority. Add a counter as a tie-breaker, as the documentation suggests, so the items themselves never need to be compared.
  • A max-heap in a min-heap library. Store negated numbers, or use the max-heap functions if your version has them, and remember to negate back.
  • Updating or removing an item that is not at the top. A heap does not support this cheaply. Mark the entry as removed and skip it when it reaches the top.
  • Duplicate values. They are fine in a heap, and they count as separate items.

A good habit is to test your solution on the smallest tricky input you can write by hand, such as three values with k equal to 2, before you call it done.

Four practice problems, in order of difficulty

These are our own practice problems, written for this site. Try each on paper first, then open the working. The set runs from the k-th largest of a stream to a running median.

Problem 1. Values arrive one at a time: 14, 3, 21, 9, 17, 5, 30, 8, 12, 26, 1, 19. What is the 4th largest value among all twelve? Give an integer.

Show the answer and the working

Answer: 19

  1. Keep a min-heap that holds at most 4 values: the 4 largest seen so far. Its top, the smallest of those 4, is the 4th largest so far. A new value larger than the top replaces the top, and a smaller value is ignored.
  2. The first four values fill it: 14, 3, 21, 9. Then 17 replaces 3, 5 is ignored, 30 replaces 9, 8 is ignored, 12 is ignored, 26 replaces 14, 1 is ignored, and 19 replaces 17.
  3. The heap ends holding 19, 21, 26 and 30, and its top is 19.
  4. Each of n values costs at most O(log k) for a heap of size k, so the total is O(n log k), better than sorting everything when k is small.

Problem 2. Three lists are each sorted from smallest to largest: 2, 9, 15, 22, 30; 4, 5, 11, 23; and 1, 8, 10, 14, 18, 40. If all their values were merged into one sorted list, which value would be 7th? Give an integer.

Show the answer and the working

Answer: 10

  1. Keep a min-heap with one entry per list: the smallest value not yet taken from it, with the list it came from. Take the top, then push the next value from the same list.
  2. The heap starts with 2, 4 and 1. Taking the top seven times gives 1 (from the third list), then 2, then 4, then 5, then 8, then 9, then 10.
  3. The 7th value taken is 10.
  4. With k lists the heap never holds more than k entries, so each of the n values costs O(log k) and the full merge costs O(n log k). Only the 7 values needed are taken here.

Problem 3. Ropes of lengths 5, 3, 8, 2, 10, 4 are joined into one rope, two at a time. Joining two ropes costs the sum of their lengths, and the joined rope can be joined again. What is the least total cost of joining all six into one? Give an integer.

Show the answer and the working

Answer: 78

  1. Always join the two shortest ropes, because a rope joined early is counted again at every later join. Keep the ropes in a min-heap so the two shortest are on hand.
  2. Join 2 and 3 for 5 (ropes now 5, 8, 10, 4, 5). Join 4 and 5 for 9 (ropes 5, 8, 10, 9). Join 5 and 8 for 13 (ropes 10, 9, 13). Join 9 and 10 for 19 (ropes 13, 19). Join 13 and 19 for 32.
  3. The costs are 5, 9, 13, 19 and 32, and they add to 78.
  4. Each of the n - 1 joins takes O(log n) heap operations, so the total is O(n log n).

Problem 4. Values arrive one at a time: 5, 15, 1, 3, 8, 7, 9, 10, 20, 2. After each arrival, the median of all values so far is noted: the middle value when the count is odd, and the smaller of the two middle values when the count is even. What is the sum of the ten medians? Give an integer.

Show the answer and the working

Answer: 57

  1. Keep a max-heap for the smaller half and a min-heap for the larger half, with the smaller half allowed one extra value. The median is the top of the smaller half. After each arrival, move one value across if the sizes get out of balance.
  2. The medians after each arrival are: 5, 5, 5, 3, 5, 5, 7, 7, 8, 7. For example after 4 values the sorted list is 1, 3, 5, 15 and the smaller middle value is 3; after 9 values the sorted list is 1, 3, 5, 7, 8, 9, 10, 15, 20 and the middle is 8.
  3. The sum is 5 + 5 + 5 + 3 + 5 + 5 + 7 + 7 + 8 + 7 = 57.
  4. Each arrival costs O(log n) and reading the median costs O(1), so the whole stream is O(n log n), against O(n^2 log n) if every prefix were re-sorted.

Every answer above is recomputed by a separate program when the site is built, and each is rebuilt by a different route from the written steps. A wrong answer would stop the build. Read how the problems are checked.

These are our own practice problems, written for this site. If you have signed an agreement about an assessment, keep its contents to yourself, including in a coaching session.

A longer ladder of heaps problems

Four worked problems are a start, and a longer list is worth having for the weeks before an interview. The table sorts 17 problem types that interviewers often use for heaps into three sets, with what each set trains. A coaching company that publishes a large question list on this topic sorts its own list by the stage where such questions tend to turn up: simpler ones on a phone screen, harder ones on a video call or onsite round, where you may get more time. We keep that idea and describe each type in our own words.

Heaps problem types in three sets, with a count of each
SetTypesProblems to look upWhat the set trains
Easy3the k-th largest value in a stream; last stone weight; the weakest rows of a matrixA heap as a running best-so-far
Medium8meeting rooms needed at once; the k most frequent items; the k-th smallest value in a sorted grid; task scheduling with a cooling gap; the k closest points; rearranging a string so no letters touch; the k smallest pair sums; the least effort pathA heap as a priority queue inside a greedy or shortest-path step
Hard6the skyline of a set of buildings; the median of a data stream; the smallest range that covers every list; hiring k workers at the lowest cost; the fewest refueling stops; a team with the best performanceTwo heaps, or a heap with lazy deletion, around a sorted order

Do not try to read every solution. New questions appear every season, so the aim is to own the pattern behind a set, not the answer to each item. For each problem, set a timer, write your own attempt with no reference, and only then read a solution. When you get stuck, look at one solution, close it and redo the problem from a blank page the next day. A pile of read solutions teaches far less than a few redone from memory.

Say which kind of heap you hold and what each entry contains before you push anything. Libraries differ: some give a min-heap only, which is why a max-heap is often built by negating values. A heap does not search or remove from the middle cheaply, so when a problem seems to need that, say how you would skip stale entries.

A short routine to practice

  1. Ask whether the best item changes as you go. If it does, a heap fits.
  2. Say whether it is a min-heap or a max-heap and what each entry holds.
  3. State the cost: O(log n) per push or pop, and the size the heap reaches.
  4. Say what breaks ties.
  5. Trace the first three pushes and pops by hand.

Questions

What does a heap cost for each operation?

Looking at the smallest item is O(1) because it sits at the root. Adding an item or removing the smallest is O(log n), per the Open Data Structures text, and the Python documentation says heapify builds a heap in linear time.

How do I get a max-heap in Python?

The heapq module is a min-heap, and its documentation says textbooks often focus on max-heaps while this implementation favors min-heaps. Recent versions list max-heap functions, and a common workaround on older ones is to store negated values.

When is a heap better than sorting?

Use a heap when you need only the top k items or a running best, because a heap of size k costs O(n log k) over n items. Sort when you need the whole order.

How a session helps

A session with George is a place to code a problem aloud and have the reasoning questioned: why a min-heap for the largest values, what each entry holds and how ties are broken. You write all the code yourself. Next, read the data structures checklist and the coding and complexity practice, and use the coding prep schedule to put the topics on a calendar. See the packages page for the sessions, or book a session.

Want help with your own applications? See internship interview coaching, a career coach for college internships, or resume review for internships.

Start with one hour

  • Your first purchase is refundable for unused time within 7 days. Nothing renews. Refund terms