Challenge - 5 Problems
Heap Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output array after building a max heap?
Given the array [4, 10, 3, 5, 1], what is the array representation after applying the build max heap process?
DSA Java
int[] arr = {4, 10, 3, 5, 1}; // After build max heap, what is arr?
Attempts:
2 left
💡 Hint
Remember that build max heap rearranges the array so that each parent is greater than its children.
✗ Incorrect
The build max heap process starts from the last non-leaf node and heapifies down. After heapifying, the array becomes [10, 5, 3, 4, 1].
❓ Predict Output
intermediateWhat is the output array after building a min heap?
Given the array [7, 2, 6, 3, 9], what is the array representation after applying the build min heap process?
DSA Java
int[] arr = {7, 2, 6, 3, 9}; // After build min heap, what is arr?
Attempts:
2 left
💡 Hint
Build min heap ensures each parent is smaller than its children.
✗ Incorrect
Heapify starts from last non-leaf node and moves upward, swapping to maintain min heap property. The final array is [2, 3, 6, 7, 9].
🔧 Debug
advancedDoes this heapify method cause an error when building a max heap?
What error will this Java heapify method cause when building a max heap?
DSA Java
void heapify(int[] arr, int n, int i) { int largest = i; int left = 2 * i + 1; int right = 2 * i + 2; if (left < n && arr[left] > arr[largest]) largest = left; if (right < n && arr[right] > arr[largest]) largest = right; if (largest != i) { int temp = arr[i]; arr[i] = arr[largest]; arr[largest] = temp; heapify(arr, n, largest); } } void buildHeap(int[] arr) { int n = arr.length; for (int i = n / 2 - 1; i >= 0; i--) { heapify(arr, n, i); } }
Attempts:
2 left
💡 Hint
Does heapify access array elements without boundary checks? Examine the if conditions.
✗ Incorrect
No error, the code runs correctly. The loop starts at n/2 - 1, which is the last non-leaf node, and heapify checks left < n and right < n before accessing arr[left] or arr[right], preventing out-of-bounds exceptions.
🧠 Conceptual
advancedWhy does build heap start heapifying from the middle of the array?
Why does the build heap algorithm start heapifying from the index n/2 - 1 instead of from index 0?
Attempts:
2 left
💡 Hint
Think about which nodes have children in a binary heap array.
✗ Incorrect
Nodes from n/2 to n-1 are leaf nodes with no children, so they already satisfy heap property. Heapifying them is unnecessary.
🚀 Application
expertWhat is the height of the heap built from an array of size 31?
If you build a complete binary heap from an array of size 31, what is the height of the heap?
Attempts:
2 left
💡 Hint
Height of a complete binary tree with n nodes is floor(log2(n)).
✗ Incorrect
Height is the number of edges on the longest path from root to leaf. For 31 nodes (2^5 - 1), height = floor(log2(31)) = 4.
