Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a min heap using PriorityQueue.
DSA Java
PriorityQueue<Integer> minHeap = new PriorityQueue[1]();Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of angle brackets for the type.
Using curly braces or square brackets which are invalid here.
✗ Incorrect
The PriorityQueue constructor requires the type parameter in angle brackets to create a min heap of integers.
2fill in blank
mediumComplete the code to add elements from the array to the min heap.
DSA Java
for (int num : nums) { minHeap.[1](num); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using poll() which removes elements instead of adding.
Using peek() which only views the smallest element.
✗ Incorrect
The offer() method adds an element to the PriorityQueue (min heap).
3fill in blank
hardFix the error in the code to extract the kth smallest element by removing elements from the min heap.
DSA Java
int kthSmallest = 0; for (int i = 0; i < k; i++) { kthSmallest = minHeap.[1](); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using peek() which does not remove elements.
Using offer() which adds elements instead of removing.
✗ Incorrect
poll() removes and returns the smallest element from the min heap, which is needed to find the kth smallest.
4fill in blank
hardFill both blanks to complete the method that returns the kth smallest element using a min heap.
DSA Java
public int findKthSmallest(int[] nums, int k) {
PriorityQueue<Integer> minHeap = new PriorityQueue[1]();
for (int num : nums) {
minHeap.[2](num);
}
for (int i = 0; i < k - 1; i++) {
minHeap.poll();
}
return minHeap.peek();
}Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the type parameter in PriorityQueue.
Using add() instead of offer(), which also works but offer() is preferred here.
✗ Incorrect
The PriorityQueue needs the type parameter and elements are added using offer() method.
5fill in blank
hardFill all three blanks to complete the method that returns the kth smallest element by removing elements from the min heap.
DSA Java
public int findKthSmallest(int[] nums, int k) {
PriorityQueue<Integer> minHeap = new PriorityQueue[1]();
for (int num : nums) {
minHeap.[2](num);
}
int kthSmallest = 0;
for (int i = 0; i < k; i++) {
kthSmallest = minHeap.[3]();
}
return kthSmallest;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using peek() instead of poll() to remove elements.
Omitting the type parameter in PriorityQueue.
✗ Incorrect
The PriorityQueue needs the type parameter , elements are added with offer(), and poll() removes the smallest element to find the kth smallest.
