Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to insert an element into a max heap list.
DSA Python
def insert_max_heap(heap, element): heap.append(element) i = len(heap) - 1 while i > 0 and heap[(i - 1) // 2] < heap[i]: heap[i], heap[(i - 1) // 2] = heap[(i - 1) // 2], heap[i] i = [1]
Attempts:
3 left
💡 Hint
Common Mistakes
Using i // 2 as parent index which is incorrect for zero-based indexing.
Using i - 1 or i + 1 which are not parent indices.
✗ Incorrect
In a heap represented as a list, the parent index of a node at index i is (i - 1) // 2.
2fill in blank
mediumComplete the code to get the left child index of a node in a heap list.
DSA Python
def left_child(i): return [1]
Attempts:
3 left
💡 Hint
Common Mistakes
Using 2*i which is the formula for left child in one-based indexing.
Using i + 1 which is just the next element.
✗ Incorrect
In a heap list, the left child of node at index i is at 2*i + 1.
3fill in blank
hardFix the error in the code that heapifies a subtree rooted at index i in a max heap.
DSA Python
def max_heapify(heap, n, i): largest = i left = 2 * i + 1 right = 2 * i + 2 if left < n and heap[left] > heap[[1]]: largest = left if right < n and heap[right] > heap[largest]: largest = right if largest != i: heap[i], heap[largest] = heap[largest], heap[i] max_heapify(heap, n, largest)
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing left child with largest which is initially set to i but not updated yet.
Using left or right as index which is incorrect here.
✗ Incorrect
We compare heap[left] with heap[i], the root of the subtree, to find the largest.
4fill in blank
hardFill both blanks to complete the code that builds a max heap from an unordered list.
DSA Python
def build_max_heap(arr): n = len(arr) for i in range([1], -1, -1): [2](arr, n, i)
Attempts:
3 left
💡 Hint
Common Mistakes
Starting from n - 1 which is a leaf node and does not need heapify.
Using a wrong function name like heapify instead of max_heapify.
✗ Incorrect
We start heapifying from the last parent node at n//2 - 1 down to 0 using max_heapify function.
5fill in blank
hardFill all three blanks to complete the code that extracts the maximum element from a max heap.
DSA Python
def extract_max(heap): if len(heap) == 0: return None max_element = heap[[1]] heap[[2]] = heap.pop() max_heapify(heap, len(heap), [3]) return max_element
Attempts:
3 left
💡 Hint
Common Mistakes
Using -1 or len(heap)-1 as index for max element which is incorrect.
Not heapifying from root after replacement.
✗ Incorrect
The max element is at index 0. We replace root with last element at index 0 and heapify from root.
