Data Structures & Algorithms chapters (13)
  1. 01Introduction to DSA
  2. 02Arrays & Strings Algorithms
  3. 03Searching & Sorting Algorithms
  4. 04Asymptotic Analysis & Complexity
  5. 05Linked Lists
  6. 06Stacks & Queues
  7. 07Hashing & Hash Tables
  8. 08Recursion & Backtracking
  9. 09Binary Trees & BST
  10. 10Heaps & Priority Queues
  11. 11Graphs & Graph Algorithms
  12. 12Greedy Algorithms & Bit Manipulation
  13. 13Dynamic Programming (DP)

Chapter 10

Heaps & Priority Queues

3 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

A binary heap is a complete binary tree stored in an array that keeps the min (or max) at the root; insert and extract are O(log n), peek is O(1), and building is O(n).

It implements priority queues, heap sort and Top-K selection.

Heaps underpin Dijkstra, Prim, scheduling and streaming problems; "build heap is O(n)" is a classic GATE proof.

OS task schedulers, event simulation, A* search, top trending items, median of data stream.

1

Binary Heap & Priority Queue

A binary heap is a complete binary tree with the heap property: in a min-heap each parent <= its children (root is the minimum); in a max-heap each parent >= children. A priority queue is an ADT (insert, extract-min/max, peek) commonly implemented with a heap.

In short: A tree where the boss is always the smallest (or largest), stored compactly in an array.

Heap: parent beats children (priority)

Think about it

GATE asks heap array layout, resulting arrays after operations, and complexities.

Array 0-indexed: parent (i-1)//2, left 2i+1, right 2i+2 (1-indexed: i//2, 2i, 2i+1).

Height = floor(log2 n).

Leaves occupy indices n//2 ..

n-1 so there are ceil(n/2) leaves.

Insert: append at the end, sift up while smaller than parent: O(log n).

Extract-min: swap root with last, remove last, sift down choosing the smaller child: O(log n).

Peek O(1).

Search arbitrary key O(n); delete arbitrary node O(log n) given its index; decrease-key O(log n) (sift up).

A heap is NOT sorted - only parent-child order holds; in a min-heap the maximum is somewhere among the leaves (n/2 candidates).

Compared to a sorted array (insert O(n)) and BST (O(log n) balanced, but more memory and pointer overhead) the heap is cache-friendly and simplest for min/max queries.

Fibonacci heap gives amortized O(1) insert/decrease-key (theoretical benefit for Dijkstra).

Python heapq is a min-heap only: for a max-heap push negated keys.

Ties and tuples: use (priority, counter, item) to avoid comparing uncomparable items.

Key points

  • Heap property: Parent <= children (min) or >= (max).
  • Sift-up / sift-down: Bubble a node toward the root / toward leaves to restore order.
  • Priority queue: ADT serving the element of highest priority first.
  • Operations: insert O(log n), extract O(log n), peek O(1), build O(n), search O(n).
  • Max element of a min-heap is at a leaf: finding it takes O(n).

Example

