1. Gyanastra
  2. Data Structures
  3. UGC NET: Advanced Data Structures
  4. Heaps and Priority Queues
Free lesson, no account needed 9 min read 12 practice questions after it
Asked in past papers3 times
  • GATE CSE2025
  • UGC NET20172004

Data Structures · UGC NET: Advanced Data Structures

Heaps and Priority Queues

Overview

A heap is a complete binary tree stored in an array that maintains a parent-child order.
A priority queue is an abstract data type in which each element has a priority and the highest or lowest priority element is removed first.
This topic belongs to Advanced Data Structures and is tested through array validity, heap operations, build-heap traces, priority-queue implementation, and complexity comparisons.
You need prior comfort with arrays, binary trees, recursion, and asymptotic notation.

Key concepts

  • A priority queue is an Abstract Data Type supporting INSERT, MAXIMUM or MINIMUM, EXTRACT-MAX or EXTRACT-MIN, and INCREASE-KEY or DECREASE-KEY. A max-priority queue removes the largest priority; a min-priority queue removes the smallest.
  • A binary heap implements a priority queue using an array interpreted as a complete binary tree: all levels are full except possibly the last, and the last level is filled from left to right. The array has no gaps.
  • A max-heap satisfies the heap-order property: for every node ii, A[parent(i)]≥A[i]A[\text{parent}(i)] \ge A[i]. A min-heap satisfies A[parent(i)]≤A[i]A[\text{parent}(i)] \le A[i].
  • There is no ordering between siblings. A heap is not sorted; only the parent-child relation is guaranteed.
  • In the standard 1-indexed array convention, for a node at index ii: parent is ⌊i/2⌋\lfloor i/2 \rfloor, left child is 2i2i, right child is 2i+12i+1. For 0-indexed arrays, parent is ⌊(i−1)/2⌋\lfloor (i-1)/2 \rfloor, left is 2i+12i+1, right is 2i+22i+2.
  • For nn elements, heap height with root at level 0 is ⌊log⁡2n⌋\lfloor \log_2 n \rfloor. Internal nodes are indices 11 to ⌊n/2⌋\lfloor n/2 \rfloor; leaves are indices ⌊n/2⌋+1\lfloor n/2 \rfloor+1 to nn.
  • In a max-heap, the maximum is at the root in O(1)O(1). The minimum must occur among the leaves; finding it needs O(n)O(n) worst-case scanning. In a min-heap the opposite holds.
  • MAX-HEAPIFY restores the heap property in O(log⁡n)O(\log n). BUILD-MAX-HEAP uses bottom-up heapify in O(n)O(n). Insert and extract are O(log⁡n)O(\log n).
  • Insertion: append the new key at the end, then bubble it upward while it is larger than its parent. Extract-max: save the root, move the last element to the root, reduce heap size, then heapify down.
  • HEAP-INCREASE-KEY in a max-heap moves the key upward. HEAP-DECREASE-KEY in a max-heap moves the key downward. In a min-heap, the directions reverse.
  • A binary heap is the standard implementation of a priority queue. A balanced binary search tree also supports dynamic-set operations, but a heap is simpler and faster for repeated priority extraction.
  • Heap sort builds a max-heap and repeatedly extracts the maximum. It runs in O(nlog⁡n)O(n\log n), is in-place, and is not stable.
  • With nn distinct keys, the number of distinct binary max-heaps satisfies a recurrence based on choosing keys for the left subtree; the root is always the maximum.

How it works

  1. Array-to-tree mapping. Treat A[1]A[1] as the root. For every index ii, its children are 2i2i and 2i+12i+1 if those indices are at most heap size. This creates exactly one complete binary tree shape for each nn.
  2. Check heap validity. For a max-heap, scan internal nodes i=1i=1 to ⌊n/2⌋\lfloor n/2 \rfloor. At each node, verify A[i]≥A[2i]A[i] \ge A[2i] when the left child exists and A[i]≥A[2i+1]A[i] \ge A[2i+1] when the right child exists. For a min-heap, reverse the inequalities.
  3. MAX-HEAPIFY(A, i). Assume the subtrees of ii are already max-heaps. Compare A[i]A[i] with its left and right children. Let largestlargest be the largest among them. If largest≠ilargest \ne i, swap A[i]A[i] with A[largest]A[largest] and recursively call MAX-HEAPIFY on largestlargest.
    Otherwise stop. Cost is O(log⁡n)O(\log n).
  4. BUILD-MAX-HEAP(A). Set heap size nn. For i=⌊n/2⌋i=\lfloor n/2 \rfloor down to 11, call MAX-HEAPIFY(A, i). Starting below the leaves works because each child subtree is already a heap. Total cost is O(n)O(n), not O(nlog⁡n)O(n\log n).
  5. Insert a key. Increase heap size by 1, place the key at the new last index, and repeatedly swap it with its parent while it is larger than the parent. This is equivalent to HEAP-INCREASE-KEY on the last position.
  6. Extract-maximum. Save A[1]A[1]. Copy the last element into A[1]A[1], reduce heap size by 1, and call MAX-HEAPIFY(A, 1) if the heap is non-empty. Return the saved maximum.
  7. Increase-key. If a max-heap key at index ii is increased, compare it upward with its parent and swap while it is larger. Stop when it is not larger than the parent or reaches the root.
