0
0
DSA C++programming~10 mins

Kth Smallest Element Using Min 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 create a min heap from the vector.

DSA C++
std::priority_queue<int, std::vector<int>, [1]> minHeap(nums.begin(), nums.end());
Drag options to blanks, or click blank then click option'
Astd::greater<int>
Bstd::less<int>
Cstd::equal_to<int>
Dstd::not_equal_to<int>
Attempts:
3 left
💡 Hint
Common Mistakes
Using std::less creates a max heap, not a min heap.
Forgetting to specify the comparator leads to max heap behavior.
2fill in blank
medium

Complete the code to pop the smallest element from the min heap.

DSA C++
minHeap.[1]();
Drag options to blanks, or click blank then click option'
Aremove
Bdelete
Cpop
Dextract
Attempts:
3 left
💡 Hint
Common Mistakes
Using remove or delete which are not valid methods for priority_queue.
Trying to erase elements by value instead of popping the top.
3fill in blank
hard

Fix the error in the code to get the kth smallest element from the min heap.

DSA C++
for (int i = 1; i < [1]; ++i) {
    minHeap.pop();
}
return minHeap.top();
Drag options to blanks, or click blank then click option'
Ak
Bk-1
Ck*2
Dk+1
Attempts:
3 left
💡 Hint
Common Mistakes
Using k-1 in the loop condition causes one less pop than needed.
Using k+1 or k*2 causes too many pops and wrong result.
4fill in blank
hard

Fill both blanks to complete the function that returns the kth smallest element using a min heap.

DSA C++
int kthSmallest(std::vector<int>& nums, int k) {
    std::priority_queue<int, std::vector<int>, [1]> minHeap(nums.begin(), nums.end());
    for (int i = 1; i < [2]; ++i) {
        minHeap.pop();
    }
    return minHeap.top();
}
Drag options to blanks, or click blank then click option'
Astd::greater<int>
Bk
Ck-1
Dstd::less<int>
Attempts:
3 left
💡 Hint
Common Mistakes
Using std::less creates max heap, wrong for kth smallest.
Looping until i < k-1 pops too few elements.
5fill in blank
hard

Fill all three blanks to create a function that returns the kth smallest element using a min heap and handles empty input.

DSA C++
int kthSmallest(std::vector<int>& nums, int k) {
    if (nums.empty() || k > nums.size()) return -1;
    std::priority_queue<int, std::vector<int>, [1]> minHeap(nums.begin(), nums.end());
    for (int i = 1; i < [2]; ++i) {
        minHeap.[3]();
    }
    return minHeap.top();
}
Drag options to blanks, or click blank then click option'
Astd::greater<int>
Bk
Cpop
Dstd::less<int>
Attempts:
3 left
💡 Hint
Common Mistakes
Not checking for empty input or k out of range.
Using wrong comparator or wrong method to remove elements.