liveBook · Manning

Min-heap

As explained in Grokking Data Structures

A min-heap is a heap in which every parent has a value no larger than its children, so the root contains the smallest element.

A min-heap keeps its smallest element at the root: every parent has a value no larger than either child. Think of it as a priority queue where smaller numbers receive higher priority. section 10.13

A min-heap is useful when you need to:

  • Extract the next-smallest element repeatedly. section 10.13
  • Keep only the k best candidates while scanning n entries. section 10.21
  • Implement the ordering rule through a priority function, such as priority(x) = -x when smaller values should appear first. section 10.13

Keeping the six largest entries

Scan the entries one by one while storing only six in a min-heap. The root is the least frequent item among the current six; when a new entry is better, remove that root and insert the new entry. This takes O(n*log(k)) steps and O(k) extra space. section 10.21

def k_largest_elements(arr, k):
    heap = Heap(element_priority=lambda x: -x[1])
    for i in range(len(arr)):
        if len(heap) >= k:
            if heap.peek()[1] < arr[i]:
                heap.top()                 #1
                heap.insert((i, arr[i]))
        else:
            heap.insert((i, arr[i]))
    return [heap.top() for _ in range(k)]

print(k_largest_elements(drawn, 6))
#1 When we remove the smallest element, we don’t need the value. We just discard it.

The Python listing demonstrates a bounded min-heap using a custom priority function for selecting frequent entries. section 10.21

How Grokking Data Structures covers it

How deep it goes
Defines parent–child ordering, explains priority inversion, and applies the structure to bounded selection without detailing heap implementation.
Examples
Demonstrates six-largest selection from lottery-frequency entries using a Python heap and a custom priority function.
What you can do after
Apply a min-heap to extract small elements and solve top-k selection with bounded additional space.
How it connects
Connects min-heaps with heaps, max-heaps, priority queues, priority functions, and almost complete trees.

Also explained in

Compare how 2 books explain min-heap →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Data Structures. The section links point to the parts of the book it draws on.