Figure. The new key is placed at the next array position and repeatedly swapped with its parent when larger. Insertion stops when the child is not larger than the parent, leaving a valid max-heap.

Formulas

  • Use 1-indexed arrays A[1…n]A[1\dots n]; nn is the current heap size, and root is at level 0.

parent(i)=⌊i2⌋,left(i)=2i,right(i)=2i+1\text{parent}(i)=\left\lfloor \frac{i}{2}\right\rfloor,\qquad \text{left}(i)=2i,\qquad \text{right}(i)=2i+1

height of heap=⌊log⁡2n⌋\text{height of heap}=\left\lfloor \log_2 n\right\rfloor

internal nodes=1…⌊n2⌋,leaves=⌊n2⌋+1…n\text{internal nodes}=1\ldots \left\lfloor \frac{n}{2}\right\rfloor,\qquad \text{leaves}=\left\lfloor \frac{n}{2}\right\rfloor+1\ldots n

number of leaves=n−⌊n2⌋=⌈n2⌉\text{number of leaves}=n-\left\lfloor \frac{n}{2}\right\rfloor=\left\lceil \frac{n}{2}\right\rceil

TMAX-HEAPIFY(n)≤T(2n/3)+Θ(1)=O(log⁡n)T_{\text{MAX-HEAPIFY}}(n)\le T(2n/3)+\Theta(1)=O(\log n)

TBUILD-MAX-HEAP(n)=∑h=0⌊log⁡2n⌋⌈n2h+1⌉O(h)=O(n)T_{\text{BUILD-MAX-HEAP}}(n)=\sum_{h=0}^{\lfloor \log_2 n\rfloor} \left\lceil \frac{n}{2^{h+1}}\right\rceil O(h)=O(n)

Tinsert=Textract-max=O(log⁡n),Tfind-max=O(1),Tfind-min in max-heap=O(n)T_{\text{insert}}=T_{\text{extract-max}}=O(\log n),\qquad T_{\text{find-max}}=O(1),\qquad T_{\text{find-min in max-heap}}=O(n)

  • For distinct keys, number of binary max-heaps: H(0)=H(1)=1,H(n)=(n−1L)H(L)H(R)H(0)=H(1)=1,\qquad H(n)=\binom{n-1}{L}H(L)H(R)
  • where LL and RR are the sizes of the left and right subtrees of the complete binary tree with nn nodes, and L+R=n−1L+R=n-1. The root is fixed as the maximum key.

Worked examples

Example 1: Is the array a max-heap?
Check A=[30,20,18,12,15,10,8]A=[30,20,18,12,15,10,8], n=7n=7.
Internal nodes are i=1,2,3i=1,2,3.
i=1i=1: children 20,1820,18; 30≥2030\ge20 and 30≥1830\ge18.
i=2i=2: children 12,1512,15; 20≥1220\ge12 and 20≥1520\ge15.
i=3i=3: children 10,810,8; 18≥1018\ge10 and 18≥818\ge8.
All checks pass, so it is a valid max-heap.

Example 2: Insert 15, 10, 25, 8, 20 into an empty max-heap.
Insert 15: [15][15].
Insert 10: [15,10][15,10].
Insert 25: append [15,10,25][15,10,25], swap with parent 1515: [25,10,15][25,10,15].
Insert 8: append [25,10,15,8][25,10,15,8]; parent 1010, no swap.
Insert 20: append [25,10,15,8,20][25,10,15,8,20], swap with 1010: [25,20,15,8,10][25,20,15,8,10]; parent 2525, stop.
Final max-heap: [25,20,15,8,10][25,20,15,8,10].

Example 3: Floyd’s bottom-up build-max-heap.
Start A=[4,11,7,19,8,6]A=[4,11,7,19,8,6], n=6n=6. Start at i=⌊6/2⌋=3i=\lfloor6/2\rfloor=3.
i=3i=3: value 77, child 66; no swap.
i=2i=2: value 1111, children 19,819,8; swap with 1919: [4,19,7,11,8,6][4,19,7,11,8,6].
i=1i=1: value 44, children 19,719,7; swap with 1919: [19,4,7,11,8,6][19,4,7,11,8,6]; then at index 2, value 44, children 11,811,8; swap with 1111: [19,11,7,4,8,6][19,11,7,4,8,6].
Final heap: [19,11,7,4,8,6][19,11,7,4,8,6]. Height is ⌊log⁡26⌋=2\lfloor\log_2 6\rfloor=2; right child of root is A[3]=7A[3]=7.

Example 4: Count distinct max-heaps for 4 distinct keys.
Take keys {5,10,15,20}\{5,10,15,20\}, n=4n=4. The complete tree has left subtree size L=2L=2, right subtree size R=1R=1. Root must be 2020. Choose 2 of the remaining 3 keys for the left subtree: (32)=3\binom{3}{2}=3. A 2-node max-heap has H(2)=1H(2)=1; a 1-node heap has H(1)=1H(1)=1. Hence H(4)=3⋅1⋅1=3H(4)=3\cdot1\cdot1=3.

