0
0
DSA Javascriptprogramming~10 mins

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

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

Complete the code to create a frequency map of elements in the array.

DSA Javascript
const freqMap = new Map();
for (const num of nums) {
  freqMap.set(num, (freqMap.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 subtraction or multiplication instead of addition.
2fill in blank
medium

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

DSA Javascript
for (const [num, freq] of freqMap.entries()) {
  heap.push({ val: num, freq: freq });
  heap.sort((a, b) => b.freq [1] a.freq);
}
Drag options to blanks, or click blank then click option'
A*
B+
C/
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition or multiplication in the sort comparator.
3fill in blank
hard

Fix the error in the code that extracts the top k frequent elements from the heap.

DSA Javascript
const result = [];
for (let i = 0; i < k; i++) {
  result.push(heap.[1]().val);
}
Drag options to blanks, or click blank then click option'
Ashift
Bpop
Cpush
Dunshift
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() which removes the last element instead of the first.
4fill in blank
hard

Fill both blanks to complete the function that returns the top k frequent elements.

DSA Javascript
function topKFrequent(nums, k) {
  const freqMap = new Map();
  for (const num of nums) {
    freqMap.set(num, (freqMap.get(num) || 0) [1] 1);
  }
  const heap = [];
  for (const [num, freq] of freqMap.entries()) {
    heap.push({ val: num, freq: freq });
    heap.sort((a, b) => b.freq [2] a.freq);
  }
  const result = [];
  for (let i = 0; i < k; i++) {
    result.push(heap.shift().val);
  }
  return result;
}
Drag options to blanks, or click blank then click option'
A+
B-
C*
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up operators for counting and sorting.
5fill in blank
hard

Fill all three blanks to complete the function using a heap to find top k frequent elements.

DSA Javascript
function topKFrequent(nums, k) {
  const freqMap = new Map();
  for (const num of nums) {
    freqMap.set(num, (freqMap.get(num) || 0) [1] 1);
  }
  const heap = [];
  for (const [num, freq] of freqMap.entries()) {
    heap.push({ val: num, freq: freq });
    heap.sort((a, b) => b.freq [2] a.freq);
  }
  const result = [];
  for (let i = 0; i < k; i++) {
    result.push(heap.[3]().val);
  }
  return result;
}
Drag options to blanks, or click blank then click option'
A+
B-
Cshift
Dpop
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() instead of shift() to remove elements.