Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a map that counts frequencies of elements.
DSA C++
std::unordered_map<int, int> freqMap; for (int num : nums) { freqMap[num] [1]; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '=' instead of '++' resets the count instead of increasing it.
Using '--' decreases the count which is incorrect here.
✗ Incorrect
We use ++ to increase the count of each number in the frequency map.
2fill in blank
mediumComplete the code to push pairs of (frequency, number) into the priority queue.
DSA C++
std::priority_queue<std::pair<int, int>> maxHeap; for (auto& p : freqMap) { maxHeap.[1](std::make_pair(p.second, p.first)); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop instead of push removes elements instead of adding.
Using top or empty does not add elements.
✗ Incorrect
We use push to add elements into the priority queue.
3fill in blank
hardFix the error in the loop that extracts top k elements from the heap.
DSA C++
std::vector<int> result; for (int i = 0; i < k; i++) { result.push_back(maxHeap.[1]().second); maxHeap.pop(); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() to access element causes error because pop() returns void.
Using push() or empty() are incorrect for accessing elements.
✗ Incorrect
We use top() to access the element at the top of the heap before popping it.
4fill in blank
hardFill both blanks to create a min-heap that stores pairs of (frequency, number).
DSA C++
auto cmp = [](const std::pair<int, int>& a, const std::pair<int, int>& b) {
return a.[1] > b.[2];
};
std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, decltype(cmp)> minHeap(cmp); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing 'second' compares the number, not frequency.
Using size or empty are invalid for pair elements.
✗ Incorrect
We compare the 'first' element of pairs which is frequency to create a min-heap.
5fill in blank
hardFill all three blanks to insert elements into the min-heap and maintain size k.
DSA C++
for (auto& p : freqMap) { minHeap.[1](p); if (minHeap.[2]() > k) { minHeap.[3](); } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using top() instead of size() to check heap size.
Using pop() before checking size causes errors.
✗ Incorrect
We push elements, check size, and pop smallest to keep top k frequent elements.