Kth Largest Element Using Max Heap in DSA C++ - Time & Space Complexity
We want to understand how long it takes to find the kth largest number using a max heap.
How does the time needed grow as the list of numbers gets bigger?
Analyze the time complexity of the following code snippet.
#include <vector>
#include <queue>
int findKthLargest(std::vector<int>& nums, int k) {
std::priority_queue<int> maxHeap(nums.begin(), nums.end());
for (int i = 1; i < k; ++i) {
maxHeap.pop();
}
return maxHeap.top();
}
This code builds a max heap from the list and removes the largest element k-1 times to get the kth largest.
- Primary operation: Building the max heap and popping elements from it.
- How many times: Building heap once over n elements, then popping k-1 times.
Building the heap takes time proportional to the number of elements, and each pop takes time related to the heap size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Build heap ~20 ops, pop up to k times ~k*log 10 |
| 100 | Build heap ~700 ops, pop up to k times ~k*log 100 |
| 1000 | Build heap ~10,000 ops, pop up to k times ~k*log 1000 |
Pattern observation: Building the heap grows roughly 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: "Popping k times from the heap is O(k) because each pop is just one step."
[OK] Correct: Each pop requires rearranging the heap, which takes time proportional to log n, not constant time.
Understanding this time complexity helps you explain how efficient your solution is and why heaps are useful for selection problems.
"What if we used a min heap of size k instead of a max heap of size n? How would the time complexity change?"
Practice
kth largest element using a max heap?Solution
Step 1: Understand max heap property
A max heap always keeps the largest element at the root, so extracting the root gives the current largest element.Step 2: Extract max
By removing the rootktimesktimes, the last extracted element is thekthlargest.Final Answer:
Build max heap and extract maxktimes -> Option BQuick Check:
Max heap extraction = kth largest element [OK]
k times to get kth largest [OK]- Using min heap instead of max heap
- Sorting and picking wrong index
- Confusing kth largest with kth smallest
nums in-place?Solution
Step 1: Understand std::make_heap default behavior
By default,std::make_heapcreates a max heap usingoperator<.Step 2: Check syntax correctness
std::make_heap(nums.begin(), nums.end()); correctly callsstd::make_heapon the vector range without extra comparators, making a max heap in-place.Final Answer:
std::make_heap(nums.begin(), nums.end()); -> Option DQuick Check:
Defaultmake_heap= max heap [OK]
- Using std::greater<int>() creates min heap
- Incorrect priority_queue constructor usage
- Confusing comparator direction
std::vector<int> nums = {3, 2, 1, 5, 6, 4};
std::make_heap(nums.begin(), nums.end());
for (int i = 0; i < 2; ++i) {
std::pop_heap(nums.begin(), nums.end() - i);
}
int kthLargest = nums[0];
std::cout << kthLargest << std::endl;Solution
Step 1: Build max heap from nums
Heap aftermake_heapis [6, 5, 4, 2, 3, 1] (largest at front).Step 2: Perform two pop_heap operations
First pop_heap moves 6 to end, second pop_heap moves 5 next to end. Now,nums[0]is 5.Final Answer:
5 -> Option CQuick Check:
After 2 pops, root = 5 [OK]
- Assuming root stays 6 after pops
- Confusing pop_heap with pop_back
- Not adjusting heap size correctly
std::vector<int> nums = {7, 10, 4, 3, 20, 15};
std::priority_queue<int> maxHeap(nums.begin(), nums.end());
int kthLargest;
for (int i = 0; i < 3; ++i) {
kthLargest = maxHeap.top();
maxHeap.pop();
}
std::cout << kthLargest << std::endl;Solution
Step 1: Check priority_queue construction
ConstructingmaxHeapfrom vector range is valid and creates max heap.Step 2: Verify loop logic for kth largest
Loop extracts top element 3 times; last extracted is 3rd largest.Final Answer:
No error, code works correctly -> Option AQuick Check:
Priority queue pop k times = kth largest [OK]
- Thinking priority_queue constructor is invalid
- Off-by-one error in loop count
- Confusing make_heap and priority_queue usage
Solution
Step 1: Efficiency priority
For large n, O(n log k) is best vs O(n log n); min-heap size k scans once.Step 2: Track unique top-k largest
Iterate array, maintain min-heap of top 5 uniques (with set for lookup); add if new and > root or size <5, evict root otherwise.Final Answer:
Use a min heap of size 5 to track unique elements while iterating -> Option AQuick Check:
Min-heap size k + set = O(n log k) kth unique largest [OK]
- Full max heap pop until k unique (worst O(n log n) with dup leaders)
- Set first: O(n log n) time/space
- Sorting without explicit dedup logic
Ready to prove it?
Pass the test and this pattern moves unknown
