Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a min heap from the given array.
DSA Typescript
const minHeap = new MinHeap(); for (const num of nums) { minHeap.[1](num); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'push' or 'append' which are array methods, not heap methods.
✗ Incorrect
The method to add elements to a min heap is usually called 'insert'.
2fill in blank
mediumComplete the code to extract the smallest element from the min heap.
DSA Typescript
const smallest = minHeap.[1](); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'pop' which removes the last element in an array, not the smallest in a heap.
✗ Incorrect
The method to remove and return the smallest element in a min heap is 'extractMin'.
3fill in blank
hardFix the error in the loop that extracts k smallest elements from the min heap.
DSA Typescript
for (let i = 0; i < k; i++) { result.push(minHeap.[1]()); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'peek' which does not remove elements, causing an infinite loop or repeated values.
✗ Incorrect
To get the k smallest elements, we must extract the minimum each time using 'extractMin'.
4fill in blank
hardFill both blanks to complete the function that returns the kth smallest element using a min heap.
DSA Typescript
function kthSmallest(nums: number[], k: number): number {
const minHeap = new MinHeap();
for (const num of nums) {
minHeap.[1](num);
}
let result = 0;
for (let i = 0; i < k; i++) {
result = minHeap.[2]();
}
return result;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'pop' instead of 'extractMin' which does not guarantee smallest element removal.
✗ Incorrect
We insert all numbers into the min heap, then extract the minimum k times to get the kth smallest.
5fill in blank
hardFill both blanks to complete the function that returns the kth smallest element using a min heap with early stopping.
DSA Typescript
function kthSmallest(nums: number[], k: number): number {
const minHeap = new MinHeap();
for (const num of nums) {
minHeap.[1](num);
}
let result = 0;
for (let i = 0; i < k; i++) {
result = minHeap.[2]();
}
return result;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'pop' which removes the last element, not the smallest.
✗ Incorrect
Insert all numbers, then extract the minimum k times to get the kth smallest element.