Kth Smallest Element Using Min Heap in DSA C++ - Time & Space Complexity
We want to understand how long it takes to find the kth smallest number using a min heap.
How does the time needed grow as the list gets bigger?
Analyze the time complexity of the following code snippet.
#include <queue>
#include <vector>
int kthSmallest(std::vector<int>& nums, int k) {
std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap(nums.begin(), nums.end());
for (int i = 1; i < k; ++i) {
minHeap.pop();
}
return minHeap.top();
}
This code builds a min heap from the list and removes the smallest element k-1 times to find the kth smallest.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Removing the smallest element from the min heap (pop operation).
- How many times: The pop operation repeats k-1 times.
- Building the min heap from the array happens once at the start.
Building the heap takes time proportional to the size of the list, then each pop takes time related to the heap size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Build heap ~ O(10), pop k-1 times (each ~ O(log 10)) |
| 100 | Build heap ~ O(100), pop k-1 times (each ~ O(log 100)) |
| 1000 | Build heap ~ O(1000), pop k-1 times (each ~ O(log 1000)) |
Pattern observation: Building heap grows linearly with n, popping grows with k times log n.
Time Complexity: O(n + k log n)
This means the time grows mostly with the size of the list and the number of pops, each pop taking a bit longer as the list grows.
[X] Wrong: "The time is just O(k) because we pop k times."
[OK] Correct: Each pop operation takes time related to the heap size (log n), not constant time, so total time depends on k times log n plus building the heap.
Understanding this time complexity helps you explain why using a heap is efficient for finding the kth smallest element compared to sorting the whole list.
"What if we used a max heap of size k instead of a min heap of size n? How would the time complexity change?"
Practice
kth smallest element using a min heap?Solution
Step 1: Understand min heap property
A min heap always keeps the smallest element at the root, so extracting the root gives the smallest element.Step 2: Extract minimum
By extracting the rootktimesktimes, we get thekthsmallest element.Final Answer:
Build a min heap and extract minimumktimes -> Option BQuick Check:
Min heap extraction = kth smallest element [OK]
- Using max heap instead of min heap
- Sorting array instead of using heap
- Confusing kth smallest with kth largest
Solution
Step 1: Understand default heap behavior
By default,std::make_heapcreates a max heap.Step 2: Use comparator for min heap
Passingstd::greater<int>()as comparator creates a min heap.Final Answer:
std::make_heap with std::greater comparator -> Option AQuick Check:
std::make_heap + std::greater = min heap [OK]
- Using default make_heap creates max heap
- Confusing push_heap and make_heap
- Using pop_heap to create heap
std::vector<int> v = {7, 10, 4, 3, 20, 15};
std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap(v.begin(), v.end());
int k = 3;
int kthSmallest;
for (int i = 0; i < k; i++) {
kthSmallest = minHeap.top();
minHeap.pop();
}
std::cout << kthSmallest << std::endl;Solution
Step 1: Build min heap from vector
The min heap elements in order of extraction are 3, 4, 7, 10, 15, 20.Step 2: Extract min 3 times
Extracted elements: 3 (1st), 4 (2nd), 7 (3rd). So, kth smallest (k=3) is 7.Final Answer:
7 -> Option CQuick Check:
3rd smallest element = 7 [OK]
- Confusing kth smallest with kth largest
- Off-by-one error in loop
- Not popping from heap after top
std::vector<int> nums = {5, 3, 8, 4, 2};
std::priority_queue<int> minHeap(nums.begin(), nums.end());
int k = 2;
int result;
for (int i = 0; i < k; i++) {
result = minHeap.top();
minHeap.pop();
}
std::cout << result << std::endl;Solution
Step 1: Check priority_queue default behavior
By default,std::priority_queueis a max heap, so it will give the largest element first.Step 2: Effect on kth smallest extraction
Extracting top k times from max heap gives kth largest, not kth smallest.Final Answer:
priority_queue creates max heap by default, not min heap -> Option AQuick Check:
Default priority_queue = max heap [OK]
- Assuming priority_queue is min heap by default
- Wrong loop count for kth element
- Calling pop before top
kth smallest unique element?Solution
Step 1: Remove duplicates using hash set
Using a hash set removes duplicates efficiently, reducing the data size.Step 2: Build min heap from unique elements and extract kth
Building min heap from unique elements and extracting kth smallest is efficient and correct.Final Answer:
Use a hash set to remove duplicates, then build min heap and extract kth element -> Option DQuick Check:
Remove duplicates first, then min heap extraction [OK]
- Extracting kth smallest without removing duplicates
- Using max heap instead of min heap
- Sorting entire array unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
