- Learn
- Computer Science & IT
- Programming
- Data Structures and Algorithms
- Heaps and Priority Queues
Heaps and Priority Queues
IntermediateLesson 7 of 10 in Data Structures and Algorithms Course
What you will learn
- Describe the operations of a priority queue, tell it apart from ordinary queues and stacks, and compare the costs of simple implementations with a binary heap.
- Describe the priority queue operationsState what a priority queue stores, which operations it offers, and what it does and does not promise about order.
- Compare simple implementations with a binary heapWork out the cost of each priority queue operation for unsorted arrays, sorted arrays, balanced search trees and binary heaps, and choose an implementation for a workload.
- Describe the priority queue operations
- Recognize the shape and order rules that make a tree a binary heap, and store and navigate that tree in an array with index arithmetic.
- Recognize complete trees and the heap propertyCheck the shape rule and the order rule of a binary heap and state what they imply about where items are.
- Move between tree positions and array indexesStore a complete tree level by level in an array, compute parent and child indexes with 0-based and 1-based formulas, and check whether an array is a heap.
- Recognize complete trees and the heap property
- Restore the heap property after inserting, extracting, changing or removing items, implement these operations in Python, and use the heap tools in the Python and Java standard libraries.
- Insert an item with sift upAdd an item at the end of the array and move it up past larger parents until the heap property holds again, and explain why this takes logarithmic time.
- Remove the top item with sift downExtract the minimum by moving the last item to the root and pushing it down past smaller children, handling nodes with one child and empty heaps.
- Change or remove an item inside the heapUpdate an item's priority or remove an item from the middle of a heap with an index map, and use lazy deletion when no index map is kept.
- Use heapq in Python and PriorityQueue in JavaApply Python's heapq functions correctly, build max-heaps and stable priority queues with tuples and counters, and use Java's PriorityQueue.
- Insert an item with sift up
- Turn an unordered array into a heap bottom-up, prove why this takes linear time, and sort in place with heap sort.
- Build a heap bottom-up in linear timeTurn an unordered array into a heap by sifting down from the last internal node to the root, and explain why the total work is linear.
- Sort an array in place with heap sortSort ascending with a max-heap inside the array itself, trace the algorithm, and compare heap sort's time, space and stability with other sorting algorithms.
- Build a heap bottom-up in linear time
- Recognize problems where a heap gives the efficient solution, including keeping the best k items, merging sorted data, tracking a running median and scheduling tasks and events.
- Find the k largest or smallest itemsKeep the k best items of a large collection or stream with a heap of size k, and compare this with sorting, full heapify and selection.
- Merge k sorted sequencesMerge several sorted lists or streams into one sorted output with a heap holding one item per list.
- Keep a running median with two heapsReport the median of a growing stream after every new number by balancing a max-heap of the lower half against a min-heap of the upper half.
- Schedule tasks and events by priority or timeUse a priority queue to process tasks by urgency, run a time-ordered event simulation, count the rooms a set of meetings needs and spread jobs across machines.
- Find the k largest or smallest items
Heaps and Priority Queues study guide
1Explain what a priority queue does and how it can be built
A priority queue answers a recurring question: which waiting item should go next? Its interface leaves room for several implementations, each with different costs. Connect insert, peek, and extract to the ordering rule, then compare arrays, search trees, and heaps against a workload. The useful choice depends on how often the program adds work, removes work, or needs all items in order.
1.1 How a priority queue chooses the next item
A priority queue stores items with keys that decide which item is served next. It is an abstract data type: the operations describe behavior, while an implementation decides how to deliver it efficiently. A binary heap is one implementation.
Decide what "next" means
A min-priority queue returns a smallest key. A max-priority queue returns a largest key. For a support system where priority 1 is most urgent, the min-oriented version serves priority 1 before priority 5. The word "priority" alone does not tell you which numeric direction wins.
| Operation | Effect |
|---|---|
| Insert, push, or offer | Add an item and its key. |
| Peek, find-min, or find-max | Read the top item without removing it. |
| Extract, pop, or poll | Remove and return the top item. |
| Size or is-empty | Report how many items remain or whether any remain. |
Some interfaces also build a queue from a collection, change an item's priority, or remove a named item. Those extra operations need implementation support; fast access to the top does not provide fast access to every item.
Trace the operations
Start with an empty min-priority queue. Insert 5, then 2, then 8. Extract returns 2 and leaves 5 and 8. Insert 1. Peek returns 1, and the size stays 3 because peek removes nothing. Extract now returns 1; another extract returns 5. Only 8 remains, so the size is 1.
This trace describes results, not a required storage layout. The queue may rearrange items whenever it needs to preserve its promises. Printing a heap's underlying array generally shows neither insertion order nor sorted order. To consume everything in priority order, repeatedly extract.
An empty queue has no top item. Python's heapq.heappop raises IndexError; Java's PriorityQueue.poll returns null. Check emptiness when draining a queue, and use the documented empty-case behavior when writing a function that removes one item.
Make ties explicit
Equal keys do not promise equal-priority items will leave in arrival order. If that order matters, attach an increasing arrival counter and compare (priority, arrival_number). The priority is compared first; the counter settles equal priorities. A unique counter also prevents the comparison from reaching a payload that has no ordering, such as a dictionary.
Arrival order itself can be the priority rule. Choosing the earliest arrival produces FIFO queue behavior; choosing the latest produces stack behavior. For ordinary FIFO work, a normal queue gives the needed operations directly. A priority queue is useful when urgency, a deadline, or another changing key decides the next item.
A simulation uses event times as keys. A top-k algorithm uses scores, and a merge uses the next value from each input. The common feature is repeated access to an extreme item while the waiting collection changes.
Key Takeaways
- A min-priority queue serves a smallest key; a max-priority queue serves a largest key.
- Peek leaves the item in place; extract removes it.
- An increasing arrival counter gives equal-priority items FIFO order.
- The interface promises the next item, not sorted storage.
- Handle the empty case according to the chosen API.
1.2 Choose a structure for the workload
Different data structures can provide the same priority queue behavior. Compare their costs using the operations your program actually performs. Here, is the number of stored items, and the queue is min-oriented.
Compare the main choices
| Implementation | Insert | Peek minimum | Extract minimum | Main trade-off |
|---|---|---|---|---|
| Unsorted dynamic array | amortized | Cheap additions, repeated scans. | ||
| Array sorted decreasingly | Minimum at the end; insertion shifts items. | |||
| Balanced search tree | Also supports search and ordered traversal. | |||
| Binary heap | amortized | Compact array, fast mixed updates. |
A balanced tree can make peek constant-time by caching a pointer to its minimum. Heap insertion's amortized qualification accounts for occasional dynamic-array resizing; the sift itself follows a logarithmic path.
For an unsorted array, extract scans for the minimum. Once its index is known, move the last item into that gap and pop the end; there is no need to shift the whole suffix. The scan still dominates the operation.
For a sorted array, binary search finds an insertion position in logarithmic time, but opening that position takes linear time. Finding a slot quickly does not remove the cost of shifting. A sorted linked list has a related trade-off: constant-time extraction at the head, but a linear walk to find an insertion point.
Choose for the workload
Suppose a program collects measurements and asks for the minimum once at the end. Append them to a list and scan once. Paying for a heap repair at every addition brings no useful benefit. If all data is available and every item is needed in order, sorting once is a direct solution.
A service that repeatedly receives new jobs and dispatches the best waiting job has interleaved inserts and extracts. A binary heap supports both without rescanning or shifting the entire collection. At one million items its tree height is 19: a sift up uses at most 19 swaps, while a standard sift down uses at most 38 key comparisons. An unsorted-array extract examines one million entries.
Connect priority queues to sorting
Insert all items, then extract until empty. An unsorted-array implementation repeatedly selects a minimum, giving selection-sort behavior and work. Maintaining a sorted array during insertion gives insertion-sort behavior, also quadratic. A binary heap gives sorting.
This connection rules out a comparison-based priority queue with both constant-time worst-case insertion and constant-time worst-case extraction. Those two guarantees would sort arbitrary comparable keys in linear total time, contradicting the comparison-sorting lower bound. The argument concerns comparison-based methods; it does not apply unchanged to restricted integer-key techniques.
Other heap families include d-ary, binomial, pairing, and Fibonacci heaps. They offer different trade-offs for operations such as merging and priority changes, with more implementation machinery.
Key Takeaways
- Count the operations in the workload before choosing a structure.
- Binary search does not eliminate a sorted array's linear shifting cost.
- A binary heap balances frequent inserts and extracts with logarithmic repairs.
- Priority queue sorting connects operation costs to the comparison-sorting lower bound.
2Represent a binary heap as an array
A binary heap combines two rules: a complete tree shape and an order rule between parents and children. The complete shape lets a plain array store the tree without pointers. Learn to read that array as levels, locate relatives by index, and check the heap property. These details explain both why the root is immediately useful and why searching elsewhere is still expensive.
2.1 The two rules of a binary heap
A binary heap needs both a shape rule and an order rule. Keeping one while breaking the other is not enough. The shape controls height and storage; the order makes an extreme item easy to reach.
Recognize the complete shape
A complete binary tree fills every level except possibly the last. The last level fills from left to right with no gaps. Adding one node therefore has a single permitted position: the next slot on that last level, or the first slot of a new level.
| Tree term | Requirement |
|---|---|
| Complete | All earlier levels filled; last level filled from the left. |
| Full | Every node has either zero or two children. |
| Perfect | Every level filled completely. |
A complete tree may have a node with just a left child, so completeness does not require fullness. A perfect tree of height has nodes. Height counts edges: a one-node tree has height 0.
For any nonempty complete tree, height is . Seven nodes fit in height 2; the eighth starts height 3. A tree with one million nodes has height 19. Depth can hold at most nodes, which explains why adding a level roughly doubles capacity.
Check parent–child order
A min-heap requires every parent key to be at most each child key. A max-heap reverses that inequality. Equal values are allowed; duplicates do not need special positions.
The local rule extends along every downward path. In a min-heap, a node is no greater than any descendant, so the root is a smallest item in the entire tree. Peek only reads that root and takes time.
Consider a root 1 with children 5 and 2, plus a child 9 below the 5. The tree is complete and every edge obeys parent-at-most-child. It is a valid min-heap even though the right child 2 is smaller than the left child 5. There is no required comparison between siblings.
Know what partial order leaves unknown
A binary search tree partitions left and right subtrees around a node's key. A heap compares parents with children instead. Searching for 6 in a min-heap cannot follow a single left-or-right choice: either subtree may contain it. A plain heap's arbitrary search is therefore linear in the worst case.
A nondecreasing array read in level order is a min-heap, but a min-heap array can have many rises and falls. Several valid arrays may represent the same multiset of keys. Judge them by the edge rule, not by whether they match one preferred arrangement.
After choosing one smallest item as the root, a second-smallest item can be found among its children. More generally, some occurrence of a k-th-smallest value lies at depth at most : too many strictly smaller ancestors would put it later in the ordering. Duplicates mean equal values can also appear deeper. A maximum occurs at a leaf, though an equal maximum may also appear internally. Finding that maximum still requires examining about half the nodes in the worst case.
Key Takeaways
- A heap satisfies complete shape and parent–child order.
- Equal keys and unordered siblings are allowed.
- The root is a minimum in a min-heap; arbitrary searches can still be linear.
- A complete tree has logarithmic height, measured in edges.
- Complete, full, and perfect describe different shape properties.
- A valid heap array need not be sorted or uniquely arranged.
2.2 Read array positions as a tree
Store a complete tree in level order: root first, then each level from left to right. Because no positions are missing, a list of items represents exactly the occupied part of the tree. Parent and child links come from indexes, so no node pointers are needed.
Use one index convention
| Relative | Root at index 0 | Root at index 1 |
|---|---|---|
Left child of i | 2*i + 1 | 2*i |
Right child of i | 2*i + 2 | 2*i + 1 |
Parent of non-root i | (i - 1) // 2 | i // 2 |
Python lists and heapq use the 0-based column. Some textbooks leave index 0 unused and use the 1-based column. Mixing them makes the root at index 0 its own left child, which is a sign that the formulas do not match the representation.
A computed child exists only when its index is less than the heap size. The root has no parent, so use the parent formula only after checking i > 0. Python's / returns a floating-point value; the // in these formulas performs integer division and produces an integer index.
Read an array as a tree
For [2, 5, 3, 9, 6, 4, 8], index 0 holds root 2. Indexes 1 and 2 hold its children 5 and 3. The children of index 1 are indexes 3 and 4, holding 9 and 6. The children of index 2 are indexes 5 and 6, holding 4 and 8.
To find the parent of index 6, calculate (6 - 1) // 2, which is 2. That parent holds 3. To find the children of index 3, calculate 7 and 8. Both fall outside a seven-item heap, so index 3 is a leaf.
With 0-based indexing, leaves occupy n // 2 through n - 1; the last internal node is n // 2 - 1. When n = 7, indexes 0–2 are internal and 3–6 are leaves. The depth of index is . For an empty array there are no nodes, and for a one-item array the root is also a leaf.
Check order in one pass
The dense list already supplies a complete shape. To validate a min-heap, check each non-root item against its parent:
def is_min_heap(a):
return all(a[(i - 1) // 2] <= a[i]
for i in range(1, len(a)))
The seven-item array above passes. [2, 5, 3, 4, 6] fails at index 3: its parent at index 1 holds 5, which is greater than 4. Checking only that the root is smallest misses this violation below the root. The complete check takes time.
The next insertion goes at index n, keeping the array dense. Removing the last position is also cheap. Insertion uses that end position directly; extraction uses its value to fill the root before repairing order.
Key Takeaways
- Level-order storage turns tree links into index arithmetic.
- In a 0-based heap, children are
2*i + 1and2*i + 2. - Check bounds before reading children and use
//for parent indexes. - Check every parent–child edge to validate a heap.
- Leaves begin at
n // 2; heap construction starts just before them.
3Keep a heap in order as it changes
Heap updates preserve the complete shape while repairing order along one path. Follow an inserted item upward and a replacement root downward, then extend those repairs to priority changes and removal. Library functions package the same ideas, but their return values, tie handling, and update rules still matter. Trace the changing indexes before translating each operation into code.
3.1 Append an item and sift it up
An insertion changes the complete tree in exactly one place. Append the new item to the end of the array, then repair the path from that item toward the root. This repair is sift up, also called swim, bubble up, or percolate up.
Follow the new item
In a min-heap, compare the new item with its parent. If the item is smaller, swap them and continue from the parent's index. Stop at the root or when the parent is no greater than the item. Equality already satisfies the heap property, so equal values need no swap.
def push(a, item):
a.append(item)
i = len(a) - 1
while i > 0:
p = (i - 1) // 2
if a[p] <= a[i]:
break
a[i], a[p] = a[p], a[i]
i = p
The root check comes before computing or using a parent. After each swap, i = p follows the inserted item. Forgetting that assignment keeps checking the old position and can stop the repair too soon.
Work through an insertion
Insert 1 into [2, 5, 3, 9, 6, 4, 8].
- Append at index 7:
[2, 5, 3, 9, 6, 4, 8, 1]. Its parent is index 3, holding 9. - Swap 1 with 9:
[2, 5, 3, 1, 6, 4, 8, 9]. The new index of 1 is 3; its parent is index 1, holding 5. - Swap 1 with 5:
[2, 1, 3, 5, 6, 4, 8, 9]. Now compare index 1 with root 2. - Swap again:
[1, 2, 3, 5, 6, 4, 8, 9]. The inserted item reaches the root after three swaps.
The same initial heap with an inserted 10 needs no swap: it goes below 9, and 9 is already smaller. A heap update does not need to visit every node simply because the collection is large.
Explain why one path is enough
Before insertion, all existing edges were ordered. Appending adds a leaf, so only its edge to its parent can fail. When the new value rises, the old parent moves downward. That parent was already no greater than the older descendants below it, so moving it down preserves their order. Any remaining violation stays between the new value and its next parent.
For a max-heap, reverse the comparison: a new value rises while larger than its parent. The shape and index arithmetic stay the same.
A heap with items has height . Each sift step crosses one edge, so the worst-case sift costs time and constant auxiliary space. The best case stops after one comparison. Dynamic-array append is amortized constant time, making insertion amortized logarithmic overall.
Do not insert at the front of the list. Prepending shifts every old index, changes parent–child relationships throughout the tree, and costs linear time. Appending preserves those relationships and confines the repair to one ancestor path.
Key Takeaways
- Append at the end to preserve the complete shape.
- Sift up swaps a min-heap item past larger parents.
- Update the current index after each swap; stop at the root or an ordered edge.
- Only the inserted item's ancestor path needs repair.
- The sift is logarithmic; dynamic-array insertion has an amortized bound.
3.2 Replace the root and sift it down
The minimum is easy to read at the root, but removing it must leave a complete tree. Fill its position with the last item, shorten the array, and repair downward. Sift down is also called sink, bubble down, or percolate down.
Choose the smaller child
At each position in a min-heap, find the smaller existing child. If that child is smaller than the current item, swap and follow the displaced item downward. Stop at a leaf or when neither child is smaller.
Suppose the current item is 9 and its children are 3 and 2. Swapping with 2 puts 2 above both 3 and 9. Swapping with 3 leaves 3 above 2, so the heap property would still fail at the position just repaired. Child selection is part of correctness.
def sift_down(a, i, n):
while 2 * i + 1 < n:
child = 2 * i + 1
right = child + 1
if right < n and a[right] < a[child]:
child = right
if a[i] <= a[child]:
break
a[i], a[child] = a[child], a[i]
i = child
def pop_min(a):
if not a:
raise IndexError("pop from empty heap")
result = a[0]
last = a.pop()
if a:
a[0] = last
sift_down(a, 0, len(a))
return result
The left child can exist without a right child, so the right index gets its own bounds check. Removing the final item leaves an empty list; the guard avoids writing a new root into that empty list.
Trace an extraction
Start with [1, 2, 3, 5, 6, 4, 8, 9] and save 1. Move the last item 9 to the root and shrink, giving [9, 2, 3, 5, 6, 4, 8].
The root's smaller child is 2. Swap to get [2, 9, 3, 5, 6, 4, 8]. At index 1, the children are 5 and 6, so swap with 5: [2, 5, 3, 9, 6, 4, 8]. Index 3 has no child inside the seven-item array. Stop and return the saved 1.
The returned value is the old root, not the value now at the root. Peek reads that new root without changing anything.
Use the repair beyond the root
Sift down works at any index whose two child subtrees are already heaps. Picking the smaller child establishes order at the current position; only the subtree receiving the larger displaced item can still need repair. This requirement is why bottom-up construction processes children before parents.
A sift crosses at most the tree height. With up to two key comparisons per level, extraction costs time and iterative sift down uses extra space. A one-item heap needs no sift at all.
Removing the first list element with a.pop(0) shifts the remaining array in linear time and changes all tree positions. Filling the root from the end preserves the shape without shifting the other items.
Key Takeaways
- Save the root, fill it from the last position, and shrink before repairing.
- Swap with the smaller existing child in a min-heap.
- Check the right child separately because a left-only node is possible.
- Return the saved old root.
- Sift down needs heap-ordered child subtrees.
- Empty and one-item heaps require explicit handling.
3.3 Update and remove named items
A heap locates its root immediately, but it has no fast route to a named item. Finding an arbitrary item in a plain heap can take time. Efficient priority updates therefore need a way to locate the item as well as a way to repair its position.
Keep an index map
An indexed heap adds a dictionary from each unique item ID to its array index. Every swap updates the dictionary for both moved items. Use stable identities: two tasks may share a priority, so the priority itself cannot identify a task.
For a min-heap, a decreased key may violate the edge to its parent, so sift up. An increased key may violate edges to children, so sift down. With an index map, lookup and the logarithmic repair give expected time using a hash dictionary. If the key stays equal, no repair is needed.
In [2, 5, 3, 9, 6, 4, 8], decrease 9 at index 3 to 0. It swaps past 5 and then 2, producing [0, 2, 3, 5, 6, 4, 8]. In the original heap, increasing 5 to 7 instead swaps it with child 6, producing [2, 6, 3, 9, 7, 4, 8]. Reverse these directions for a max-heap.
Remove an item from the middle
Move the last item into the removed item's slot and shrink the heap. Compare the replacement with its parent: if it is smaller in a min-heap, sift up; otherwise sift down. Removing the last slot needs no replacement. Also remove the deleted ID from the map and record the replacement's new index before repairing.
Removal does not always sift down. From [1, 10, 2, 11, 12, 3, 4], remove 11 at index 3. The final 4 fills its slot, giving [1, 10, 2, 4, 12, 3]. Since 4 is smaller than parent 10, it rises to produce [1, 4, 2, 10, 12, 3]. A downward-only repair would miss the violation.
Leave cancelled entries until later
Lazy deletion is an alternative when maintaining an index map is inconvenient. Keep a dictionary from task ID to its live entry. To cancel a task, mark that entry stale and remove its live dictionary mapping. To change priority, mark the old entry and push a new entry with the new priority.
Extraction repeatedly pops until it reaches a live entry. Peek also has to discard stale entries at the root before reporting the next live item. A removed marker belongs in the payload; changing a comparison key in place could break the heap ordering. A unique counter before the payload prevents payload comparisons.
Stale entries still occupy space. Let count all physical heap entries, including stale ones. Each push or pop costs , and finding one live item may require several pops. Each stale entry is discarded once, so cleanup can be charged to the earlier operations that created it. It is not a logarithmic worst-case guarantee for each logical extraction. The approach works especially well when cancellations are uncommon.
Key Takeaways
- Use unique item IDs and update the index map after every swap.
- In a min-heap, decreasing a key sifts up; increasing it sifts down.
- Arbitrary removal may need either direction of repair.
- Lazy deletion marks old entries and skips them when they reach the top.
- Lazy-deletion costs depend on physical heap size, including stale entries.
3.4 Use the heap library correctly
Python's heapq functions maintain a min-heap inside an ordinary list. They provide the repairs, but the caller still chooses valid keys, initializes the heap, and handles ties and empty inputs.
Build and use a heap
import heapq
h = [7, 2, 6]
heapq.heapify(h)
heapq.heappush(h, 4)
smallest = heapq.heappop(h) # 2
next_value = h[0] # 4
heapify mutates its argument in time and returns None. Writing h = heapq.heapify(h) loses the list reference. An empty list is already a heap; repeated heappush calls can build it without a separate heapify. An arbitrary nonempty list needs heapification before heap operations. The functions do not validate every edge for you.
| Combined operation | Meaning | Empty heap |
|---|---|---|
heappushpop(h, x) | Push, then remove a minimum. | Returns x; heap stays empty. |
heapreplace(h, x) | Remove old minimum, then push. | Raises IndexError. |
With [2, 5, 3] and incoming 1, push-pop returns 1 and keeps the old heap. Replacement returns 2 and retains 1. Replacement always admits the incoming item, so a bounded top-k algorithm must test whether that item deserves admission first.
Select maximum values and settle ties
For numeric max-priority behavior on Python versions before 3.14, store negated keys. Pushing -9 makes priority 9 come before priority 4 stored as -4; negate the popped key again when returning it. Python 3.14 added heapify_max, heappush_max, heappop_max, heappushpop_max, and heapreplace_max for direct max-heap operations.
Tuples compare from left to right. (priority, task) may compare tasks when priorities tie. If tasks are dictionaries, that can raise TypeError; if tasks are strings, it gives alphabetical tie order. Use an increasing unique counter for FIFO ties:
from itertools import count
counter = count()
h = []
heapq.heappush(h, (2, next(counter), {"name": "email"}))
heapq.heappush(h, (2, next(counter), {"name": "invoice"}))
priority, order, task = heapq.heappop(h)
The counter settles the comparison before Python reaches the dictionaries, and the email task leaves first.
Match the library to the job
Iteration over the list gives heap order. Repeated pops give sorted output while consuming the heap; sorted(h) returns an ordered copy. nlargest and nsmallest select top-k items, and merge lazily merges already sorted iterables. queue.PriorityQueue adds a thread-safe put/get interface for communication between threads.
Java's java.util.PriorityQueue serves the least item under its natural order or supplied comparator. Comparator.reverseOrder() gives numeric max-priority behavior. offer and poll are logarithmic; peek and size are constant-time; contains and remove(Object) are linear. poll returns null on empty, stored null elements are forbidden, ties are arbitrary, and iteration is not priority ordered.
Key Takeaways
heapifychanges a list in place and returnsNone.- Push and pop require a list that already obeys the heap invariant.
- Push-pop and replacement differ in whether the incoming item must remain.
- Use
(priority, counter, task)for FIFO ties and non-comparable payloads. - Negated numeric keys support max-priority behavior across Python versions.
- Python 3.14 adds direct max-heap functions.
- Neither Python heap-list iteration nor Java priority queue iteration gives sorted order.
4Build a heap in linear time and sort with it
Having all items available changes how a heap should be built. Bottom-up construction repairs small subtrees first and reaches the root with only linear total work. Heap sort then repeatedly moves an extreme item into its final position. Track the boundary between the active heap and the sorted suffix to explain its time bound, constant extra space, and lack of stability.
4.1 Build from the leaves toward the root
When all items are available, bottom-up heap construction builds a heap in linear time. Floyd's method, introduced in 1964, treats the array as a complete tree and repairs child subtrees before their parents.
Start with the smallest subtrees
Leaves already satisfy the heap property: they have no child edges to violate it. The last internal node is n // 2 - 1. Sift down from there, then work backward to index 0.
def build_min_heap(a):
for i in range(len(a) // 2 - 1, -1, -1):
sift_down(a, i, len(a))
Here sift_down uses the smaller child. When processing index i, both child subtrees have already become heaps. Sifting makes the whole subtree at i a heap, preserving that condition for its parent.
Follow the bottom-up trace
Build from [15, 8, 12, 3, 10, 6, 1, 7, 4, 2].
- Index 4: swap 10 with its only child 2, giving
[15, 8, 12, 3, 2, 6, 1, 7, 4, 10]. - Index 3: 3 is below both children 7 and 4 in key value, so leave it.
- Index 2: swap 12 with 1, giving
[15, 8, 1, 3, 2, 6, 12, 7, 4, 10]. - Index 1: swap 8 with 2, giving
[15, 2, 1, 3, 8, 6, 12, 7, 4, 10]. - Index 0: 15 swaps with 1 and then 6, producing
[1, 2, 6, 3, 8, 15, 12, 7, 4, 10].
This takes five swaps. Repeated insertion on the same input gives [1, 2, 3, 7, 4, 12, 6, 15, 8, 10] after 12 swaps. Different arrays can both be correct heaps.
Add work by height
Multiplying by the largest possible sift length gives a valid but loose upper bound. Most nodes cannot sift that far. About half are leaves, about a quarter have height 1, and about an eighth have height 2. Only a few nodes can take long paths.
For a perfect 15-node tree, the total available downward distance is
The decreasing node counts outweigh the increasing heights. The weighted series gives a constant factor times , hence linear construction. More exactly, the sum of node heights in a complete tree is , where popcount counts binary 1 bits. It is less than , so the standard sift makes fewer than swaps and fewer than key comparisons.
At one million nodes the swap bound is 999,993. Worst-case repeated insertion can use 17,951,445 swaps, because decreasing inputs make each arriving value climb toward the root.
Avoid the wrong direction
Sifting down from the root first does not establish the needed child-subtree condition. On [5, 4, 3, 2, 1], processing indexes 0 and then 1 gives [3, 1, 5, 2, 4], with 3 above 1. Left-to-right sift up is valid, but it is repeated insertion with logarithmic worst-case work per added item.
Key Takeaways
- Process internal nodes from
n // 2 - 1back to 0. - Each sift begins with heap-ordered child subtrees.
- Charge work by node height: most nodes can move little or not at all.
- Bottom-up construction takes linear time, despite a logarithmic root sift.
- Repeated insertion is valid but has a worse worst-case construction bound.
4.2 Grow a sorted suffix with heap sort
Heap sort uses the array itself for both the heap and the final result. For ascending order, build a max-heap. Repeatedly place its maximum at the end of the active heap, then repair the shortened heap.
Track the moving boundary
Let end be the size of the active heap. The prefix a[0:end] contains the remaining unsorted items in heap order. The suffix a[end:] contains the largest items in their final ascending positions.
Swap the root with index end - 1, decrease end, and sift down inside the prefix only. The saved maximum is no smaller than anything still in the heap and belongs immediately before the existing sorted suffix.
def sift_down_max(a, i, n):
while 2 * i + 1 < n:
child = 2 * i + 1
right = child + 1
if right < n and a[right] > a[child]:
child = right
if a[i] >= a[child]:
break
a[i], a[child] = a[child], a[i]
i = child
def heap_sort(a):
n = len(a)
for i in range(n // 2 - 1, -1, -1):
sift_down_max(a, i, n)
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift_down_max(a, 0, end)
The end passed to sift down excludes the newly placed maximum. Passing the original n would bring sorted values back into the heap.
Sort five items
Start with [4, 10, 3, 5, 1]. Bottom-up construction gives [10, 5, 3, 4, 1].
- Move 10 to index 4 and repair:
[5, 4, 3, 1, 10]. - Move 5 to index 3 and repair:
[4, 1, 3, 5, 10]. - Move 4 to index 2 and repair:
[3, 1, 4, 5, 10]. - Move 3 to index 1:
[1, 3, 4, 5, 10].
The heap shrinks from five items to one while the suffix grows. A min-heap with the same end-swapping procedure gives descending order. An in-place reversal would then give ascending order with constant extra space, but a max-heap avoids that extra pass.
Judge time, memory, and stability
Building costs . The remaining rounds each cost at most , so the worst-case bound is . Iterative sift down needs only a few variables, giving extra memory.
Heap sort is not stable. With records [(2, 'a'), (2, 'b'), (1, 'c')] compared only by their numeric key, end swaps can leave 'b' before 'a'. Comparing entire tuples would add a different ordering rule and would not demonstrate stability by numeric key alone.
| Algorithm | Worst-case time | Typical extra array space | Stable? |
|---|---|---|---|
| Heap sort | No | ||
| Merge sort on arrays | Yes, with stable merging | ||
| Basic quicksort | Depends on recursion | Usually no |
Quicksort often benefits from better cache locality. Heap sort jumps between distant parent and child indexes. Introsort starts with quicksort and switches to heap sort when recursion becomes too deep, combining practical speed with a worst-case bound.
Heapifying a Python list and popping into a new list also sorts in , but uses output storage. Stopping after extractions gives a partial sort in time.
Key Takeaways
- Ascending in-place heap sort uses a max-heap.
- Keep sift down inside the shrinking active prefix.
- Bottom-up build is linear; repeated removals set the total logarithmic factor.
- Iterative heap sort uses constant extra space.
- Equal-key records can change order, so heap sort is not stable.
- Popping into a new list uses output storage and is a different space arrangement.
5Solve top-k, merging and scheduling problems with heaps
A useful heap often stores only the information needed to decide the next step: the weakest retained score, one candidate per sorted input, the two middle boundaries, or the earliest finishing room. Match that decision to a min- or max-heap. Each application has its own invariant, so work through the update rule and its costs before choosing a library shortcut.
5.1 Retain the best few stream items
A top-k problem asks for the best few items, often while a stream is still arriving. Keeping everything sorted stores more order than the problem needs. A bounded heap keeps the retained candidates and exposes the one most likely to be replaced.
Keep the k largest with a min-heap
Use a min-heap with at most items. Before it fills, push every arrival. After it fills, the root is the smallest retained value: the admission threshold. A larger arrival replaces that root; a smaller or equal arrival can be skipped when only values matter.
import heapq
def top_k(values, k):
if k <= 0:
return []
h = []
for x in values:
if len(h) < k:
heapq.heappush(h, x)
elif x > h[0]:
heapq.heapreplace(h, x)
return sorted(h, reverse=True)
The final sort orders the retained results and costs . If only membership or the k-th-largest value is needed, omit that sort. Once at least values have arrived, h[0] is the k-th largest, counting duplicates. With fewer arrivals, a k-th-largest value does not yet exist.
For the stream 7, 2, 9, 4, 11, 5, 8, 1 with , the first three establish threshold 2. Incoming 4 replaces 2; 11 replaces 4; 5 is skipped; 8 replaces 7; 1 is skipped. The retained values are 8, 9, and 11.
A max-heap of the k largest exposes the best retained item, but admission needs the weakest one. For the k smallest, reverse the design: keep a max-heap so its root exposes the largest retained candidate.
Compare the alternatives
| Method | Time | Working storage | Useful situation |
|---|---|---|---|
| Bounded heap | for | One-pass stream, small k. | |
| Sort all items | All items present | Full order or k near n. | |
| Heapify all, pop k | Entire collection available. | ||
| Quickselect | Average , worst | All items present | One rank, reordering allowed. |
For , simply use min or max in linear time. Python's nlargest and nsmallest handle common selection tasks, including a key function; sorting is often preferable when k is near the collection size.
Squared distance ranks points by distance from the origin without square roots. Points (1, 2), (3, 1), (-1, -1), and (4, 0) have squared distances 5, 10, 2, and 16, so the closest two are (-1, -1) and (1, 2). For frequent words, count first with a dictionary, then select by count.
Preserve the intended tie policy
Skipping a new value equal to the root does not control which equal item already retained is evicted later. To prefer earlier arrivals among equal top-k scores, rank entries by (score, -arrival_number). A later tied item has a smaller ranking and is the first tied candidate evicted when a better score arrives. With two retained slots and arrivals 3, 3, 3, 7, the final pair is 7 and the first 3. Include a unique arrival number before the payload so records themselves never need comparison.
Key Takeaways
- For the k largest, a min-heap exposes the weakest retained item.
- Test admission before using
heapreplace. - The root is the k-th largest only after at least k arrivals.
- A bounded heap supports one-pass selection with memory.
- Reverse the heap orientation for the k smallest.
- Use the full ranking key to enforce tie preferences among retained records.
5.2 Merge from one candidate per input
A k-way merge combines already sorted sequences into one sorted output. A min-heap can exploit their existing order by storing one current candidate from each nonempty input.
Keep only each input's next item
For numeric lists, an entry can be (value, list_index, position). Start with the first value of every nonempty list. Pop the smallest entry, output its value, then push the next value from that same list if one exists.
Why is one candidate enough? Every later value in a sorted list is at least its current head. The smallest unconsumed value across all lists must therefore be among the heads. Pushing a successor restores exactly the candidates needed for the next decision.
import heapq
def merge_lists(lists):
h = [(a[0], j, 0) for j, a in enumerate(lists) if a]
heapq.heapify(h)
while h:
value, j, p = heapq.heappop(h)
yield value
p += 1
if p < len(lists[j]):
heapq.heappush(h, (lists[j][p], j, p))
The yield produces results as needed. An empty input contributes no initial entry. When one input ends, its candidate simply disappears. Advancing the wrong list or failing to add a successor silently loses data even though the output produced so far may look sorted.
Trace the candidates
Merge [1, 4, 9], [2, 3, 10], and [5, 6]. The initial candidates are 1, 2, and 5.
- Output 1 and add 4 from its list. Candidates are 2, 4, 5.
- Output 2 and add 3. Candidates are 3, 4, 5.
- Output 3 and add 10. Candidates are 4, 5, 10.
- Output 4 and add 9. Candidates are 5, 9, 10.
- Output 5 and add 6. Candidates are 6, 9, 10.
- Output 6, then 9, then 10 as their lists end.
The result is 1, 2, 3, 4, 5, 6, 9, 10. These candidate listings describe values in increasing order for readability, not required heap-array layouts.
Handle records and measure the cost
For records, store (sort_key, list_index, position, record). Equal sort keys compare list indexes before reaching records. Only one entry from each list is present, so that index also uniquely settles equal keys across candidates. Earlier lists win equal-key ties, and order within each list is preserved. Using (record, list_index, position) would compare the records first and may fail for non-comparable payloads.
With total items and at most candidates, each item is pushed and popped once. For this takes time and auxiliary memory beyond output and input storage. A single input just streams through in linear time. Concatenating and sorting costs , while sequentially merging an ever-growing result with the next list can cost .
Python's heapq.merge(*iterables) returns a lazy iterator over sorted inputs. It is useful for timestamp-ordered logs and for external sorting, where sorted runs on disk are merged without loading every record at once.
Key Takeaways
- Store one candidate per nonempty input.
- After a pop, advance only the list that supplied that item.
- Sorted inputs make their current heads sufficient for the next decision.
- Place sort keys and tie-breakers before record payloads.
- The heap stays bounded by the number of inputs, not total output length.
5.3 Expose the middle with two heaps
A running median reports the middle value after each arrival. Re-sorting all previous items after every update is expensive. Two heaps keep the boundary between the lower and upper halves directly accessible.
Maintain two invariants
Use a max-heap low for the lower half and a min-heap high for the upper half. Every value in low must be at most every value in high. Also, low has the same number of items as high or exactly one more.
These rules put the middle positions at the two roots. For an odd count, the median is the maximum of low. For an even count, it is the average of that value and the minimum of high.
On arrival, compare the new value with the top of low: send it to low if it is no larger, otherwise to high. Then rebalance. If low has two extra items, move its maximum to high; if high is larger, move its minimum to low. Moving a boundary item preserves the partition order.
Implement with negated lower values
import heapq
low, high = [], []
def add(x):
if not low or x <= -low[0]:
heapq.heappush(low, -x)
else:
heapq.heappush(high, x)
if len(low) > len(high) + 1:
heapq.heappush(high, -heapq.heappop(low))
elif len(high) > len(low):
heapq.heappush(low, -heapq.heappop(high))
def median():
if not low:
raise ValueError("no values")
if len(low) > len(high):
return -low[0]
return (-low[0] + high[0]) / 2
The sign conversion matters on every transfer. low stores negated values, so -low[0] reads its actual maximum. high stores ordinary values.
Follow the middle as values arrive
For the stream 5, 15, 1, 3, 8, 7, list each half below in sorted order for readability; these are sets of retained values, not heap-array layouts.
| Arrival | Lower half | Upper half | Median |
|---|---|---|---|
| 5 | 5 | empty | 5 |
| 15 | 5 | 15 | 10 |
| 1 | 1, 5 | 15 | 5 |
| 3 | 1, 3 | 5, 15 | 4 |
| 8 | 1, 3, 5 | 8, 15 | 5 |
| 7 | 1, 3, 5 | 7, 8, 15 | 6 |
After 3 enters low, that half is too large, so 5 moves to high. After 8 enters high, it becomes larger than low, so its minimum 5 moves back. The even-count medians use both roots.
Each arrival uses one push and at most one pop-and-push transfer, so updates take time. Reading the median is , while storing all values takes memory. A running median is not a constant-memory stream summary.
Balancing sizes alone is insufficient. If the heaps have equal sizes but a value in low exceeds one in high, their roots need not be the middle values. Preserve both the order partition and the size rule. For even counts, returning just one root chooses a boundary value instead of the required average.
Key Takeaways
- Use a max-heap below and a min-heap above.
- Every lower value must be at most every upper value.
- Keep the lower half equal in size or larger by one.
- Move a boundary item to rebalance after insertion.
- Odd counts use the lower root; even counts average both roots.
- Updates are logarithmic, queries constant-time, and storage linear.
5.4 Choose tasks, events, and resources by key
Scheduling problems differ in what "next" means. A priority queue turns that rule into a key, then repeatedly removes the next item, handles it, and inserts any new work it creates.
Serve urgent tasks and timed events
For urgency where priority 1 comes first, use a min-heap of (priority, arrival_number, task). The counter gives FIFO ties. If deadlines matter after urgency, the key can compare priority, then deadline, then an arrival counter.
A discrete-event simulation stores future events by event time. Pop the earliest event, move the simulation clock to that time, and process the event. Processing may add a later event. The clock jumps between events without visiting every unused time step. Define an explicit tie rule if simultaneous events can affect one another.
One service desk receives customers at minutes 0, 2, and 3; each service takes 4 minutes. The first starts at 0 and schedules a departure at 4. Arrivals at 2 and 3 wait. At 4, the next customer starts and schedules departure at 8; at 8, the last starts and schedules departure at 12. Event times are 0, 2, 3, 4, 8, and 12. The future-event heap orders happenings; a separate waiting queue can preserve customers' arrival order.
Count the rooms needed
Sort meetings by start time. Keep one heap entry per room opened, containing the end time of that room's last assigned meeting. For each meeting:
- If the earliest room end is at or before the start, replace that root with the new end time.
- Otherwise, push the new end time to open another room.
import heapq
def room_count(meetings):
ends = []
for start, end in sorted(meetings):
if ends and ends[0] <= start:
heapq.heapreplace(ends, end)
else:
heapq.heappush(ends, end)
return len(ends)
Assume meetings have positive duration and a room can be reused exactly when a meeting ends. The heap includes idle rooms through their last end times; it does not contain only currently active meetings. Its size never shrinks, so the final size is the number of rooms opened.
Meetings 09:00–09:30 and 09:05–09:10 require two rooms. Meetings 09:15–09:20 and 09:25–09:35 reuse the second room. The meeting 09:30–09:40 reuses the first. Two rooms suffice. If the earliest end exceeds a new start, every opened room is busy at that start, so another room is necessary. Sorting plus heap updates costs time.
Assign work to the least-loaded machine
Keep (load, machine_id) entries. Pop the least-loaded machine, add the job's duration, and push its new load. Jobs of 7, 5, 4, 3, 3, and 2 hours, largest first on three machines, give final loads 9, 8, and 7 hours.
This greedy assignment is fast but not always optimal. Jobs of 3, 3, 2, 2, and 2 hours on two machines give loads 7 and 5, though grouping the two 3-hour jobs together gives a 6-and-6 split. A heap efficiently follows the policy; it does not make the policy optimal.
Cancelled tasks and rescheduled events can use lazy deletion. Skip stale entries before handling the next live event. Each physical heap operation costs with stale entries included in ; a single live-event search can require several pops.
Key Takeaways
- Choose a key that states the scheduling rule: urgency, event time, end time, or load.
- Event simulation processes happenings in time order and may create new events.
- For meeting rooms, sort by start and reuse the room with the earliest end.
- The room heap keeps one entry per room opened, including idle rooms.
- Use
<=when a room can be reused at the exact end time. - Least-load assignment is a greedy policy with no general optimality guarantee.
- Skip cancelled entries before processing the next live event.
Heaps and Priority Queues examples
1Choose what leaves the queue next
10 steps
- 1IntroductionChoose the next waiting task
A collection of waiting tasks needs a rule for choosing the next one. A priority queue uses a key such as urgency or time, so a new arrival can move ahead of older work.
First trace what insert, peek, and extract do. Then compare the data structures that can deliver those results. The interface tells you what comes back; the implementation determines how much work each operation needs.
- 2ExplanationChoose the numeric direction
A min-priority queue serves a smallest key; a max-priority queue serves a largest key. If urgency 1 is most important, a min-oriented queue serves it before urgency 4.
Insert adds an item. Peek reads the top without removing it. Extract returns the top and removes it. Decide the key rule before interpreting the phrase "highest priority."
- 3ExampleFollow a queue through an arrival
A min-priority queue receives 10, 3, and 7. Extract returns 3, leaving 10 and 7.
Now insert 2. Peek returns 2 but leaves all three current items in the queue. The next extract returns 2 and leaves 7 and 10. These are the guaranteed results even if the underlying storage is not sorted.
- 4ChallengeSeparate reading from removal
A min-priority queue contains 8, 4, and 11. You peek, insert 6, then extract. What is returned by each query, and what remains?
---reveal---
Peek returns 4 without removal. After inserting 6, extract also returns 4. The remaining values are 6, 8, and 11. Peek did not consume the first minimum, so the two queries can return the same value.
- 5TipGive tied tasks a second key
Equal priorities have no promised arrival order. To preserve FIFO ties, store entries ranked by
(priority, arrival_number), using a counter that increases on every insertion.The primary priority still decides unequal cases. The arrival number acts only when priorities tie. A unique counter placed before a task payload also prevents comparisons from reaching payloads that have no ordering.
- 6ExplanationPay for scanning or shifting
An unsorted array makes additions cheap: append in amortized constant time. Finding and removing a minimum requires a linear scan.
A decreasingly sorted array reverses that trade-off. The minimum is at the end for constant-time peek and extraction, but inserting can shift a linear number of items. Binary search finds the slot; it does not open it.
- 7ConnectionBalance mixed operations with a heap
A binary heap gives constant-time peek and logarithmic repairs for insertion and extraction. Its array is compact, and a whole collection can be heapified in linear time.
A balanced search tree also gives logarithmic updates and supports ordered searches. A heap keeps less order, which is enough when the main repeated request is an extreme item. Dynamic-array growth makes the heap insertion bound amortized.
- 8ChallengeMatch the workload
A program receives values throughout the day but needs only one final minimum. Another dispatches its best waiting item after many arrivals. What simple structures suit these workloads?
---reveal---
Use an unsorted list and one final scan for the first. A binary heap suits interleaved additions and extractions in the second. Maintaining sorted-array order during every arrival would pay linear shifting costs that neither workload requires.
- 9ChallengeConnect queue costs to sorting
Suppose a comparison-based priority queue could insert and extract in constant worst-case time. How could that sort n arbitrary keys, and why is the claim impossible?
---reveal---
Insert all keys, then extract them all in order. This would use only linear total work, contradicting the comparison-sorting lower bound. The same interface that dispatches tasks can also act as a sorting engine.
- 10RecapUse behavior to choose storage
Choose the primary key direction and distinguish peek from extract. Add an arrival counter when tied tasks must keep their order.
Then count the operations your workload needs. One final extreme may need only a scan; interleaved inserts and extracts suit a heap. Sorted storage and priority access solve related but different requirements.
2Read a heap in a plain array
9 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionSee one structure in two views
- 2ExplanationCheck shape before keys
- 3ExampleRead the parent rule
- 4ChallengeFind the missing requirement
- 5ExplanationTurn positions into indexes
- 6ExampleLocate a node and its relatives
- 7ChallengeCheck an edge below the root
- 8ChallengeDistinguish a swap from an index change
- 9RecapSeparate shape, order, and position
3Repair a heap after each change
19 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionFollow the changed item
- 2ExplanationAppend and compare upward
- 3ExampleStart a two-swap insertion
- 4ExampleFinish at the root
- 5ChallengeStop before the root
- 6ExplanationFill the root from the end
- 7ExampleBegin an extraction repair
- 8ExampleRepair the next level
- 9ChallengeHandle one remaining child
- 10TipKeep boundary cases small
- 11ExplanationFind named items before repairing them
- 12ExampleSee why removal can move upward
- 13ChallengeChoose the repair and maintain the map
- 14ConnectionPostpone cancelled entries
- 15ExplanationKeep the list after heapify
- 16ChallengeChoose admission behavior
- 17TipUse a counter before the payload
- 18ChallengeCombine stable ties and rescheduling
- 19RecapRepair one path and keep identities current
4Build once, then grow a sorted suffix
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionUse repairs for batch work
- 2ExplanationStart above the leaves
- 3ExampleRepair the lowest internal nodes
- 4ExampleFinish at the root
- 5Key InsightCount short paths more often
- 6ChallengeExplain the loop direction
- 7ExplanationPut the largest remaining value last
- 8ExampleStart the sort-down phase
- 9ExampleGrow the finished suffix
- 10ChallengeProtect the completed suffix
- 11ConnectionSeparate memory from stability
- 12ChallengeAccount for an unfinished sort
- 13RecapUse the right invariant for each phase
5Choose the boundary a heap should expose
20 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionAsk what must be accessible next
- 2ExplanationExpose the weakest retained score
- 3ExampleLet the threshold rise
- 4ChallengeMake the admission decision
- 5TipGive ties the intended ranking
- 6ExplanationKeep one head from each input
- 7ExampleAdvance the input that just won
- 8ChallengeFind the next candidate
- 9ConnectionSpend memory on candidates
- 10ExplanationKeep the two middle boundaries
- 11ExampleRebalance after a low arrival
- 12ExampleRebalance after a high arrival
- 13ChallengeAverage after the next arrival
- 14ExplanationOrder future events by time
- 15ExampleTrack one end time per room
- 16ChallengeRecognize idle rooms in the heap
- 17Key InsightEfficient choice can still be greedy
- 18ChallengeChoose between two meanings of next
- 19TipRemove stale events before reading time
- 20RecapName the root's job
Heaps and Priority Queues practice questions
Set 1: Choose priorities and read heap arrays10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
Show answerHide answer
Question 5 of 10
Show answerHide answer
Question 6 of 10
[3, 7, 4, 10, 6, 8] represents a complete tree. Which parent–child pair breaks min-heap order?Show answerHide answer
(4 - 1) // 2, which is 1, which holds 7. Since 7 exceeds 6, that edge violates min-heap order. Comparing the root only would miss this failure; root 3 is below both of its own children.Question 7 of 10
[4, 8, 6, 11, 10, 9] using sift up. What is the final array?Show answerHide answer
[2, 8, 4, 11, 10, 9, 6]. Moving through index 1 would follow the wrong ancestor path and change an unrelated part of the heap.Question 8 of 10
Show answerHide answer
Question 9 of 10
Show answerHide answer
Question 10 of 10
[2, 5, 4, 9, 7, 8, 6]. It extracts once, inserts 3, then extracts again. What is the final array under standard smaller-child sift down and sift up?Show answerHide answer
[4, 5, 6, 9, 7, 8]. Inserting 3 moves it through index 2 to the root; extracting it then moves 6 down past 4, restoring [4, 5, 6, 9, 7, 8]. Leaving 3 in the final heap would forget the second extraction.Set 2: Repair updates and use heap libraries10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
[1, 4, 3, 8, 6, 5]. What array remains after smaller-child sift down?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
[3, 6]. After extracting its minimum, what is returned and what array remains?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
[2, 9, 4, 12, 14, 6, 7], change the key 12 to 3. What is the repaired array?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
[1, 11, 3, 14, 13, 5, 4], then increase the root key to 8. What array remains after the required repairs?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
heapq.heapify(values) return after successfully rearranging a Python list?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
h = [6, 9, 7], what do heappushpop(h, 4) and heapreplace(h, 4) return, respectively?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 3: Build heaps and trace in-place sorting10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
[9, 6, 8, 2, 4]. What final array results?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
[10, 7, 8, 3, 2], what result exposes the problem with this method?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
[16, 11, 13, 4, 8]. What is the whole array after one root-to-end swap and complete repair?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
[(4, "P"), (4, "Q"), (2, "R")]. It swaps only on a strict child improvement. What is the final record order?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
values is arbitrary and nonempty. A program needs a heap and also wants to preserve that list's original order. What initialization is appropriate?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 4: Select results and combine ordered streams10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
(score, arrival_number, name) in a min-heap, with increasing arrival numbers. It replaces the root only for a strictly higher incoming score. Records arrive P:5, Q:5, R:8, S:9. What names remain, and how must the arrival component change to prefer earlier tied records?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
[2, 8], [1, 6, 9], and [4, 7] with one head per input. After outputting 1 and then 2 and adding their successors, what candidate values are in the heap?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
(timestamp, list_index, position, record) and prefers earlier list indexes on equal timestamps. List 0 has A:2, B:6; list 1 has C:2, D:4; list 2 has E:3. What is the complete output order?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 5: Apply heap invariants in changing workloads10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
[10, 14, 12, 18] as a min-heap. It receives 9, 16, then 11. What is the final k-th-largest value, and how many of these arrivals enter the retained heap?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
low = [-6, -2], high = [9, 14]. Insert 12 and rebalance so the lower half owns any extra item. What is the new median?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
[9, 6, 7, 2, 12, 15] and the active heap size is 4. What is the next value placed into its final position, and at which index?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Abstract data type
Admission threshold
Amortized cost
Ancestor path
Arbitrary removal
B
Balanced search tree
Binary heap
Bottom-up construction
C
Child subtree
Comparator
Comparator.reverseOrder() makes the largest natural-order value the head of a priority queue.Comparison-sorting lower bound
Complete binary tree
D
Discrete-event simulation
E
External sorting
Extract
F
Full binary tree
Future-event queue
G
Greedy scheduling
H
Heap boundary
Heap insertion
Heap property
Heap replacement
heapreplace with an inferior top-k candidate still admits it, so the admission test matters.Heap sort
Heapify
heapq.heapify performs this task in linear time.heapq.heapify(data), use data itself because the function's return value is None.heapq
heapq module supplies functions that maintain a binary heap in an ordinary list, using min-heap order by default.heapq.heappush(h, 8) inserts 8 while repairing the existing min-heap stored in h.I
In-place sorting
Indexed heap
Internal node
Introsort
K
k-way merge
L
Lazy deletion
Lazy iterator
heapq.merge can deliver the first merged records without building a complete output list.Leaf
Level order
Linear time
M
Machine load
Median boundary
Merge candidate
O
Order statistic
P
Partition invariant
Peek
Perfect binary tree
Popcount
Priority change
Priority key
Priority queue
Push-pop
heappushpop with incoming 2 returns 2 and leaves the old values.Q
Quickselect
R
Ranking function
Rebalancing
Repeated-insertion construction
Replacement root
Room reuse
Room-end heap
Running median
S
Sift down
Sift up
Sorted array implementation
Sorted suffix
Stability
Stable priority queue
(priority, counter, task) keep equal-priority tasks in FIFO order and avoid comparing payloads.Stale entry
T
Top-k selection
Tree height
U
Unsorted array implementation
#
0-based indexing
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.