CodeBlanks Logo Icon CodeBlanks

Min and max heap

Difference between min-heap and max-heap.

Min and max heap

In a min-heap each node is smaller than or equal to its children; the root is the smallest. In a max-heap each node is larger than or equal to its children; the root is the largest.

A heap is stored as a complete binary tree in an array. Parent (i-1)//2, left child 2i+1, right child 2i+2.

Min-heap is used to get the smallest element quickly in a priority queue; max-heap for the largest.

Parent-child

In the array representation, the parent of node at index i is (i-1)//2, left child 2i+1, right child 2i+2.

The root is arr[0] and has no parent. Leaves are in the second half of the array (i ≥ n//2).

These formulas give parent-child relations in O(1); no pointers needed.

Practice Check min-heap

Write is_min_heap(arr). Each child must be >= parent. Print True with print(is_min_heap([1, 3, 2, 5, 4])).

Starter code

solution.py
def is_min_heap(arr):
    # Check min-heap

Sample solution

solution.py
def is_min_heap(arr):
    # Check min-heap
    for i in range(1, len(arr)):
        if arr[(i - 1) // 2] > arr[i]:
            return False
    return True
print(is_min_heap([1, 3, 2, 5, 4]))

Expected output

True

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the root in a min-heap?

  • The largest
  • The smallest element Correct answer
  • The median
  • Random

Explanation: The smallest element

2 Parent

Question
parent = (i - 1) // ____
Answer
parent = (i - 1) // 2

Explanation: 2 is right.

3 Min and max heap: match the terms

Term Meaning
Min-heap Root smallest
Max-heap Root largest
Parent (i-1)//2
Left child 2i+1

All lessons in Intermediate