What this topic covers
16 subtopics- Heap operations7
- Library heaps7
- Array layout5
- Heap basics4
- Top-k4
- Building a heap3
- Heap variants3
- Applications2
- Greedy with heaps2
- Heap sort2
- Choosing a structure1
- Generating sequences1
Show all 16 subtopics
- Merging1
- Scheduling1
- Simulation1
- Two heaps1
- Beginner 15
- Intermediate 15
- Advanced 15
About this topic
A binary heap is a complete binary tree stored in an array: the children of index i are 2i + 1 and 2i + 2, its parent is (i − 1) // 2. In a max-heap every parent is ≥ its children, so the maximum is at index 0. Insert by appending and sifting up; remove the top by moving the last element to the root and sifting down – both O(log n). Heaps power priority queues, top-k problems, Dijkstra and heap sort. Each heap below is drawn as a tree with its array underneath.
Free preview
Sample questions
Try each one first, then open the answer for the explanation and why the other options are wrong.
Which array is a valid max-heap?
- 90
- 15
- 10
- 7
- 16
- 2
- 90
- 10
- 15
- 12
- 7
- 20
- 90
- 15
- 10
- 7
- 12
- 2
- 10
- 15
- 90
- 7
- 12
- 2
Show answer and explanation
Explanation
Check each parent against its children: 90 ≥ 15, 10; 15 ≥ 7, 12; 10 ≥ 2. In B, 16 is a child of 15. In C the root is not the largest. In D, 20 is a child of 15.
Why the other options are wrong
- A16 is greater than its parent 15.
- B20 is greater than its parent 15.
- DThe root must be the maximum.
Bottom-up heapify turns this array into a min-heap (sifting down from the last parent to the root). What is the result?
- 03
- 19
- 22
- 31
- 44
- 55
- 1
- 2
- 3
- 4
- 5
- 9
- 2
- 1
- 3
- 9
- 4
- 5
- 1
- 3
- 2
- 4
- 9
- 5
- 1
- 3
- 2
- 9
- 4
- 5
Show answer and explanation
Explanation
Index 2 (2) is already smaller than 5. Index 1 (9) swaps with its smaller child 1. Index 0 (3) swaps with its smaller child 1 → [1, 3, 2, 9, 4, 5]. Heapify does not sort.
Why the other options are wrong
- AThat is sorted, not just a heap.
- BThe root must be the minimum.
- C9 stays at index 3 after its swap.
Bottom-up build of a max-heap from the sorted array [1, 2, 3, 4, 5, 6, 7]. How many swaps are made in total?
The answer is a number – work it out, then open the solution.
Show answer and explanation
Explanation
Index 2 (3) swaps with 7; index 1 (2) swaps with 5; index 0 (1) swaps with 7, then with 6 below it. 1 + 1 + 2 = 4 swaps, giving [7, 5, 6, 4, 2, 1, 3].