Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to count the frequency of each element in the list.
DSA Python
from collections import Counter def top_k_frequent(nums, k): freq = Counter(nums) return freq[1]
Attempts:
3 left
💡 Hint
Common Mistakes
Using .keys() returns only elements without counts.
Using .values() returns only counts without elements.
Using .most_common() returns a list, not a dict view.
✗ Incorrect
We use freq.items() to get pairs of (element, frequency) for processing.
2fill in blank
mediumComplete the code to push frequency and element pairs into the heap.
DSA Python
import heapq heap = [] for num, count in freq.items(): heapq.heappush(heap, ([1], num))
Attempts:
3 left
💡 Hint
Common Mistakes
Pushing count directly creates a min heap, not max heap.
Pushing num instead of count does not sort by frequency.
✗ Incorrect
We push (-count, num) to create a max heap by frequency using Python's min heap.
3fill in blank
hardFix the error in extracting the top k frequent elements from the heap.
DSA Python
result = [] for _ in range(k): freq, num = heapq.heappop(heap) result.append([1]) return result
Attempts:
3 left
💡 Hint
Common Mistakes
Appending freq adds negative counts, not elements.
Appending -freq would give positive counts, not elements.
✗ Incorrect
We append num because it is the element, freq is the negative count.
4fill in blank
hardFill both blanks to complete the function that returns the top k frequent elements using a heap.
DSA Python
def top_k_frequent(nums, k): freq = Counter(nums) heap = [] for num, count in freq.items(): heapq.heappush(heap, ([1], num)) result = [] for _ in range(k): freq, num = heapq.heappop(heap) result.append([2]) return result
Attempts:
3 left
💡 Hint
Common Mistakes
Using count instead of -count breaks max heap logic.
Appending freq instead of num adds counts, not elements.
✗ Incorrect
Push negative count for max heap and append num to result.
5fill in blank
hardFill all three blanks to create a complete function that returns the top k frequent elements using a heap.
DSA Python
import heapq from collections import Counter def top_k_frequent(nums, k): freq = Counter(nums) heap = [] for num, count in freq.items(): heapq.heappush(heap, ([1], [2])) result = [] for _ in range(k): freq, num = heapq.heappop(heap) result.append([3]) return result
Attempts:
3 left
💡 Hint
Common Mistakes
Using count instead of -count breaks max heap logic.
Appending freq instead of num adds counts, not elements.
✗ Incorrect
Push (-count, num) to heap, pop and append num to result.
