What is a Heap, and how is it used in algorithm design?

Instruction: Discuss the structure of a Heap and its role in efficient algorithm implementation.

Context: This question probes the candidate's understanding of Heaps, focusing on their structure and applications in algorithms, such as priority queues.

Updated

Official answer

A binary min-heap is a complete binary tree whose parent key is no greater than either child's key. Its array representation puts the minimum at index zero, but does not sort the entire array. A max-heap reverses the comparison.

For a binary heap, peek is O(1), insertion and removal of the root are O(log n), and bottom-up heap construction is O(n), under the usual comparison model. It supports priority queues, repeated top-k selection and shortest-path frontiers.

Equal priorities are not automatically served in arrival order. In Python, add a monotonically increasing tie-breaker when that behavior is required:

from heapq import heappush, heappop
from itertools import count

queue = []
sequence = count()
heappush(queue, (2, next(sequence), 'first'))
heappush(queue, (2, next(sequence), 'second'))
first_task = heappop(queue)[2]  # 'first'

The unique sequence also avoids comparing task objects when priorities tie. Updating a priority or deleting an arbitrary task requires an additional strategy, such as an index map or lazy removal; it is not the same as removing the root. Define empty-queue behavior and account for retained stale entries if using lazy removal.

Related Questions