heapq.heapify converts list into a min-heap, smallest element at root (index 0).
Step 2: Apply heapify on given list
After heapify, the list becomes [1, 2, 4, 5, 3, 6], which satisfies min-heap property.
Final Answer:
[1, 2, 4, 5, 3, 6] -> Option B
Quick Check:
heapify(min-heap) = [1, 2, 4, 5, 3, 6] [OK]
Hint: heapq.heapify creates min-heap, smallest first [OK]
Common Mistakes:
Expecting sorted list instead of heap order
Confusing max-heap with min-heap output
Assuming original list order remains
4. The following code attempts to build a heap from an array but does not produce the correct heap. What is the error?
def build_heap(arr):
n = len(arr)
for i in range(n):
heapify(arr, i, n)
def heapify(arr, i, n):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[left] > arr[largest]:
largest = left
if right < n and arr[right] > arr[largest]:
largest = right
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
heapify(arr, largest, n)
arr = [4, 10, 3, 5, 1]
build_heap(arr)
print(arr)
medium
A. The loop should run from n//2 - 1 down to 0, not from 0 to n
B. The heapify function should use min-heap logic instead of max-heap
C. The swap inside heapify is missing
D. The array length n is calculated incorrectly
Solution
Step 1: Analyze build_heap loop range
Heap building requires heapify calls from last non-leaf node down to root, i.e., from n//2 - 1 down to 0.
Step 2: Identify incorrect loop direction
The code loops from 0 to n, which is incorrect and misses proper heapify order.
Final Answer:
The loop should run from n//2 - 1 down to 0, not from 0 to n -> Option A
Quick Check:
Build heap loop must go bottom-up [OK]
Hint: Build heap bottom-up from last parent to root [OK]
Common Mistakes:
Looping top-down instead of bottom-up
Confusing min-heap and max-heap logic
Forgetting to swap elements in heapify
5. Given an array arr = [9, 4, 7, 1, -2, 6, 5], you want to build a max-heap using the heapify method. Which sequence of indices should you call heapify on to build the heap correctly?
hard
A. From index 0 to len(arr)-1 in ascending order
B. Only on index 0
C. From index len(arr)-1 down to 0 in descending order
D. From index len(arr)//2 - 1 down to 0 in descending order
Solution
Step 1: Identify last non-leaf node
For array length 7, last non-leaf node is at index 7//2 - 1 = 2.
Step 2: Correct heapify call order
Heapify must be called from index 2 down to 0 to ensure all subtrees satisfy max-heap property.
Final Answer:
From index len(arr)//2 - 1 down to 0 in descending order -> Option D
Quick Check:
Heapify bottom-up from last parent to root [OK]
Hint: Start heapify from last parent index down to root [OK]
Common Mistakes:
Calling heapify in ascending order
Calling heapify only on root
Calling heapify on all indices including leaves
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.