Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a max heap using PriorityQueue in Java.
DSA Java
PriorityQueue<Integer> maxHeap = new PriorityQueue<>([1]);Attempts:
3 left
💡 Hint
Common Mistakes
Using natural order comparator creates a min heap instead of max heap.
Passing null does not create a max heap.
✗ Incorrect
Using Collections.reverseOrder() creates a max heap by reversing the natural order.
2fill in blank
mediumComplete the code to add elements from the array to the max heap.
DSA Java
for (int num : nums) { maxHeap.[1](num); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using poll() removes elements instead of adding.
Using peek() only views the top element.
✗ Incorrect
The offer() method adds elements to the PriorityQueue (max heap).
3fill in blank
hardFix the error in the code to extract the kth largest element from the max heap.
DSA Java
int kthLargest = 0; for (int i = 0; i < k; i++) { kthLargest = maxHeap.[1](); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using peek() causes an infinite loop or wrong result.
Using offer() or remove() incorrectly.
✗ Incorrect
poll() removes and returns the top element, which is needed to get the kth largest.
4fill in blank
hardFill both blanks to complete the method that returns the kth largest element using a max heap.
DSA Java
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> maxHeap = new PriorityQueue[1];
for (int num : nums) {
maxHeap[2](num);
}
for (int i = 0; i < k - 1; i++) {
maxHeap.poll();
}
return maxHeap.peek();
}Attempts:
3 left
💡 Hint
Common Mistakes
Not using reverseOrder() causes min heap behavior.
Using add() or offer() both work, but offer() is preferred.
✗ Incorrect
Use PriorityQueue<>(Collections.reverseOrder()) to create max heap and offer() to add elements.
5fill in blank
hardFill all three blanks to complete the method that returns the kth largest element by polling k times from the max heap.
DSA Java
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> maxHeap = new PriorityQueue[1];
for (int num : nums) {
maxHeap[2](num);
}
int result = 0;
for (int i = 0; i < k; i++) {
result = maxHeap.[3]();
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using peek() instead of poll() in the loop.
Not using reverseOrder() causes wrong heap behavior.
✗ Incorrect
Create max heap with reverseOrder(), add elements with offer(), and poll() k times to get kth largest.
