0
0
DSA C++programming~10 mins

Top K Frequent Elements Using Heap in DSA C++ - Interactive Practice

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

Complete 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'
A--
B++
C=
D*=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '=' instead of '++' resets the count instead of increasing it.
Using '--' decreases the count which is incorrect here.
2fill in blank
medium

Complete 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'
Apush
Bpop
Ctop
Dempty
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop instead of push removes elements instead of adding.
Using top or empty does not add elements.
3fill in blank
hard

Fix 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'
Atop
Bpop
Cpush
Dempty
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.
4fill in blank
hard

Fill 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'
Afirst
Bsecond
Csize
Dempty
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing 'second' compares the number, not frequency.
Using size or empty are invalid for pair elements.
5fill in blank
hard

Fill 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'
Apush
Bsize
Cpop
Dtop
Attempts:
3 left
💡 Hint
Common Mistakes
Using top() instead of size() to check heap size.
Using pop() before checking size causes errors.