Heaps and Priority Queues

Learn how a priority queue always hands you the most urgent item, and how a binary heap makes that fast. Store a heap in a plain array, restore its order with sift up and sift down, build a heap from scratch in linear time and sort with heap sort. Then use heaps to keep the top k items of a stream, merge sorted lists, track a running median and schedule tasks and events, with examples in Python.

IntermediateLesson 7 of 10 in Data Structures and Algorithms Course

What you will learn

  1. 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 operations
      State 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 heap
      Work 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.
  2. 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 property
      Check 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 indexes
      Store 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.
  3. 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 up
      Add 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 down
      Extract 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 heap
      Update 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 Java
      Apply Python's heapq functions correctly, build max-heaps and stable priority queues with tuples and counters, and use Java's PriorityQueue.
  4. 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 time
      Turn 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 sort
      Sort 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.
  5. 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 items
      Keep 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 sequences
      Merge several sorted lists or streams into one sorted output with a heap holding one item per list.
    • Keep a running median with two heaps
      Report 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 time
      Use 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.

Heaps and Priority Queues study guide

5 chapters

1

Explain 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.

OperationEffect
Insert, push, or offerAdd an item and its key.
Peek, find-min, or find-maxRead the top item without removing it.
Extract, pop, or pollRemove and return the top item.
Size or is-emptyReport 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, n is the number of stored items, and the queue is min-oriented.

Compare the main choices
ImplementationInsertPeek minimumExtract minimumMain trade-off
Unsorted dynamic arrayO(1) amortizedO(n)O(n)Cheap additions, repeated scans.
Array sorted decreasinglyO(n)O(1)O(1)Minimum at the end; insertion shifts items.
Balanced search treeO(log⁡n)O(log⁡n)O(log⁡n)Also supports search and ordered traversal.
Binary heapO(log⁡n) amortizedO(1)O(log⁡n)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 O(n2) work. Maintaining a sorted array during insertion gives insertion-sort behavior, also quadratic. A binary heap gives O(nlog⁡n) 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 Ω(nlog⁡n) 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.
2

Represent 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 termRequirement
CompleteAll earlier levels filled; last level filled from the left.
FullEvery node has either zero or two children.
PerfectEvery 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 h has 2h+1−1 nodes. Height counts edges: a one-node tree has height 0.

For any nonempty complete tree, height is ⌊log⁡2n⌋. Seven nodes fit in height 2; the eighth starts height 3. A tree with one million nodes has height 19. Depth d can hold at most 2d 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 O(1) 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 k−1: 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 n 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
RelativeRoot at index 0Root at index 1
Left child of i2*i + 12*i
Right child of i2*i + 22*i + 1
Parent of non-root i(i - 1) // 2i // 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 i is ⌊log⁡2(i+1)⌋. 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 O(n) 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 + 1 and 2*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.
3

Keep 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].

  1. Append at index 7: [2, 5, 3, 9, 6, 4, 8, 1]. Its parent is index 3, holding 9.
  2. 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.
  3. Swap 1 with 5: [2, 1, 3, 5, 6, 4, 8, 9]. Now compare index 1 with root 2.
  4. 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 n items has height ⌊log⁡2n⌋. Each sift step crosses one edge, so the worst-case sift costs O(log⁡n) 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 O(log⁡n) time and iterative sift down uses O(1) 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 O(n) 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 O(log⁡n) 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 H count all physical heap entries, including stale ones. Each push or pop costs O(log⁡H), 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 O(n) 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 operationMeaningEmpty 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

  • heapify changes a list in place and returns None.
  • 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.
4

Build 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].

  1. Index 4: swap 10 with its only child 2, giving [15, 8, 12, 3, 2, 6, 1, 7, 4, 10].
  2. Index 3: 3 is below both children 7 and 4 in key value, so leave it.
  3. Index 2: swap 12 with 1, giving [15, 8, 1, 3, 2, 6, 12, 7, 4, 10].
  4. Index 1: swap 8 with 2, giving [15, 2, 1, 3, 8, 6, 12, 7, 4, 10].
  5. 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 n by the largest possible sift length gives a valid but loose O(nlog⁡n) 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

8⋅0+4⋅1+2⋅2+1⋅3=11.

The decreasing node counts outweigh the increasing heights. The weighted series ∑h≥0h/2h=2 gives a constant factor times n, hence linear construction. More exactly, the sum of node heights in a complete tree is n−popcount⁡(n), where popcount counts binary 1 bits. It is less than n, so the standard sift makes fewer than n swaps and fewer than 2n 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 - 1 back 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].

  1. Move 10 to index 4 and repair: [5, 4, 3, 1, 10].
  2. Move 5 to index 3 and repair: [4, 1, 3, 5, 10].
  3. Move 4 to index 2 and repair: [3, 1, 4, 5, 10].
  4. 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 O(n). The remaining n−1 rounds each cost at most O(log⁡n), so the worst-case bound is O(nlog⁡n). Iterative sift down needs only a few variables, giving O(1) 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.

