0
0
DSA Typescriptprogramming~10 mins

Top K Frequent Elements Using Heap in DSA Typescript - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to count the frequency of each number in the array.

DSA Typescript
const frequencyMap = new Map<number, number>();
for (const num of nums) {
  frequencyMap.set(num, (frequencyMap.get(num) || 0) [1] 1);
}
Drag options to blanks, or click blank then click option'
A-
B+
C*
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-' instead of '+' will decrease the count.
Using '*' or '/' will not correctly count frequency.
2fill in blank
medium

Complete the code to push elements into the heap with their frequency as priority.

DSA Typescript
for (const [num, freq] of frequencyMap.entries()) {
  heap.push({ value: num, priority: [1] });
}
Drag options to blanks, or click blank then click option'
Afreq
Bnum
Cfreq + 1
Dfreq - 1
Attempts:
3 left
💡 Hint
Common Mistakes
Multiplying or dividing frequency changes the priority incorrectly.
Subtracting 1 may cause wrong priority.
3fill in blank
hard

Fix the error in the code to maintain the heap size at most k by removing the smallest frequency element.

DSA Typescript
if (heap.size() > k) {
  heap.[1]();
}
Drag options to blanks, or click blank then click option'
Ainsert
Bpush
Cpeek
Dpop
Attempts:
3 left
💡 Hint
Common Mistakes
Using push or insert adds elements instead of removing.
peek only returns the top without removing.
4fill in blank
hard

Fill both blanks to extract the top k frequent elements from the heap into the result array.

DSA Typescript
const result: number[] = [];
while (heap.size() > 0) {
  const top = heap.[1]();
  result.[2](top.value);
}
Drag options to blanks, or click blank then click option'
Apop
Bpush
Cpeek
Dshift
Attempts:
3 left
💡 Hint
Common Mistakes
Using peek does not remove elements from the heap.
Using shift is for arrays, not heaps.
5fill in blank
hard

Fill all three blanks to return the result array reversed so the most frequent elements come first.

DSA Typescript
return result.[1]().[2]((a, b) => b [3] a);
Drag options to blanks, or click blank then click option'
Areverse
Bsort
C-
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' in the sort comparison will not sort correctly.
Not reversing will give least frequent first.