Skip to main content
Data Structures
CHAPTER 22 Beginner

Heaps and Priority Heaps

Updated: May 17, 2026
15 min read

# CHAPTER 22

Heaps and Priority Heaps

1. Introduction

In Chapter 15, we discovered the Priority Queue, a system where the most urgent data skips the line. We learned that using an Array was terribly slow O(n). We need a data structure that can instantly hand us the highest priority item in O(1) time, while organizing incoming data in blistering O(log n) time. Enter the Heap. A Heap is a bizarre, specialized variation of a Binary Tree. It completely abandons the "left-is-smaller, right-is-larger" rules of the BST. Instead, it operates on one primal law: *The absolute largest (or smallest) value must aggressively bubble up to the absolute Root of the tree.*

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define the architectural laws of Min-Heaps and Max-Heaps.
  • Understand how Complete Binary Trees allow Heaps to be secretly stored in flat Arrays.
  • Execute the Heapify (Bubble-Up / Sink-Down) algorithms.
  • Analyze the exact Time Complexity of extracting the Root node.

3. The Two Laws of the Heap

A Heap is a Binary Tree that strictly enforces two laws:

#### Law 1: The Shape Property (Complete Binary Tree) A Heap must be a Complete Binary Tree. This means every single level of the tree must be 100% full before starting a new level. Furthermore, the bottom level must be filled explicitly from Left to Right, with absolutely no gaps.

#### Law 2: The Heap Property (Max or Min)

  • Max-Heap: Every Parent node must be mathematically GREATER than or equal to both of its children. (The absolute largest number in the dataset sits on the Throne at the Root).
  • Min-Heap: Every Parent node must be mathematically SMALLER than or equal to both of its children. (The absolute smallest number sits at the Root).

*Crucial Note: Unlike a BST, there is NO mathematical relationship between siblings! The left child can be larger than the right child. The only rule is Parent > Children.*

4. The Array Secret (O(1) Pointers)

Because a Heap is a *Complete Binary Tree* with absolutely zero gaps, Computer Scientists realized something brilliant: We don't need memory pointers (node.left, node.right) at all! We can physically store the Tree inside a standard, flat Array, and use mathematical formulas to find the children instantly!

If a Parent Node is at array index i:

  • Left Child Index: (2 * i) + 1
  • Right Child Index: (2 * i) + 2
  • Parent Index: (i - 1) / 2

Visualizing the Array Trick:

text
1234567
Tree:       [100]
           /     \
         [50]    [70]
        /   \
      [10]  [20]

Array: [100, 50, 70, 10, 20]

*Index 1 is 50. Its left child is (2 * 1) + 1 = 3. Index 3 is 10. The math is perfectly flawless and requires zero RAM overhead for pointers!*

5. Insertion (Bubbling Up)

Let's insert 90 into the Max-Heap above.
  1. 1. Insert at the Bottom: Because it's a Complete Tree, 90 MUST be placed at the first available gap (the left child of 70). Array becomes: [100, 50, 70, 10, 20, 90].
  1. 2. Heapify Up (Bubble Up): 90 is larger than its parent 70. This violates the Max-Heap law! We swap them. 90 bubbles up.
  1. 3. Check again. 90 is smaller than the Root 100. The law is satisfied. The bubbling stops.

6. Deletion (Sinking Down)

You can only ever delete the Root node (the highest priority item).
  1. 1. Remove Root: 100 is extracted. The throne is empty.
  1. 2. Move the Bottom up: Take the absolute last element in the array (70) and place it on the Root throne.
  1. 3. Heapify Down (Sink Down): 70 looks at its children (50 and 90). 90 is larger! 70 swaps with 90, sinking down to restore the Max-Heap law.

7. Implementation Concept

python
123456789101112131415161718
# Python Example: Max-Heap Sinking Algorithm (Heapify Down)
def heapify_down(arr, n, i):
    largest = i           # Assume Parent is largest
    left = 2 * i + 1      # Left child math
    right = 2 * i + 2     # Right child math

    # Is left child larger than Parent?
    if left < n and arr[left] > arr[largest]:
        largest = left

    # Is right child larger than the current largest?
    if right < n and arr[right] > arr[largest]:
        largest = right

    # If the Parent is NOT the largest, SWAP and recurse!
    if largest != i:
        arr[i], arr[largest] = arr[largest], arr[i] # Swap
        heapify_down(arr, n, largest) # Recursively sink down!

8. Complexity Analysis