AlgorithmWorst-case timeTypical extra array spaceStable?
Heap sortO(nlog⁡n)O(1)No
Merge sort on arraysO(nlog⁡n)O(n)Yes, with stable merging
Basic quicksortO(n2)Depends on recursionUsually 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 O(nlog⁡n), but uses output storage. Stopping after k extractions gives a partial sort in O(n+klog⁡n) 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.
5

Solve 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 k 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 O(klog⁡k). If only membership or the k-th-largest value is needed, omit that sort. Once at least k 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 k=3, 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
MethodTimeWorking storageUseful situation
Bounded heapO(nlog⁡k) for k≥2O(k)One-pass stream, small k.
Sort all itemsO(nlog⁡n)All items presentFull order or k near n.
Heapify all, pop kO(n+klog⁡n)O(n)Entire collection available.
QuickselectAverage O(n), worst O(n2)All items presentOne rank, reordering allowed.

For k=1, 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 O(k) 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.

  1. Output 1 and add 4 from its list. Candidates are 2, 4, 5.
  2. Output 2 and add 3. Candidates are 3, 4, 5.
  3. Output 3 and add 10. Candidates are 4, 5, 10.
  4. Output 4 and add 9. Candidates are 5, 9, 10.
  5. Output 5 and add 6. Candidates are 6, 9, 10.
  6. 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 N total items and at most k candidates, each item is pushed and popped once. For k≥2 this takes O(Nlog⁡k) time and O(k) auxiliary memory beyond output and input storage. A single input just streams through in linear time. Concatenating and sorting costs O(Nlog⁡N), while sequentially merging an ever-growing result with the next list can cost O(Nk).

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.

ArrivalLower halfUpper halfMedian
55empty5
1551510
11, 5155
31, 35, 154
81, 3, 58, 155
71, 3, 57, 8, 156

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 O(log⁡n) time. Reading the median is O(1), while storing all values takes O(n) 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:

  1. If the earliest room end is at or before the start, replace that root with the new end time.
  2. 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 O(nlog⁡n) 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 O(log⁡H) with stale entries included in H; 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

5 Walkthroughs

1

Choose what leaves the queue next

10 steps
Trace priority queue behavior, then compare storage choices for different workloads.
  1. 1
    IntroductionChoose 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.

  2. 2
    ExplanationChoose 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."

  3. 3
    ExampleFollow 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.

  4. 4
    ChallengeSeparate 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.

  5. 5
    TipGive 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.

  6. 6
    ExplanationPay 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.

  7. 7
    ConnectionBalance 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.

  8. 8
    ChallengeMatch 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.

  9. 9
    ChallengeConnect 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 Ω(nlog⁡n) comparison-sorting lower bound. The same interface that dispatches tasks can also act as a sorting engine.

  10. 10
    RecapUse 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.

2

Read a heap in a plain array

9 steps
Check complete shape and parent–child order, then navigate the matching array positions.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionSee one structure in two views
  2. 2
    ExplanationCheck shape before keys
  3. 3
    ExampleRead the parent rule
  4. 4
    ChallengeFind the missing requirement
  5. 5
    ExplanationTurn positions into indexes
  6. 6
    ExampleLocate a node and its relatives
  7. 7
    ChallengeCheck an edge below the root
  8. 8
    ChallengeDistinguish a swap from an index change
  9. 9
    RecapSeparate shape, order, and position
3

Repair a heap after each change

19 steps
Follow insertions, extractions, named updates, and the matching library operations.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFollow the changed item
  2. 2
    ExplanationAppend and compare upward
  3. 3
    ExampleStart a two-swap insertion
  4. 4
    ExampleFinish at the root
  5. 5
    ChallengeStop before the root
  6. 6
    ExplanationFill the root from the end
  7. 7
    ExampleBegin an extraction repair
  8. 8
    ExampleRepair the next level
  9. 9
    ChallengeHandle one remaining child
  10. 10
    TipKeep boundary cases small
  11. 11
    ExplanationFind named items before repairing them
  12. 12
    ExampleSee why removal can move upward
  13. 13
    ChallengeChoose the repair and maintain the map
  14. 14
    ConnectionPostpone cancelled entries
  15. 15
    ExplanationKeep the list after heapify
  16. 16
    ChallengeChoose admission behavior
  17. 17
    TipUse a counter before the payload
  18. 18
    ChallengeCombine stable ties and rescheduling
  19. 19
    RecapRepair one path and keep identities current
4

Build once, then grow a sorted suffix

13 steps
Construct a heap bottom-up, account for its linear cost, and trace in-place heap sort.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionUse repairs for batch work
  2. 2
    ExplanationStart above the leaves
  3. 3
    ExampleRepair the lowest internal nodes
  4. 4
    ExampleFinish at the root
  5. 5
    Key InsightCount short paths more often
  6. 6
    ChallengeExplain the loop direction
  7. 7
    ExplanationPut the largest remaining value last
  8. 8
    ExampleStart the sort-down phase
  9. 9
    ExampleGrow the finished suffix
  10. 10
    ChallengeProtect the completed suffix
  11. 11
    ConnectionSeparate memory from stability
  12. 12
    ChallengeAccount for an unfinished sort
  13. 13
    RecapUse the right invariant for each phase