Example 5: Match operations with worst-case costs in a max-heap.
FIND-MAX takes O(1)O(1) because the root is maximum.
EXTRACT-MAX takes O(log⁡n)O(\log n) because it calls heapify once.
BUILD-MAX-HEAP from an unsorted array takes O(n)O(n).
SEARCH for an arbitrary key takes O(n)O(n) because heap order does not order siblings or subtrees.

Comparison

FeatureMax-heapMin-heap
Parent-child ruleParent ≥\ge childrenParent ≤\le children
RootLargest keySmallest key
Fast extractionExtract-maxExtract-min
Finding opposite extremeMinimum in O(n)O(n), among leavesMaximum in O(n)O(n), among leaves
Key increaseBubble upwardMay require heapify down
ImplementationInsertPeek extremeExtract extremeSearch arbitrary key
Binary heapO(log⁡n)O(\log n)O(1)O(1)O(log⁡n)O(\log n)O(n)O(n)
Balanced BSTO(log⁡n)O(\log n) averageO(log⁡n)O(\log n)O(log⁡n)O(\log n)O(log⁡n)O(\log n) average
Sorted arrayO(n)O(n)O(1)O(1)O(1)O(1)O(log⁡n)O(\log n)
Unsorted arrayO(1)O(1)O(n)O(n)O(n)O(n)O(n)O(n)
PointBUILD-MAX-HEAPRepeated insertion
MethodBottom-up heapifyAppend and bubble up
CostO(n)O(n)O(nlog⁡n)O(n\log n)
UseConvert an existing array into a heapInsert elements one by one

Revision summary

  • A binary heap is a complete binary tree with a parent-child order; it is not a sorted array.
  • 1-indexed: parent ⌊i/2⌋\lfloor i/2\rfloor, children 2i2i and 2i+12i+1; 0-indexed shifts by one.
  • Height is ⌊log⁡2n⌋\lfloor\log_2 n\rfloor; root is at level 0.
  • Leaves are indices ⌊n/2⌋+1…n\lfloor n/2\rfloor+1\ldots n; internal nodes are 1…⌊n/2⌋1\ldots\lfloor n/2\rfloor.
  • In a max-heap, max is at root O(1)O(1); min lies among leaves and costs O(n)O(n) to find.
  • Build-heap is O(n)O(n); inserting nn elements one by one is O(nlog⁡n)O(n\log n).
  • Insert bubbles up; extract-max replaces root by last and heapifies down.
  • Increase-key in a max-heap moves upward; decrease-key moves downward.
  • A heap is the standard priority-queue implementation, not a general-purpose search tree.
  • Arbitrary search or deletion by value in a heap is O(n)O(n); use a balanced BST for general dynamic-set operations.
  • Count distinct heaps only for distinct keys, using the complete-tree left and right subtree sizes.

Previous-year exam insights

  • Array-validity questions are direct: check every internal node against its children.
    A single violation deep in the array makes the option wrong.
  • “Smallest element in a max-heap” is a classic trap.
    It is not at the root; it is among the leaves and requires O(n)O(n) worst-case time.
  • Tree-diagram valid-heap questions test the heap-order property on every parent-child edge, not left-right symmetry.
  • Build-heap questions expect bottom-up heapify from ⌊n/2⌋\lfloor n/2\rfloor down to 1, not repeated insertion.
    Check the final array and the root’s children separately.
  • Priority-queue implementation questions usually expect binary heap. For insert/delete of arbitrary numbers in a stored set, a balanced binary tree or BST is the intended dynamic-set structure.
  • Insertion-sequence questions require append-then-bubble-up tracing.
    The final array is a heap, not a sorted array.
  • Match-the-list questions mix O(1)O(1), O(log⁡n)O(\log n), O(n)O(n), and O(nlog⁡n)O(n\log n): know find-extreme, extract, build, and arbitrary search separately.
  • Statement questions often test height ⌊log⁡2n⌋\lfloor\log_2 n\rfloor, complete-tree shape, duplicates in heaps, and the fact that heap order is partial, not total.

Practice at PARIKSHA

You are ready for the PARIKSHA tests of this sub-topic when you can:

  • Write parent, left-child, and right-child indices in both 1-indexed and 0-indexed arrays.
  • Test any array for max-heap or min-heap validity in linear time.
  • State where the smallest element can lie in a max-heap and justify the O(n)O(n) bound.
  • Trace a sequence of insertions into an empty max-heap and write the final array.
  • Run Floyd’s BUILD-MAX-HEAP from an unsorted array, showing every swap.
  • Trace EXTRACT-MAX and give the first few extracted keys.
  • Match heap operations with their worst-case complexities.
  • Explain why a binary heap is preferred for a priority queue and when a BST is better.
  • Count distinct max-heaps for small nn using subtree sizes and binomial coefficients.
  • Distinguish heap search by value from heap access to the root or to a known index.

Attempt the PARIKSHA sub-topic test first, then the subject test.

Pages 1–2 of 2