Code
Min-heap implementation:
class MinHeap:
    def __init__(self): self.a = []
    def push(self, x):
        a = self.a; a.append(x); i = len(a) - 1
        while i and a[(i - 1) // 2] > a[i]:
            a[(i - 1) // 2], a[i] = a[i], a[(i - 1) // 2]
            i = (i - 1) // 2
    def pop(self):
        a = self.a
        a[0], a[-1] = a[-1], a[0]
        top = a.pop()
        self._down(0)
        return top
    def _down(self, i):
        a, n = self.a, len(self.a)
        while True:
            s, l, r = i, 2 * i + 1, 2 * i + 2
            if l < n and a[l] < a[s]: s = l
            if r < n and a[r] < a[s]: s = r
            if s == i: return
            a[i], a[s] = a[s], a[i]; i = s

import heapq
h = []; heapq.heappush(h, 5); heapq.heappush(h, 1)
print(heapq.heappop(h))            # 1
max_heap = []; heapq.heappush(max_heap, -7)   # max-heap via negation
2

Heapify & Heap Sort

Heapify (build-heap) converts an arbitrary array into a heap by sifting down every internal node from index n//2 - 1 down to 0, in O(n) time. Heap sort builds a max-heap, then repeatedly swaps the root with the last element and sifts down on the shrinking heap: O(n log n), in place, not stable.

In short: Fix the heap from the bottom up, then repeatedly pull the biggest element to the end.

Think about it

The O(n) proof is a perennial GATE favourite; heap sort is the in-place O(n log n) worst-case sort.

Why build-heap is O(n) and not O(n log n): a node at height h costs O(h) to sift down and there are at most ceil(n / 2^(h+1)) nodes of height h, so total = sum over h of n/2^(h+1) * h = O(n * sum h/2^h) = O(n) (the series converges to 2).

Inserting n elements one by one is O(n log n).

Heap sort: build O(n), then n-1 extractions each O(log n): O(n log n) in best, average and worst case; space O(1); not stable; poor cache behaviour so quick sort is faster in practice, but heap sort has the worst-case guarantee (used inside introsort).

Ascending order uses a max-heap (largest goes to the end); descending uses a min-heap.

Number of comparisons for build-heap is at most 2n.

Heapifying [4,10,3,5,1]: sift 10 (index 1) -> children 5,1, ok; sift 4 at root swaps with 10: [10,5,3,4,1], then 4 vs children (index 3,4: none).

Partial heap sort (k extractions) finds the k largest in O(n + k log n).

Key points

  • Heapify: Restore heap order at a node by sifting down.
  • Build-heap: Heapify from last internal node to the root.
  • In-place: O(1) auxiliary memory.

Example

Code
Build-heap and heap sort:
def sift_down(a, i, n):             # max-heap
    while True:
        big, l, r = i, 2 * i + 1, 2 * i + 2
        if l < n and a[l] > a[big]: big = l
        if r < n and a[r] > a[big]: big = r
        if big == i: return
        a[i], a[big] = a[big], a[i]
        i = big

def build_max_heap(a):               # O(n)
    for i in range(len(a) // 2 - 1, -1, -1):
        sift_down(a, i, len(a))

def heap_sort(a):                    # O(n log n), O(1) space
    n = len(a)
    build_max_heap(a)
    for end in range(n - 1, 0, -1):
        a[0], a[end] = a[end], a[0]
        sift_down(a, 0, end)
3

Top K Elements Pattern

To find the K largest elements keep a MIN-heap of size K: for each element, push it; if size exceeds K pop the smallest. The heap ends with the K largest. Time O(n log k), space O(k). For K smallest use a max-heap.

In short: Keep a small leaderboard of K; the weakest member (heap top) is kicked out whenever a better one arrives.

Think about it

Top-K and merge-K are the most common heap interview patterns and test the choice of heap direction.

Using the opposite heap type is the key insight: the root of the min-heap is the K-th largest so far and the cheapest to compare/evict.

Alternatives: sort O(n log n); heapify all then pop k: O(n + k log n); quickselect O(n) expected.

Choose heap for streaming data or when k << n.

K-th largest = root of the size-K min-heap.

Top K frequent: count with a hash map (O(n)), then size-K min-heap on counts: O(n log k) (or bucket sort O(n)).

K closest points to origin: max-heap of size K on distance.

Merge K sorted lists: min-heap of (value, list index): O(N log K) where N is total elements.

Running median: max-heap for the lower half and min-heap for the upper half, rebalanced so sizes differ by at most 1: add O(log n), median O(1).

K-th smallest in a sorted matrix with heap: O((k + n) log n).

Task scheduling and Huffman coding also use extract-two-minimum loops.

Edge cases: k > n, k = 0, ties, negative numbers.

Key points

  • Size-K heap: Fixed-capacity heap holding the best K seen so far.
  • Two-heap median: Max-heap lower half + min-heap upper half.
  • Quickselect: Average O(n) selection of k-th element.

Example

Code
Top-K, merge K, running median:
import heapq
from collections import Counter

def k_largest(nums, k):               # O(n log k)
    h = []
    for x in nums:
        heapq.heappush(h, x)
        if len(h) > k: heapq.heappop(h)
    return sorted(h, reverse=True)

def top_k_frequent(nums, k):
    cnt = Counter(nums)
    return [x for x, _ in heapq.nlargest(k, cnt.items(), key=lambda p: p[1])]

def merge_k_lists(lists):             # lists of sorted ints, O(N log K)
    h = [(l[0], i, 0) for i, l in enumerate(lists) if l]
    heapq.heapify(h); out = []
    while h:
        v, i, j = heapq.heappop(h); out.append(v)
        if j + 1 < len(lists[i]):
            heapq.heappush(h, (lists[i][j + 1], i, j + 1))
    return out

class MedianFinder:
    def __init__(self): self.lo, self.hi = [], []     # lo = max-heap (neg)
    def add(self, x):
        heapq.heappush(self.lo, -x)
        heapq.heappush(self.hi, -heapq.heappop(self.lo))
        if len(self.hi) > len(self.lo):
            heapq.heappush(self.lo, -heapq.heappop(self.hi))
    def median(self):
        if len(self.lo) > len(self.hi): return -self.lo[0]
        return (-self.lo[0] + self.hi[0]) / 2

Solved examples

Example 01 · Basic

Insert 10, 4, 7, 2, 9 one by one into a min-heap. Give the array.

Given Data:
    Required To Find:

    Array

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: [10]; add 4 -> swap -> [4,10].
    Step 2: add 7 -> [4,10,7].
    Step 3: add 2 at idx3, parent idx1 (10) swap, parent idx0 (4) swap -> [2,4,7,10].
    Step 4: add 9 at idx4, parent idx1 (4) ok -> [2,4,7,10,9].
    Final Answer: [2, 4, 7, 10, 9]

    Approach note: Parent of index i is (i-1)//2.

    Example 02 · Intermediate

    Build a max-heap from [3, 9, 2, 1, 4, 5] using bottom-up heapify.

    Given Data:
      Required To Find:

      Array

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: n=6: start at index 2 (value 2); children idx5 (5): swap -> [3,9,5,1,4,2].
      Step 2: idx1 (9): children 1,4 -> fine.
      Step 3: idx0 (3): children 9,5 -> swap with 9 -> [9,3,5,1,4,2]; then 3 vs children 1,4 -> swap with 4 -> [9,4,5,1,3,2].
      Final Answer: [9, 4, 5, 1, 3, 2]

      Approach note: Start at the last internal node.

      Example 03 · Advanced

      Find the 3rd largest in a stream [5, 2, 8, 1, 9, 3] using a heap.

      Given Data:
        Required To Find:

        Heap state and answer

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: k=3 min-heap: add 5,2,8 -> {2,5,8}.
        Step 2: add 1 -> size 4, pop 1 -> {2,5,8}.
        Step 3: add 9 -> pop 2 -> {5,8,9}.
        Step 4: add 3 -> pop 3 -> {5,8,9}.
        Step 5: Root = 5.
        Final Answer: 5 (time O(n log 3))

        Approach note: Min-heap root is the K-th largest.

        Example 04 · Basic

        In a 1-indexed max-heap array [_, 20, 15, 10, 8, 12], what are the children indexes of the node at index 2?

        Given Data:
          Required To Find:

          Child indexes and values

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: Left child index = 2*i = 4 → value 8
          Step 2: Right child index = 2*i+1 = 5 → value 12
          Final Answer: Indexes 4 and 5 (values 8 and 12)

          Approach note: Parent of i is floor(i/2).

          Real-world applications

          DSA

          Using Heaps & Priority Queues in real projects

          OS task schedulers, event simulation, A* search, top trending items, median of data stream.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: A heap is a sorted array.

          Why this is wrong: Only parent-child order is enforced; siblings and levels are not ordered.

          ✅ Verified Truth: Heap gives O(1) min/max, not sorted traversal.

          ⚠️ Exam Tip: Array [1,5,2,6,7,3] is a valid min-heap but not sorted.

          ❌ Myth: Building a heap from n elements is O(n log n).

          Why this is wrong: Most nodes are near the leaves and sift very short distances.

          ✅ Verified Truth: Bottom-up heapify is O(n); repeated insertion is O(n log n).

          ⚠️ Exam Tip: Quote sum of h/2^h converging to 2.

          ❌ Myth: Use a max-heap to find the K largest.

          Why this is wrong: A max-heap of size K evicts the wrong element; you need to evict the smallest.

          ✅ Verified Truth: Use a min-heap of size K for K largest (max-heap for K smallest).

          ⚠️ Exam Tip: The heap root should be the candidate to discard.

          Revision notes

          A binary heap is a complete binary tree stored in an array that keeps the min (or max) at the root; insert and extract are O(log n), peek is O(1), and building is O(n). It implements priority queues, heap sort and Top-K selection.

          High-Yield Quick Revision Points

          1. Min-heap: parent <= children; parent (i-1)//2, children 2i+1, 2i+2
          2. insert/extract O(log n), peek O(1), build O(n)
          3. Heap sort: max-heap, swap root to end, sift-down; O(n log n), in place, unstable
          4. Top K largest: min-heap size K, O(n log k); merge K lists O(N log K)
          5. Median: max-heap (low) + min-heap (high)

          Practice questions

          Question 1 · MCQ (GATE)

          Time to build a heap from n elements bottom-up:

          Question 2 · MCQ (GATE)

          Index of the left child of node i (0-indexed array):

          Question 3 · MCQ (GATE)

          Where is the maximum in a min-heap?

          Question 4 · MCQ (GATE)

          Heap sort worst-case time and space:

          Question 5 · MCQ (Interview)

          Merging K sorted lists with N total elements using a heap: