Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a frequency map for the elements in the array.
DSA Java
Map<Integer, Integer> freqMap = new HashMap<>(); for (int num : nums) { freqMap.put(num, freqMap.getOrDefault(num, [1]) + 1); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 as default causes counts to be off by one.
Using the element itself as default causes errors.
✗ Incorrect
We use 0 as the default frequency for elements not yet in the map, then add 1.
2fill in blank
mediumComplete the code to create a priority queue (min-heap) that sorts elements by frequency.
DSA Java
PriorityQueue<Integer> heap = new PriorityQueue<>((a, b) -> freqMap.get([1]) - freqMap.get(b));Attempts:
3 left
💡 Hint
Common Mistakes
Swapping 'a' and 'b' changes min-heap to max-heap.
Using freqMap instead of elements causes errors.
✗ Incorrect
We compare frequencies of elements 'a' and 'b' to build a min-heap based on frequency.
3fill in blank
hardFix the error in the code that adds elements to the heap and maintains its size at k.
DSA Java
for (int num : freqMap.keySet()) { heap.offer(num); if (heap.size() > [1]) { heap.poll(); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using nums.length causes heap to grow too large.
Using 0 causes no elements to be removed.
✗ Incorrect
We keep the heap size at most k to track top k frequent elements.
4fill in blank
hardFill both blanks to extract elements from the heap into the result list in correct order.
DSA Java
List<Integer> result = new ArrayList<>(); while (!heap.isEmpty()) { result.add([1]); } Collections.[2](result);
Attempts:
3 left
💡 Hint
Common Mistakes
Using peek() does not remove elements, causing infinite loop.
Sorting instead of reversing changes order incorrectly.
✗ Incorrect
We poll elements from the heap and then reverse the list to get descending frequency order.
5fill in blank
hardFill all three blanks to complete the method that returns the top k frequent elements.
DSA Java
public List<Integer> topKFrequent(int[] nums, int k) {
Map<Integer, Integer> freqMap = new HashMap<>();
for (int num : nums) {
freqMap.put(num, freqMap.getOrDefault(num, [1]) + 1);
}
PriorityQueue<Integer> heap = new PriorityQueue<>((a, b) -> freqMap.get(a) - freqMap.get(b));
for (int num : freqMap.keySet()) {
heap.offer(num);
if (heap.size() > [2]) {
heap.poll();
}
}
List<Integer> result = new ArrayList<>();
while (!heap.isEmpty()) {
result.add(heap.poll());
}
Collections.[3](result);
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 as default frequency causes off-by-one errors.
Not limiting heap size causes incorrect results.
Sorting instead of reversing changes order.
✗ Incorrect
Default frequency is 0, keep heap size at k, then reverse the result list for correct order.
