1. University MCA (AI/ML) Semester 2
  2. CAP7004
  3. Unit 5

CAP7004 · Unit 5: Trees

Heaps and priority queues

8 practice questions

Key points

  • Min-heap root is the smallest; complete tree in an array
  • Parent (i-1)//2; children 2i+1, 2i+2
  • Push/pop O(log n), peek O(1), heapify O(n)
  • heapq is a min-heap; negate values for max-heap

A binary heap is a complete binary tree with the heap property. In a min-heap every parent is <= its children, so the minimum is at the root; a max-heap is the reverse.

Array layout (0-based): parent of i is (i - 1) // 2; children are 2i + 1 and 2i + 2. Completeness means no gaps in the array.

Operations:

  • Insert (heappush): add at the end, sift up while smaller than the parent. O(log n).
  • Extract-min (heappop): take the root, move the last element to the root, sift down. O(log n).
  • Peek at the min: h[0], O(1).
  • Build-heap (heapify) from n items: O(n), not O(n log n).
  • Heap sort: build a heap then extract n times: O(n log n), in place, not stable.

Python `heapq` is a min-heap on a list. Pushing 5, 3, 8, 1, 9, 2 gives the array [1, 3, 2, 5, 9, 8]; after heappop it is [2, 3, 8, 5, 9]. For a max-heap push negated values. heapq.nlargest(2, xs) and nsmallest(2, xs) return the extremes. Tuples such as (priority, item) give a priority queue: smallest priority first.

Applications: priority queues, scheduling, Dijkstra, k-largest problems.

Exam pitfall: a heap is not sorted; only parent-child order is guaranteed.

Try two questions

Question 1 · Tier 1, Recall

In a min-heap, the smallest element is at:

  1. A leaf
  2. The middle
  3. The last array position
  4. The root
Show the answer

D. The heap property puts the minimum at the top.

Question 2 · Tier 2, Understand

Time complexity of heapq.heappush and heappop is:

  1. O(n log n)
  2. O(log n)
  3. O(n)
  4. O(1)
Show the answer

B. Sift up or down follows a path whose length is the tree height.