Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the min heap size.
DSA C
int minHeapSize = [1];Attempts:
3 left
💡 Hint
Common Mistakes
Initializing heap size to 0 or n instead of k.
Using 1 which is not related to k.
✗ Incorrect
The min heap size should be initialized to k because we want to find the kth smallest element.
2fill in blank
mediumComplete the code to insert an element into the min heap.
DSA C
void insertMinHeap(int heap[], int* size, int value) {
heap[*size] = value;
int i = *size;
(*size)++;
while (i != 0 && heap[(i - 1) / 2] > heap[i]) {
int temp = heap[i];
heap[i] = heap[(i - 1) / 2];
heap[(i - 1) / 2] = [1];
i = (i - 1) / 2;
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong variable for swapping.
Not swapping correctly causing infinite loop.
✗ Incorrect
We swap the current element with its parent using the temporary variable 'temp'.
3fill in blank
hardFix the error in the code to heapify the min heap.
DSA C
void minHeapify(int heap[], int size, int i) {
int smallest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < size && heap[left] < heap[[1]])
smallest = left;
if (right < size && heap[right] < heap[smallest])
smallest = right;
if (smallest != i) {
int temp = heap[i];
heap[i] = heap[smallest];
heap[smallest] = temp;
minHeapify(heap, size, smallest);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Comparing with wrong index causing incorrect heap property.
Using smallest instead of i in first comparison.
✗ Incorrect
We compare heap[left] with heap[i] to find the smallest element.
4fill in blank
hardFill both blanks to extract the minimum element from the min heap.
DSA C
int extractMin(int heap[], int* size) {
if (*size <= 0)
return -1;
int root = heap[0];
heap[0] = heap[[1]];
(*size)--;
minHeapify(heap, *size, [2]);
return root;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong index for last element.
Heapifying from wrong index.
✗ Incorrect
We replace root with last element at index (*size) - 1 and heapify from root index 0.
5fill in blank
hardFill all three blanks to find the kth smallest element using the min heap.
DSA C
int kthSmallest(int arr[], int n, int k) {
int heap[[1]];
int size = 0;
for (int i = 0; i < n; i++) {
insertMinHeap(heap, &size, arr[i]);
}
int result = -1;
for (int i = 0; i < [2]; i++) {
result = extractMin(heap, &size);
}
return [3];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong heap size.
Extracting min wrong number of times.
Returning wrong variable.
✗ Incorrect
Heap size is n to hold all elements, extract min k times, then return the last extracted value.
