Skip to content

Heaps and the largest k values

A min-heap keeps its smallest value at the root. Every parent is no greater than either child, but unrelated branches need not be ordered. Python’s heapq stores this structure in an ordinary list and changes that list in place.

Use a heap when you repeatedly need the next smallest value or a fixed number of largest values. The examples below use invented integer scores. Read arrays and Python lists before using the heap’s index representation.

For a node at index i, its children occupy indices 2 * i + 1 and 2 * i + 2, when those positions exist. The root occupies index 0. heapify rearranges a list into a heap in O(n) time. It does not sort the list.

import heapq
heap = [6, 2, 9, 4, 8]
heapq.heapify(heap)
print("Heap array:", heap)
print("Minimum:", heap[0])
heapq.heappush(heap, 3)
print("After push 3:", heap)
print("Pop minimum:", heapq.heappop(heap))
print("Remaining heap:", heap)
print("Sorted values:", sorted(heap))
Heap array: [2, 4, 9, 6, 8]
Minimum: 2
After push 3: [2, 4, 3, 6, 8, 9]
Pop minimum: 2
Remaining heap: [3, 4, 9, 6, 8]
Sorted values: [3, 4, 6, 8, 9]

The minimum is available in O(1) time. Push and pop repair a path of O(log n) heap levels. Python’s dynamic list storage also permits occasional O(n) resize work during a push or pop. O(log n) describes their amortized total cost. heappop raises IndexError on an empty heap.

Given integer scores and a requested count k, return the largest k scores in descending order. Keep duplicates because equal scores can belong to different observations. Accept k = 0, and reject values outside 0 through the input length.

Maintain a min-heap of the retained scores. Its smallest score is the threshold that a later score must exceed. After the first k scores, the heap contains the largest k scores from the processed prefix, including ties. Each later update preserves this invariant.

def largest_scores(values: list[int], k: int) -> list[int]:
"""Return the largest k values in descending order, preserving ties.
Args:
values: Integer scores in any order.
k: Number of scores to return, between zero and len(values).
Returns:
The largest k values in descending order.
Raises:
ValueError: If k is outside the supported range.
"""
if k < 0 or k > len(values):
raise ValueError("k must be between zero and the input length.")
if k == 0:
return []
retained = values[:k]
heapq.heapify(retained)
for index in range(k, len(values)):
if values[index] > retained[0]:
heapq.heapreplace(retained, values[index])
return sorted(retained, reverse=True)
scores = [6, 2, 9, 4, 8]
k = 3
retained = scores[:k]
heapq.heapify(retained)
print("Initial retained heap:", retained)
for index in range(k, len(scores)):
value = scores[index]
if value > retained[0]:
removed = heapq.heapreplace(retained, value)
print("Read:", value, "Replace:", removed, "Heap:", retained)
else:
print("Read:", value, "Keep heap:", retained)
print("Largest scores:", largest_scores(scores, k))
print("Original scores:", scores)
Initial retained heap: [2, 6, 9]
Read: 4 Replace: 2 Heap: [4, 6, 9]
Read: 8 Replace: 4 Heap: [6, 8, 9]
Largest scores: [9, 8, 6]
Original scores: [6, 2, 9, 4, 8]

If a new score does not exceed the threshold, at least k retained scores are already as large. Otherwise, replacing the minimum restores the largest-k invariant. The conditional check matters because heapreplace always removes the old minimum, even when its replacement is smaller.

Let n be the input length, with 1 <= k <= n. These costs assume constant-time comparisons between the integer scores. The initial copy and heap construction take O(k). Each later score takes O(1) comparison work and at most O(log k) repair work. Sorting the final answer takes O(k log k).

The complete bound is O(n log(k + 1)), which also expresses the linear case when k = 1. The heap and returned list each use O(k) space, so auxiliary space excluding the returned list is O(k). When k = 0, the function returns before scanning the input and uses O(1) time and space. Iterating over values[k:] instead would allocate an avoidable O(n) suffix copy.

assert largest_scores([], 0) == []
assert largest_scores([5, 5, 1], 2) == [5, 5]
assert largest_scores([-4, -1, -7], 1) == [-1]
assert largest_scores([3, 1, 2], 3) == [3, 2, 1]
try:
largest_scores([1, 2], 3)
except ValueError as error:
print(type(error).__name__, str(error))
print("Boundary checks passed.")
ValueError k must be between zero and the input length.
Boundary checks passed.
  • Solve Kth Largest Element in an Array with a heap of size k. State what the heap root means after the final input.
  • Solve Last Stone Weight by repeatedly selecting the largest values. For Python versions without max-heap functions, explain the effect of negating each stored weight.

Download the Python source to run the complete example locally.

Python’s heapq documentation defines the heap invariant and the difference between heapreplace and heappushpop. Those definitions explain the conditional replacement in this lesson.

Open Data Structures on binary heaps explains the implicit array representation and its logarithmic repair paths. It also derives linear-time heap construction.