Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a min heap from the input array.
DSA C#
var minHeap = new PriorityQueue<int, int>(); foreach (var num in nums) { minHeap.[1](num, num); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using Add or Insert which are not methods of PriorityQueue.
Using Push which is not a C# PriorityQueue method.
✗ Incorrect
The PriorityQueue in C# uses Enqueue to add elements with their priority. Here, the element and its priority are the same.
2fill in blank
mediumComplete the code to remove the smallest element from the min heap.
DSA C#
int smallest = minHeap.[1]();Attempts:
3 left
💡 Hint
Common Mistakes
Using Pop which is not a method in C# PriorityQueue.
Using ExtractMin which is not a C# PriorityQueue method.
✗ Incorrect
PriorityQueue in C# uses Dequeue to remove and return the element with the smallest priority.
3fill in blank
hardFix the error in the loop condition to extract the kth smallest element.
DSA C#
for (int i = 1; i < [1]; i++) { minHeap.Dequeue(); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using k causes the loop to remove one too many elements.
Using nums.Length is unrelated to k.
✗ Incorrect
We remove k-1 smallest elements first, so the next element dequeued is the kth smallest.
4fill in blank
hardFill both blanks to complete the method that returns the kth smallest element using a min heap.
DSA C#
public int KthSmallest(int[] nums, int k)
{
var minHeap = new PriorityQueue<int, int>();
foreach (var num in nums)
minHeap.[1](num, num);
for (int i = 1; i < [2]; i++)
minHeap.Dequeue();
return minHeap.Dequeue();
}Attempts:
3 left
💡 Hint
Common Mistakes
Using Add instead of Enqueue.
Using k instead of k - 1 in the loop.
✗ Incorrect
Use Enqueue to add elements to the min heap and loop k-1 times to remove the smallest elements before returning the kth smallest.
5fill in blank
hardFill all three blanks to complete the method that returns the kth smallest element using a min heap with proper variable names.
DSA C#
public int KthSmallestElement(int[] [1], int [2]) { var [3] = new PriorityQueue<int, int>(); foreach (var num in nums) minHeap.Enqueue(num, num); for (int i = 1; i < k; i++) minHeap.Dequeue(); return minHeap.Dequeue(); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using inconsistent variable names causing errors.
Using numbers instead of nums for the array parameter.
✗ Incorrect
The method parameters are nums and k, and the min heap variable is named minHeap to match usage in the method.
