Skip to the solution
MediumDSA15 min read

What is a heap / priority queue?

711 views

The problem

Question presented to candidate: "What is a heap, and what is a priority queue? Explain how a binary heap is laid out, how push and pop work and what they cost, and show me how you would use one in Python โ€” and how you would build one yourself if the library did not exist."

What a strong answer should cover:

  • A priority queue is the abstract type (insert, peek best, remove best); a binary heap is the usual implementation: a complete binary tree stored in a list.
  • The two rules (complete shape, parent โ‰ค child) and the index arithmetic: parent (i โˆ’ 1) // 2, children 2i + 1 and 2i + 2.
  • Push = append + sift up, pop = move last to root + sift down, both O(log n); peek O(1); bottom-up heapify O(n).
  • A heap is only partly sorted: the root is the minimum, siblings are in no order, and popping everything gives heap sort.
  • Python specifics: heapq is a set of functions on a plain list and is a min-heap only; negate keys for a max-heap (or use the _max functions added in Python 3.14); push (priority, counter, item) tuples so ties never compare the items.

Code / implementation expected: Optional โ€” be ready to write push and pop with sift up / sift down on a Python list, and to use heapq fluently.

  • heap
  • priority-queue

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

15 min read ยท 13 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonA min-heap from scratch: push, sift up, pop, sift down
PythonHeapify vs n pushes (comparisons counted) and the built-in priority queue

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 71 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you rotate an Nร—N matrix by 90 degrees in place?

Continue