5

Choose the boundary a heap should expose

20 steps
Use heaps for top-k, sorted merging, running medians, and scheduling decisions.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionAsk what must be accessible next
  2. 2
    ExplanationExpose the weakest retained score
  3. 3
    ExampleLet the threshold rise
  4. 4
    ChallengeMake the admission decision
  5. 5
    TipGive ties the intended ranking
  6. 6
    ExplanationKeep one head from each input
  7. 7
    ExampleAdvance the input that just won
  8. 8
    ChallengeFind the next candidate
  9. 9
    ConnectionSpend memory on candidates
  10. 10
    ExplanationKeep the two middle boundaries
  11. 11
    ExampleRebalance after a low arrival
  12. 12
    ExampleRebalance after a high arrival
  13. 13
    ChallengeAverage after the next arrival
  14. 14
    ExplanationOrder future events by time
  15. 15
    ExampleTrack one end time per room
  16. 16
    ChallengeRecognize idle rooms in the heap
  17. 17
    Key InsightEfficient choice can still be greedy
  18. 18
    ChallengeChoose between two meanings of next
  19. 19
    TipRemove stale events before reading time
  20. 20
    RecapName the root's job

Heaps and Priority Queues practice questions

50 Practice Questions in 5 sets

Set 1: Choose priorities and read heap arrays10 Practice Questions

Question 1 of 10

A tree has root 2 with children 6 and 4. The node 6 has only a right child 9, and no other nodes exist. Why is this tree not a binary heap?
  1. The root does not contain a minimum.
  2. The left child is greater than the right child.
  3. The final level has a gap before an occupied slot.
  4. The tree does not fill every level completely.
Show answerHide answer
Answer: C
The final level occupies a right-child position while the earlier left-child slot is empty, breaking completeness. Every listed parent–child key comparison is valid for a min-heap. Ordering siblings would not fix the missing shape requirement, which applies independently of the keys.

Question 2 of 10

In a 0-based heap containing 15 items, what are the indexes of the children of index 5?
  1. 11 and 12
  2. 10 and 11
  3. 12 and 13
  4. 2 and 3
Show answerHide answer
Answer: A
The 0-based child formulas give 2⋅5+1=11 and 2⋅5+2=12, both below size 15. Using 10 and 11 mixes in the 1-based convention. The values stored at these positions do not affect the index calculation.

Question 3 of 10

A min-priority queue contains keys 6, 13, and 9. What does peek return, and how many items remain?
  1. 6; two items
  2. 13; three items
  3. 9; two items
  4. 6; three items
Show answerHide answer
Answer: D
Peek reads the smallest stored key, 6, and leaves all three items in place. Removing 6 and leaving two items would describe extraction. The minimum is chosen by its key, so arrival or storage position does not change the result.

Question 4 of 10

A min-priority queue receives 12, 5, and 9, then extracts once. It receives 4, peeks once, and extracts once more. What values remain?
  1. 9 and 12
  2. 4 and 12
  3. 5 and 9
  4. 4 and 9
Show answerHide answer
Answer: A
The first extraction removes 5. After inserting 4, peek observes 4 without removing it, and the next extraction removes 4. The remaining values are 9 and 12; treating peek as a removal would incorrectly extract 9 as well.

Question 5 of 10

An array is kept in decreasing order to implement a min-priority queue. What is the worst-case cost of inserting one new arbitrary key?
  1. O(n)
  2. O(1)
  3. O(log⁡n)
  4. O(nlog⁡n)
Show answerHide answer
Answer: A
An insertion can shift a linear number of existing items to open the required position, so it takes O(n) time in the worst case. Binary search can locate that position in logarithmic time, but it does not perform the shifts needed to keep the array sorted.

Question 6 of 10

The array [3, 7, 4, 10, 6, 8] represents a complete tree. Which parent–child pair breaks min-heap order?
  1. Parent index 0 and child index 2
  2. Parent index 1 and child index 4
  3. Parent index 2 and child index 5
  4. Parent index 1 and child index 3
