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,MAXIMUMorMINIMUM,EXTRACT-MAXorEXTRACT-MIN, andINCREASE-KEYorDECREASE-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 , . A min-heap satisfies .
- 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 : parent is , left child is , right child is . For 0-indexed arrays, parent is , left is , right is .
- For elements, heap height with root at level 0 is . Internal nodes are indices to ; leaves are indices to .
- In a max-heap, the maximum is at the root in . The minimum must occur among the leaves; finding it needs worst-case scanning. In a min-heap the opposite holds.
- MAX-HEAPIFY restores the heap property in . BUILD-MAX-HEAP uses bottom-up heapify in . Insert and extract are .
- 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 , is in-place, and is not stable.
- With 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
- Array-to-tree mapping. Treat as the root. For every index , its children are and if those indices are at most heap size. This creates exactly one complete binary tree shape for each .
- Check heap validity. For a max-heap, scan internal nodes to . At each node, verify when the left child exists and when the right child exists. For a min-heap, reverse the inequalities.
- MAX-HEAPIFY(A, i). Assume the subtrees of are already max-heaps. Compare with its left and right children. Let be the largest among them. If , swap with and recursively call MAX-HEAPIFY on .
Otherwise stop. Cost is . - BUILD-MAX-HEAP(A). Set heap size . For down to , call MAX-HEAPIFY(A, i). Starting below the leaves works because each child subtree is already a heap. Total cost is , not .
- 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.
- Extract-maximum. Save . Copy the last element into , reduce heap size by 1, and call MAX-HEAPIFY(A, 1) if the heap is non-empty. Return the saved maximum.
- Increase-key. If a max-heap key at index 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.
Drawing the diagram…
Formulas
- Use 1-indexed arrays ; is the current heap size, and root is at level 0.
- For distinct keys, number of binary max-heaps:
- where and are the sizes of the left and right subtrees of the complete binary tree with nodes, and . The root is fixed as the maximum key.
Worked examples
Example 1: Is the array a max-heap?
Check , .
Internal nodes are .
: children ; and .
: children ; and .
: children ; and .
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: .
Insert 10: .
Insert 25: append , swap with parent : .
Insert 8: append ; parent , no swap.
Insert 20: append , swap with : ; parent , stop.
Final max-heap: .
Example 3: Floyd’s bottom-up build-max-heap.
Start , . Start at .
: value , child ; no swap.
: value , children ; swap with : .
: value , children ; swap with : ; then at index 2, value , children ; swap with : .
Final heap: . Height is ; right child of root is .
Example 4: Count distinct max-heaps for 4 distinct keys.
Take keys , . The complete tree has left subtree size , right subtree size . Root must be . Choose 2 of the remaining 3 keys for the left subtree: . A 2-node max-heap has ; a 1-node heap has . Hence .
Example 5: Match operations with worst-case costs in a max-heap.
FIND-MAX takes because the root is maximum.
EXTRACT-MAX takes because it calls heapify once.
BUILD-MAX-HEAP from an unsorted array takes .
SEARCH for an arbitrary key takes because heap order does not order siblings or subtrees.
Comparison
| Feature | Max-heap | Min-heap |
|---|---|---|
| Parent-child rule | Parent children | Parent children |
| Root | Largest key | Smallest key |
| Fast extraction | Extract-max | Extract-min |
| Finding opposite extreme | Minimum in , among leaves | Maximum in , among leaves |
| Key increase | Bubble upward | May require heapify down |
| Implementation | Insert | Peek extreme | Extract extreme | Search arbitrary key |
|---|---|---|---|---|
| Binary heap | ||||
| Balanced BST | average | average | ||
| Sorted array | ||||
| Unsorted array |
| Point | BUILD-MAX-HEAP | Repeated insertion |
|---|---|---|
| Method | Bottom-up heapify | Append and bubble up |
| Cost | ||
| Use | Convert an existing array into a heap | Insert 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 , children and ; 0-indexed shifts by one.
- Height is ; root is at level 0.
- Leaves are indices ; internal nodes are .
- In a max-heap, max is at root ; min lies among leaves and costs to find.
- Build-heap is ; inserting elements one by one is .
- 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 ; 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 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 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 , , , and : know find-extreme, extract, build, and arbitrary search separately.
- Statement questions often test height , 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 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 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.