Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to swap two integers using pointers.
DSA C
void swap(int *a, int *b) {
int temp = *a;
*a = [1];
*b = temp;
}Attempts:
3 left
💡 Hint
Common Mistakes
Assigning *a = temp instead of *a = *b
Using a or b instead of *a or *b
✗ Incorrect
To swap values, assign *a = *b and *b = temp. Here, *a = *b is needed.
2fill in blank
mediumComplete the code to heapify the subtree rooted at index i in max heap.
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] [1] arr[largest])
largest = left;
if (right < n && arr[right] > arr[largest])
largest = right;
if (largest != i) {
swap(&arr[i], &arr[largest]);
maxHeapify(arr, n, largest);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' causing min heap behavior
Using '==' which doesn't update largest
✗ Incorrect
To maintain max heap, if left child is greater than current largest, update largest to left.
3fill in blank
hardFix the error in the code to build a max heap from an array.
DSA C
void buildMaxHeap(int arr[], int n) {
for (int i = n / 2 - 1; i >= 0; i--) {
[1](arr, n, i);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Calling buildMaxHeap recursively causing infinite loop
Calling swap instead of maxHeapify
✗ Incorrect
To build max heap, call maxHeapify on each non-leaf node.
4fill in blank
hardFill both blanks to extract the kth largest element using max heap.
DSA C
int extractMax(int arr[], int *n) {
if (*n <= 0)
return -1;
int max = arr[0];
arr[0] = arr[[1]];
(*n)--;
maxHeapify(arr, *n, [2]);
return max;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using *n instead of *n - 1 causing out-of-bounds access
Heapifying from wrong index
✗ Incorrect
Replace root with last element at index n-1, then heapify from root index 0.
5fill in blank
hardFill all three blanks to find the kth largest element using max heap.
DSA C
int kthLargest(int arr[], int n, int k) {
buildMaxHeap(arr, n);
int size = n;
int result = -1;
for (int i = 0; i < [1]; i++) {
result = extractMax(arr, &[2]);
}
return [3];
}Attempts:
3 left
💡 Hint
Common Mistakes
Looping n times instead of k
Passing n instead of size to extractMax
Returning size or n instead of result
✗ Incorrect
Loop k times, extract max from heap reducing size, return last extracted value.