Because the tree is a perfectly compact Complete Binary Tree, the height is mathematically locked to exactly log(n).
OperationTime Complexity
Get Max/Min (Peek)O(1)
InsertO(log n) (Bubbling up the height of the tree)
Delete/Extract RootO(log n) (Sinking down the height of the tree)

9. Real-World Applications

  1. 1. Priority Queues: As covered in Chapter 15, Heaps are the explicit engine driving OS Task Scheduling and Dijkstra's Shortest Path algorithm.
  1. 2. Heap Sort: One of the most efficient sorting algorithms in existence. You dump an array of unsorted numbers into a Min-Heap (takes O(n log n)), and then you extract_root() over and over. The numbers pop out in perfect sorted order!

10. Common Mistakes

  • Confusing a Heap with a BST: A Heap is NOT sorted horizontally! If you do an In-Order traversal of a Heap, the numbers will print out in complete gibberish. A Heap only guarantees vertical sorting (Parent > Child). Do not use a Heap to search for a random number X (it will take O(n) time). Use it strictly to find the Maximum or Minimum.

11. Exercises

  1. 1. Trace the Array math: If an element sits at Array index 6, what are the exact Array indexes of its Parent, its Left Child, and its Right Child?
  1. 2. Draw a Max-Heap containing 10, 20, 15, 30, 40. *(Hint: Insert them one by one and Bubble Up!)*

12. MCQs with Answers

Question 1

What Abstract Data Type (ADT) is natively powered by the underlying architecture of a Binary Heap?

Question 2

What is the fundamental, uncompromising architectural difference between a Binary Search Tree (BST) and a Binary Heap?

Question 3

To mathematically prevent memory fragmentation, what specific "Shape Property" must a Binary Heap adhere to?

Question 4

Because a Heap perfectly adheres to the Complete Binary Tree shape, how do Senior Architects physically store the data in RAM?

Question 5

In the Array representation of a Heap, if a Parent Node resides at index i, what mathematical formula instantly yields the index of its Right Child?

Question 6

During the Insertion phase of a Max-Heap, a new value is placed at the absolute bottom of the tree. What algorithmic mechanism is triggered if the new value is mathematically larger than its Parent?

Question 7

What is the guaranteed execution Time Complexity for extracting the absolute Maximum value (the Root) from a Max-Heap containing 10 billion records?

Question 8

When an algorithm calls extract_root() on a Heap, what specific Node is aggressively ripped from the absolute bottom of the tree and placed onto the newly vacated Root throne to initiate the Sink-Down process?

Question 9

If a developer needs to locate the number 42 within a Min-Heap of 1 million integers, what is the Time Complexity of that search operation?

Question 10

Why is the "Heap Sort" algorithm highly favored in systems with extreme physical memory constraints (like embedded microchips)?

13. Interview Preparation

Top Interview Questions:
  • *Algorithmic Coding:* "Find the K-th largest element in an unsorted array of 1 million numbers." *(Answer: Do NOT sort the massive array! That takes O(N log N). Instead, create a Min-Heap of size K. Loop through the array, pushing numbers into the Heap. If the heap size exceeds K, pop the smallest element. At the end of the loop, the absolute root of your tiny Heap is the K-th largest number! Time Complexity: O(N log K)!).*

Common Pitfalls:

  • In whiteboard interviews, accidentally drawing a Heap that is not a Complete Binary Tree. If you draw a right child without first drawing a left child, you have fundamentally broken the underlying Array mathematics, and the interviewer will fail the diagram.

14. FAQs

Q: Is the Array index math different if the Array starts at 1 instead of 0? A: Yes! In older textbooks, they start the Heap at index 1. The math becomes beautifully simpler: Left Child is 2*i. Right Child is 2*i + 1. Parent is i/2. However, since all modern languages use zero-indexed arrays, you must use the 2*i + 1 formulas in actual code!

15. Summary

The Heap is a masterpiece of memory optimization. By forcing the Tree into a perfectly compact shape, we abandon slow memory pointers in favor of blistering fast mathematical array indexes. The Heap ruthlessly elevates the most critical data to the Root, powering the scheduling systems of the modern world.

16. Next Chapter Recommendation

We have optimized numbers and priorities perfectly. But what about Words? If you type "C-A-T" into Google, how does it instantly suggest "Catalog" and "Category" out of a dictionary of 10 million words? In Chapter 23: Trie Data Structure, we will explore the hyper-specialized Tree that rules Search Engines.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·