Show answerHide answer
Answer: B
Index 4 holds 6 and its parent index is (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

Insert 2 into the min-heap [4, 8, 6, 11, 10, 9] using sift up. What is the final array?
  1. [2, 4, 6, 11, 10, 9, 8]
  2. [4, 8, 2, 11, 10, 9, 6]
  3. [2, 4, 8, 11, 10, 9, 6]
  4. [2, 8, 4, 11, 10, 9, 6]
Show answerHide answer
Answer: D
Appending 2 gives index 6, whose parent index 2 holds 6. After that swap, 2 swaps with root 4, producing [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

An initially empty min-priority queue uses an unsorted dynamic array. A program inserts n distinct arbitrary keys, then extracts until empty. What is the tight worst-case total time?
  1. Θ(nlog⁡n)
  2. Θ(n)
  3. Θ(n2)
  4. Θ(log⁡n)
Show answerHide answer
Answer: C
Insertion is linear in total amortized time, but extraction scans collections of sizes n, n−1, down to 1. Those scan lengths sum to a quadratic total. Logarithmic-factor sorting would require a different representation, such as a binary heap, instead of repeated unsorted scans.

Question 9 of 10

A complete min-heap has root 3, left child 8, and right child 5. Is its parent–child order valid?
  1. No; siblings must increase left to right.
  2. Yes; both child keys are at least the root.
  3. No; all values in the left subtree must be smaller.
  4. No; the two child keys must be equal.
Show answerHide answer
Answer: B
Both edges satisfy the min-heap rule: 3 is at most 8 and at most 5. The sibling order is unrestricted, so 8 may sit to the left of 5. Requiring every left-side value to be smaller would import a binary search tree rule into a heap.

Question 10 of 10

A min-heap contains [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?
  1. [4, 5, 3, 9, 7, 8]
  2. [4, 5, 6, 9, 7, 8]
  3. [5, 6, 4, 9, 7, 8]
  4. [4, 5, 8, 9, 7, 6]
Show answerHide answer
Answer: B
The first extraction gives [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

A new key in a min-heap equals its parent. What should standard sift up do at that edge?
  1. Stop without swapping.
  2. Swap once, then stop.
  3. Move the key to the root.
  4. Compare the two siblings first.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Extract once from the min-heap [1, 4, 3, 8, 6, 5]. What array remains after smaller-child sift down?
  1. [4, 5, 3, 8, 6]
  2. [3, 4, 5, 8, 6]
  3. [3, 4, 6, 8, 5]
  4. [5, 4, 3, 8, 6]
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A min-heap contains [3, 6]. After extracting its minimum, what is returned and what array remains?
  1. Return 6; keep [3].
  2. Return 3; keep [6].
  3. Return 3; keep [].
  4. Return 6; keep [].
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

In the min-heap [2, 9, 4, 12, 14, 6, 7], change the key 12 to 3. What is the repaired array?
  1. [2, 9, 4, 3, 14, 6, 7]
  2. [3, 2, 4, 9, 14, 6, 7]
  3. [2, 3, 4, 9, 14, 6, 7]
  4. [2, 4, 3, 9, 14, 6, 7]
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Remove the item at index 4 from [1, 11, 3, 14, 13, 5, 4], then increase the root key to 8. What array remains after the required repairs?
  1. [3, 4, 5, 14, 11, 8]
  2. [3, 11, 4, 14, 8, 5]
  3. [4, 8, 3, 14, 11, 5]
  4. [3, 4, 8, 14, 11, 5]
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A lazy-deletion heap begins empty. Insert task P at priority 8 and task Q at priority 5. Change P to priority 2, change P to priority 7, then cancel Q. Before any pop or cleanup, how many physical entries and live tasks remain?
  1. 2 entries; 1 live task
  2. 4 entries; 2 live tasks
  3. 4 entries; 1 live task
  4. 1 entry; 1 live task
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What value does heapq.heapify(values) return after successfully rearranging a Python list?
  1. The smallest key
  2. The sorted list
  3. The heap size
  4. None
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Starting independently from h = [6, 9, 7], what do heappushpop(h, 4) and heapreplace(h, 4) return, respectively?
  1. 4 and 6
  2. 6 and 4
  3. 4 and 4
  4. 6 and 6
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Tasks are dictionaries. A program needs FIFO order for equal priorities, then changes an existing task's priority while using lazy deletion. What entry and update design preserves these requirements?
  1. (priority, task); edit priority in place
  2. (priority, counter, task); edit priority in place
  3. (counter, priority, task); mark old and push new
  4. (priority, counter, task); mark old and push new
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

In a min-heap with distinct keys, where must the second-smallest key occur?
  1. At the final array position
  2. At one of the root's children
  3. At the leftmost leaf only
  4. At the rightmost leaf only
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

For a 0-based array of 12 items, which index is processed first by bottom-up heap construction?
  1. 6
  2. 11
  3. 0
  4. 5
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Apply standard bottom-up min-heap construction to [9, 6, 8, 2, 4]. What final array results?
  1. [2, 4, 8, 9, 6]
  2. [2, 4, 6, 9, 8]
  3. [2, 4, 8, 6, 9]
  4. [2, 9, 8, 6, 4]
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A builder sifts down once at each internal index in increasing order. Applied to [10, 7, 8, 3, 2], what result exposes the problem with this method?
  1. [7, 2, 8, 3, 10]; 7 exceeds child 2
  2. [2, 3, 8, 7, 10]; leaves are unsorted
  3. [2, 7, 8, 3, 10]; 7 exceeds child 3
  4. [7, 3, 8, 10, 2]; 3 exceeds child 2
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A perfect binary tree has 31 nodes. What is the maximum total number of swaps justified by summing node heights for bottom-up construction?
  1. 124
  2. 26
  3. 31
  4. 15
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What heap orientation directly produces ascending in-place heap sort when each root is swapped to the active region's end?
  1. Max-heap
  2. Min-heap
  3. Either without changing output order
  4. Alternating min- and max-heaps
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Ascending heap sort has active max-heap [16, 11, 13, 4, 8]. What is the whole array after one root-to-end swap and complete repair?
  1. [11, 8, 13, 4, 16]
  2. [13, 11, 8, 4, 16]
  3. [13, 11, 16, 4, 8]
  4. [16, 11, 13, 4, 8]
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

Heap sort compares records only by numeric key. It starts its sort-down phase from [(4, "P"), (4, "Q"), (2, "R")]. It swaps only on a strict child improvement. What is the final record order?
  1. R, P, Q
  2. R, Q, P
  3. P, Q, R
  4. Q, R, P
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A programmer runs a full in-place end-swapping min-heap sort, then reverses the array in place. With iterative sifts, what time and auxiliary-space bounds describe the complete procedure?
  1. O(n) time; O(1) space
  2. O(nlog⁡n) time; O(n) space
  3. O(n2) time; O(1) space
  4. O(nlog⁡n) time; O(1) space
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A Python list values is arbitrary and nonempty. A program needs a heap and also wants to preserve that list's original order. What initialization is appropriate?
  1. h = values.copy(); heapq.heapify(h)
  2. h = heapq.heapify(values)
  3. h = values; heapq.heapify(h)
  4. h = values.copy()
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

All n items are available now, and a program needs the smallest r items in sorted order with r much smaller than n. What is the cost of heapifying all n, then popping r times?
  1. O(rlog⁡n)
  2. O(nlog⁡r)
  3. O(n+rlog⁡n)
  4. O(nr)
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

A streaming algorithm keeps the five largest scores in a heap of five entries. What must the root expose?
  1. The first score received
  2. The smallest retained score
  3. The largest retained score
  4. The median retained score
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Keep the three largest values from the stream 6, 14, 3, 9, 12, 4. What is the final threshold at the heap root?
  1. 12
  2. 6
  3. 9
  4. 14
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A three-largest filter stores (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?
  1. Q, R, S; negate arrival number
  2. P, R, S; negate arrival number
  3. Q, R, S; negate score
  4. P, R, S; negate score
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A stream of points arrives as P=(2,3), Q=(1,4), R=(3,0), S=(0,5), T=(2,1). Keep the two closest to the origin using a max-heap of squared distances. After all arrivals, which points remain and what is the root's squared-distance threshold?
  1. P and T; 13
  2. R and T; 9
  3. R and T; 5
  4. P and R; 13
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Merge [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?
  1. 4, 6, 9
  2. 6, 7, 8
  3. 4, 6, 8
  4. 2, 4, 6
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A merge uses (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?
  1. A, C, E, D, B
  2. C, A, E, D, B
  3. A, C, D, E, B
  4. A, E, C, D, B
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A merge combines 8 sorted inputs containing N records in total. A refactor puts all N records in the heap at initialization. As N grows with 8 fixed, how do time and heap storage change from the one-head method?
  1. From O(N) and O(1) to O(Nlog⁡N) and O(N)
  2. From O(Nlog⁡N) and O(N) to O(N) and O(1)
  3. From O(N) and O(N) to O(Nlog⁡N) and O(1)
  4. From O(Nlog⁡N) and O(1) to O(N) and O(N)
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A running median has lower half {2, 5} and upper half {8, 11}. What median should it report?
  1. 5
  2. 8
  3. 7.5
  4. 6.5
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

The lower median heap contains {1, 4, 7} and the upper contains {10, 12}. A new value 3 arrives. After insertion and rebalancing, what is the median?
  1. 4
  2. 7
  3. 6.5
  4. 5.5
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A two-heap median algorithm keeps the lower half equal in size to the upper half or larger by one. After processing 9, 2, 13, 5, 7, 1, what are the lower maximum, upper minimum, and median?
  1. 7, 9, 8
  2. 5, 7, 6
  3. 2, 7, 4.5
  4. 5, 9, 7
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

A future-event min-heap contains events at minutes 18, 7, and 12. Which event time does the simulation process next?
  1. 12 minutes
  2. 18 minutes
  3. 7 minutes
  4. The first inserted time
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Meetings run from 13:00–13:20, 13:05–13:15, 13:15–13:25, and 13:20–13:30. Back-to-back reuse is allowed. How many rooms are required?
  1. 3
  2. 2
  3. 1
  4. 4
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Two machines start with zero load. Jobs of 8, 7, 6, 5, and 4 hours are assigned in that order to the least-loaded machine, breaking equal-load ties by machine ID. What final loads result, and can a smaller maximum load be achieved?
  1. 17 and 13; a maximum of 15 is possible
  2. 15 and 15; no smaller maximum
  3. 17 and 13; no smaller maximum
  4. 16 and 14; a maximum of 15 is possible
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

One server serves waiting customers in arrival order, taking 5 minutes per customer. Arrivals are at minutes 0, 1, and 6. When does the third customer finish, and how long did that customer wait before service?
  1. 15; 4 minutes
  2. 11; 0 minutes
  3. 16; 5 minutes
  4. 15; 9 minutes
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A stream keeps the four largest values and has already retained [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?
  1. 12; one arrival
  2. 11; two arrivals
  3. 14; one arrival
  4. 12; two arrivals
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A median structure stores lower values as negatives: low = [-6, -2], high = [9, 14]. Insert 12 and rebalance so the lower half owns any extra item. What is the new median?
  1. 6
  2. 10.5
  3. 9
  4. 12
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A lazy-deletion min-heap contains stale entries at priorities 1 and 2, then live task X at priority 4. A logical extraction must return a live task. How many physical pops are needed, and what is returned?
  1. One pop; priority 1
  2. Two pops; priority 2
  3. One pop; task X
  4. Three pops; task X
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

During ascending in-place heap sort, the array is [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?
  1. 12 at index 4
  2. 7 at index 2
  3. 15 at index 5
  4. 9 at index 3
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A k-way merge initializes candidates from three nonempty inputs. It outputs 20 records; exactly two inputs have ended by then. How many candidates remain, and what must be true of the next output?
  1. Two; it is the smaller unfinished input head.
  2. One; it is the final input's first unconsumed item.
  3. Three; it is the final input's first unconsumed item.
  4. One; it is the final input's greatest remaining item.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A program collects arbitrary values and asks for their minimum only once, after all arrivals. Which simple strategy gives linear total time without maintaining heap order?
  1. Keep a sorted array after every arrival.
  2. Append to an unsorted list, then scan once.
  3. Scan the growing array after every arrival.
  4. Insert each item into a heap, then peek once.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

66 Key Terms, each with its definition

A

Abstract data type
An abstract data type defines a collection of operations and their behavior, leaving the storage method to an implementation.
A priority queue is an abstract data type that a binary heap or a sorted array can implement.
Admission threshold
An admission threshold is the weakest value currently retained by a full bounded heap, used to decide whether a new item belongs.
When a three-largest min-heap has root 12, an incoming 15 replaces that root while an incoming 9 is skipped.
Amortized cost
An amortized cost averages operation costs over a sequence, including occasional expensive steps such as array resizing.
Most list appends are cheap; occasional copying during growth is included in their amortized bound.
Ancestor path
An ancestor path follows successive parents from one node toward the root, bounding the positions that sift up can visit.
An item appended at index 12 can visit parent indexes 5, 2, and 0 during a 0-based sift up.
Arbitrary removal
An arbitrary removal deletes a chosen heap item by filling its position from the end and repairing upward or downward as needed.
Removing a middle item can place the last value under a larger parent, requiring a sift up.

B

Balanced search tree
A balanced search tree keeps logarithmic height while supporting ordered search, insertion, and removal through tree links.
A balanced tree is useful when a program needs both priority access and searches for named keys.
Binary heap
A binary heap is a complete binary tree whose parent keys are consistently ordered against their children's keys.
The array [2, 7, 3, 8] represents a binary min-heap even though its values are not fully sorted.
Bottom-up construction
Bottom-up construction builds a heap by sifting down internal nodes from the last internal index backward to the root.
A heap with 12 items processes indexes 5, 4, 3, 2, 1, and 0 after treating leaves as already valid.

C

Child subtree
A child subtree consists of a node's child and all descendants below that child, whose order sift down assumes is already valid.
Bottom-up construction repairs both child subtrees before processing the parent above them.
Comparator
A comparator defines the ordering used to rank objects, allowing a priority queue to serve values by a chosen rule.
Java's Comparator.reverseOrder() makes the largest natural-order value the head of a priority queue.
Comparison-sorting lower bound
The comparison-sorting lower bound requires at least logarithmic work per item on average in the worst case for sorting arbitrary keys.
Constant-time worst-case insert and extract together would violate the sorting bound for comparisons.
Complete binary tree
A complete binary tree fills every level before the last and fills its final level from left to right without gaps.
Appending one node to a heap occupies the next free level-order position and preserves completeness.

D

Discrete-event simulation
A discrete-event simulation advances its clock directly to the next scheduled event and processes any new events that action creates.
A service completion at minute 8 can schedule another completion without visiting every time in between.

E

External sorting
External sorting orders data too large to fit in memory by creating sorted runs and merging them from external storage.
A k-way heap merge combines sorted disk runs with memory proportional to the number of runs.
Extract
An extract operation removes and returns the current top item, chosen by the priority queue's min- or max-ordering rule.
Extracting from a min-priority queue with keys 4, 9, and 6 returns 4 and leaves two items behind.

F

Full binary tree
A full binary tree gives every node either zero children or two children, without requiring all levels to be filled.
A complete tree with two nodes is not full because its root has only a left child.
Future-event queue
A future-event queue is a priority queue of pending simulation events ranked by time and any explicit simultaneous-event tie rule.
An arrival at minute 6 precedes a pending departure at minute 9 in the future-event min-heap.

G

Greedy scheduling
Greedy scheduling makes each next assignment using the locally best current choice without guaranteeing the best overall schedule.
Assigning each next job to the least-loaded machine can leave a worse final balance than another grouping.

H

Heap boundary
A heap boundary is the exclusive array limit of the active heap, beyond which child positions must not be accessed during repair.
When the active heap size is 6, a computed child index of 6 is outside the heap and must be skipped.
Heap insertion
A heap insertion appends one item at the next complete-tree position, then sifts it up to restore parent–child order.
Inserting a value larger than its parent into a min-heap needs no swap after the initial append.
Heap property
The heap property orders every parent against each child: at most the child in a min-heap, or at least it in a max-heap.
A parent key 8 above child key 5 breaks the min-heap property, even when the root is the minimum.
Heap replacement
A heap replacement removes the old root and inserts the incoming item, keeping a nonempty heap's size unchanged.
Calling heapreplace with an inferior top-k candidate still admits it, so the admission test matters.
Heap sort
Heap sort orders an array by building a heap and repeatedly moving an extreme remaining item into a final position at the end.
Ascending in-place heap sort begins with a max-heap and places the largest value at the final index.
Heapify
Heapify rearranges an entire collection into heap order in place; Python's heapq.heapify performs this task in linear time.
After heapq.heapify(data), use data itself because the function's return value is None.
heapq
Python's heapq module supplies functions that maintain a binary heap in an ordinary list, using min-heap order by default.
Calling heapq.heappush(h, 8) inserts 8 while repairing the existing min-heap stored in h.

I

In-place sorting
In-place sorting rearranges the original array using only constant auxiliary storage, apart from the array itself.
Iterative heap sort needs a few indexes and swap variables instead of a separate output array.
Indexed heap
An indexed heap stores a lookup map from unique item IDs to array positions so named items can be updated without a scan.
A task scheduler updates both lookup entries whenever a sift swaps two tasks inside an indexed heap.
Internal node
An internal node is a tree node with at least one child; in a complete heap these nodes occupy the first half of the array.
A ten-item heap has its last internal node at index 4, which has a left child at index 9.
Introsort
Introsort begins with quicksort and switches to heap sort when recursion becomes too deep, maintaining a logarithmic-factor worst-case bound.
A library sort can use introsort to combine quicksort's practical speed with heap sort's time guarantee.

K

k-way merge
A k-way merge combines k sorted inputs into one sorted output by repeatedly choosing the smallest current input candidate.
Merging sorted log files can keep one timestamped record from each unfinished file in a min-heap.

L

Lazy deletion
Lazy deletion cancels an item by marking its heap entry stale and postponing physical removal until that entry reaches the top.
Rescheduling an event can mark its old entry and insert a new one without locating an array index.
Lazy iterator
A lazy iterator produces its next value when requested instead of computing and storing the entire result in advance.
Python's heapq.merge can deliver the first merged records without building a complete output list.
Leaf
A leaf is a tree node with no children; a heap's leaf indexes begin at the integer quotient of its size divided by two.
In a nine-item heap, indexes 4 through 8 are leaves and need no bottom-up repair of their own.
Level order
Level order lists a tree's nodes from the root downward, visiting every level from left to right before the next level.
The first three positions of a heap array hold the root, its left child, and its right child.
Linear time
Linear time describes a running-time bound proportional to the number of input items, up to constant factors for large inputs.
Bottom-up heap construction is linear because most nodes can move only a short distance downward.

M

Machine load
A machine load is the total duration of jobs assigned to one machine, used as the key when repeatedly choosing the least-loaded machine.
After assigning a 4-hour job to a machine with load 7 hours, push it back with load 11 hours.
Median boundary
A median boundary is an extreme value at the dividing line between lower and upper halves, available at one of the two heap roots.
For an even count, averaging the two median boundaries gives the middle value between them.
Merge candidate
A merge candidate is an input's first unconsumed item, representing that input in the heap until the item is output.
After outputting a candidate from list 2, the merge pushes list 2's successor and changes no other list.

O

Order statistic
An order statistic is a value at a specified rank when data is sorted, counting repeated values as separate positions.
After three or more arrivals, a three-largest bounded min-heap exposes the third-largest value at its root.

P

Partition invariant
A partition invariant requires every value in the median's lower heap to be at most every value in its upper heap.
Equal heap sizes do not give a correct median if a lower-half value is larger than an upper-half value.
Peek
A peek operation reads the current top item of a collection without removing it or changing how many items are stored.
Peeking at the next event lets a simulation inspect its time while leaving the event in the queue.
Perfect binary tree
A perfect binary tree has every level filled completely, so all leaves share a depth and every internal node has two children.
A perfect tree of height 3 has 15 nodes: one root, two children, four grandchildren, and eight leaves.
Popcount
The popcount of a nonnegative integer is the number of 1 bits in its binary representation, used in the exact sum of heap-node heights.
The number 15 has binary form 1111, so a 15-node complete tree has total node height 15 minus 4.
Priority change
A priority change replaces a stored item's ranking key and repairs any resulting heap-order violation along one direction.
In a min-heap, lowering a task key from 8 to 2 may move that task upward past larger parents.
Priority key
A priority key is the value or tuple used to rank an item for service, including any fields needed to settle ties.
A task key can compare urgency first and then an arrival counter when two tasks have equal urgency.
Priority queue
A priority queue stores keyed items and supplies an item with an extreme key whenever the next item is requested.
A simulation puts future events in a priority queue so the earliest pending event is handled next.
Push-pop
A push-pop operation inserts an incoming item and removes an extreme item, allowing the incoming item itself to be returned.
On a min-heap rooted at 5, heappushpop with incoming 2 returns 2 and leaves the old values.

Q

Quickselect
Quickselect partitions an in-memory collection to find a chosen rank in average linear time, with quadratic worst-case time.
Use quickselect for one rank when reordering the whole stored collection is acceptable.

R

Ranking function
A ranking function computes a comparison key for each item, allowing selection to follow a property other than the item itself.
Squared distance is a ranking function for nearby points because it preserves nonnegative distance order.
Rebalancing
Rebalancing transfers a boundary value between median heaps to restore their size rule while preserving the lower–upper partition.
If the upper heap becomes larger, move its minimum to the lower heap before reading the median.
Repeated-insertion construction
Repeated-insertion construction builds a heap by appending each input item and repairing its ancestor path with sift up.
A decreasing input gives a min-heap a new smallest key on every insertion, causing long upward paths.
Replacement root
A replacement root is the last heap item moved into the vacated root position before extraction repairs downward order.
The former last value can be larger than the root's children, so extraction may require several swaps.
Room reuse
Room reuse assigns a new meeting to an existing room whose last assigned meeting ends at or before the new start time.
A room ending at 14:10 can host a meeting beginning at 14:10 when back-to-back use is permitted.
Room-end heap
A room-end heap stores one last-assigned end time for every room opened, exposing the earliest room available for reuse.
Idle rooms remain in this heap, so its final size records allocated rooms instead of active meetings.
Running median
A running median is the median of every value received so far, updated whenever another value joins the stream.
A monitoring system can report the middle observed response time after each new measurement arrives.

S

Sift down
Sift down restores heap order by exchanging an item with its better-ranked child until its subtree obeys the heap property.
In a min-heap, replacement root 10 swaps with child 3 when its two child values are 3 and 7.
Sift up
Sift up restores heap order by moving an item toward the root while its key is out of order with its parent's key.
A new key 1 inserted below parent 6 swaps upward until it meets an ordered edge or reaches the root.
Sorted array implementation
A sorted array implementation maintains all keys in order, allowing cheap extraction at one end but requiring shifts on insertion.
Keeping the minimum at the back lets a sorted Python list remove it without shifting the rest.
Sorted suffix
A sorted suffix is the final segment of an array already in its required order and excluded from the active heap during heap sort.
After placing the two largest values, heap sort repairs only the prefix before that finished suffix.
Stability
Stability preserves the original relative order of records whose sorting keys compare equal, even after the keys are sorted.
Two records with key 7 can reverse during heap sort, demonstrating that the algorithm is not stable.
Stable priority queue
A stable priority queue serves equal-priority items in their arrival order by including an increasing arrival value in its comparison key.
Entries (priority, counter, task) keep equal-priority tasks in FIFO order and avoid comparing payloads.
Stale entry
A stale entry remains physically stored in a heap after its task was cancelled or superseded and must be skipped before service.
Ten live tasks can share a heap with many stale entries, increasing both memory use and repair costs.

T

Top-k selection
Top-k selection finds the k highest- or lowest-ranked items of a collection without necessarily ordering the entire input.
A stream processor keeps only the 20 largest readings instead of sorting every reading it receives.
Tree height
A tree's height is the number of edges on a longest path from its root to a leaf, making a one-node tree height zero.
A complete tree grows from height 2 to height 3 when its node count increases from 7 to 8.

U

Unsorted array implementation
An unsorted array implementation appends new queue items cheaply but scans the stored keys whenever it needs a minimum.
A batch of readings can stay unsorted when the program needs only one minimum after collection ends.

#

0-based indexing
0-based indexing numbers array positions starting at zero, giving a heap root index 0 and children at doubled indexes plus 1 or 2.
For a node at index 4, its left child is at index 9 if the heap is large enough to contain it.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started