Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a dictionary to count frequencies.
DSA C#
var frequencyMap = new Dictionary<int, [1]>();Attempts:
3 left
💡 Hint
Common Mistakes
Using string or bool as the value type instead of int.
✗ Incorrect
The dictionary maps integers to their frequency counts, which are integers.
2fill in blank
mediumComplete the code to add or update frequency count in the dictionary.
DSA C#
if (frequencyMap.ContainsKey(num)) { frequencyMap[num] [1] 1; } else { frequencyMap[num] = 1; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using -= or *= which would decrease or multiply the count incorrectly.
✗ Incorrect
We add 1 to the existing frequency count when the number is already in the dictionary.
3fill in blank
hardFix the error in the code to create a min-heap using PriorityQueue.
DSA C#
var minHeap = new PriorityQueue<int, int>(); foreach (var entry in frequencyMap) { minHeap.Enqueue(entry.Key, [1]); if (minHeap.Count > k) { minHeap.Dequeue(); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using entry.Key as priority which is the element, not frequency.
✗ Incorrect
The priority for the heap should be the frequency (entry.Value) to keep the least frequent element on top.
4fill in blank
hardFill both blanks to extract elements from the heap into a list in correct order.
DSA C#
var result = new List<int>(); while (minHeap.Count > 0) { result.[1](minHeap.[2]()); } result.Reverse();
Attempts:
3 left
💡 Hint
Common Mistakes
Using Peek instead of Dequeue which does not remove the element.
Using Remove which is not a method of PriorityQueue.
✗ Incorrect
We remove elements from the heap using Dequeue and add them to the result list using Add.
5fill in blank
hardFill all three blanks to complete the method returning top k frequent elements.
DSA C#
public IList<int> TopKFrequent(int[] nums, int k) {
var frequencyMap = new Dictionary<int, int>();
foreach (var num in nums) {
if (frequencyMap.ContainsKey(num)) {
frequencyMap[num] [1] 1;
} else {
frequencyMap[num] = 1;
}
}
var minHeap = new PriorityQueue<int, int>();
foreach (var entry in frequencyMap) {
minHeap.Enqueue(entry.Key, entry.Value);
if (minHeap.Count > k) {
minHeap.[2]();
}
}
var result = new List<int>();
while (minHeap.Count > 0) {
result.[3](minHeap.Dequeue());
}
result.Reverse();
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using Remove instead of Dequeue for heap removal.
Using Remove instead of Add for list insertion.
✗ Incorrect
We increment frequency with +=, remove smallest frequency with Dequeue, and add elements to result with Add.
