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:
heapqis a set of functions on a plain list and is a min-heap only; negate keys for a max-heap (or use the_maxfunctions 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.