Challenge - 5 Problems
Max Heap Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of this code snippet?
Given the array and k value, what is the kth largest element printed by this code?
DSA C
int arr[] = {3, 2, 1, 5, 6, 4}; int k = 2; // Max heap logic to find kth largest // Output the kth largest element
Attempts:
2 left
💡 Hint
Remember, the 2nd largest element is the one just smaller than the largest.
✗ Incorrect
The largest element is 6, the 2nd largest is 5.
🧠 Conceptual
intermediateWhich property does a max heap maintain?
Select the correct property that a max heap always maintains.
Attempts:
2 left
💡 Hint
Think about the root being the largest element.
✗ Incorrect
In a max heap, every parent node is larger than or equal to its children.
🔧 Debug
advancedWhat error does this code produce?
This code tries to build a max heap but has a bug. What error occurs when running it?
DSA C
void maxHeapify(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; maxHeapify(arr, n, largest); } } int main() { int arr[] = {1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17}; int n = sizeof(arr)/sizeof(arr[0]); for (int i = n / 2 - 1; i >= 0; i--) { maxHeapify(arr, n, i); } return 0; }
Attempts:
2 left
💡 Hint
Check the loop bounds carefully.
✗ Incorrect
The loop runs from i = n/2 - 1 down to 0 inclusive, which is correct for heapify.
No syntax or runtime errors occur.
❓ Predict Output
advancedWhat is the heap array after building max heap?
Given the array, what is the state of the array after building the max heap?
DSA C
int arr[] = {4, 10, 3, 5, 1}; int n = 5; for (int i = n / 2 - 1; i >= 0; i--) { maxHeapify(arr, n, i); } // Print arr after heapify
Attempts:
2 left
💡 Hint
Max heap root is the largest element.
✗ Incorrect
After heapify, the array represents a max heap with root 10, children 5 and 3, etc.
🚀 Application
expertHow many elements remain in the heap after extracting kth largest?
If you use a max heap to find the 3rd largest element by extracting the max 3 times from an array of 7 elements, how many elements remain in the heap?
Attempts:
2 left
💡 Hint
Each extraction removes one element from the heap.
✗ Incorrect
Extracting max 3 times removes 3 elements from 7, leaving 4.
