Kth Largest Element Using Max Heap in DSA Typescript - Time & Space Complexity
We want to know how the time needed to find the kth largest element changes as the input size grows.
Specifically, how the operations scale when using a max heap to solve this problem.
Analyze the time complexity of the following code snippet.
function findKthLargest(nums: number[], k: number): number {
const maxHeap = new MaxHeap();
for (const num of nums) {
maxHeap.insert(num);
}
let result = 0;
for (let i = 0; i < k; i++) {
result = maxHeap.extractMax();
}
return result;
}
This code builds a max heap from the array, then extracts the maximum element k times to find the kth largest.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Inserting each element into the max heap and extracting the max element k times.
- How many times: Insert runs n times (once per element), extractMax runs k times.
As the input size n grows, building the heap requires more insertions, each taking some time. Extracting k times also takes time depending on k.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 insertions + k extractions |
| 100 | About 100 insertions + k extractions |
| 1000 | About 1000 insertions + k extractions |
Pattern observation: Insertions grow linearly with n, extractions grow linearly with k, each operation takes time proportional to log n.
Time Complexity: O(n log n + k log n)
This means the time grows mostly by inserting all elements and then extracting k times, each operation taking about log n steps.
[X] Wrong: "Building the max heap takes only O(n) time, so total is just O(n + k log n)."
[OK] Correct: While heap construction can be done in O(n), inserting elements one by one as in this code costs O(n log n). So the total time is higher than just O(n).
Understanding how heap operations add up helps you explain your solution clearly and shows you know how to analyze performance in real problems.
"What if we used a min heap of size k instead of a max heap for the entire array? 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 a max heap and extract maxktimes -> Option DQuick Check:
Max heap extraction =kthlargest element [OK]
k times to get kth largest [OK]- Using min heap instead of max heap
- Sorting instead of using heap
- Extracting fewer or more than
ktimes
nums?Solution
Step 1: Understand heap comparator
To create a max heap, the comparator should order elements so that larger values come first, i.e.,(a, b) => b - a.Step 2: Check options
const maxHeap = new Heap(nums, (a, b) => b - a); uses(a, b) => b - a, which correctly creates a max heap.Final Answer:
const maxHeap = new Heap(nums, (a, b) => b - a); -> Option CQuick Check:
Comparatorb - a= max heap [OK]
(a, b) => b - a for max heap [OK]- Using default comparator which creates min heap
- Reversing comparator incorrectly
- Assuming new MaxHeap() exists without comparator
const nums = [3, 1, 5, 12, 2, 11];
const k = 3;
const maxHeap = new Heap(nums, (a, b) => b - a);
let kthLargest = null;
for (let i = 0; i < k; i++) {
kthLargest = maxHeap.extract();
}
console.log(kthLargest);Solution
Step 1: Build max heap from array
Max heap order: root is largest element. Initial max is 12, then 11, then 5.Step 2: Extract max
Extract 1: 12, Extract 2: 11, Extract 3: 5. Sok=3timeskthLargestis 5.Final Answer:
5 -> Option AQuick Check:
3rd largest in [3,1,5,12,2,11] = 5 [OK]
k times; last extracted is kth largest [OK]- Confusing 3rd largest with 3rd smallest
- Extracting fewer than
ktimes - Not building max heap correctly
kth largest element using a max heap:
const nums = [7, 10, 4, 3, 20, 15];
const k = 4;
const maxHeap = new Heap(nums, (a, b) => b - a);
let kthLargest = null;
for (let i = 0; i <= k; i++) {
kthLargest = maxHeap.extract();
}
console.log(kthLargest);Solution
Step 1: Check loop condition
The loop runs fromi = 0toi = kinclusive, so it runsk+1times.Step 2: Correct loop to run exactly
It should runktimesktimes, so condition must bei < k.Final Answer:
Loop runs one extra time; should bei < k-> Option BQuick Check:
Loop runsktimes to extractkthlargest [OK]
k times, not k+1 [OK]- Using <= instead of < in loop
- Wrong comparator for max heap
- Initializing variables incorrectly
nums with 1 million elements, which approach is most efficient to find the kth largest element when k is small (e.g., 10)?Solution
Step 1: Analyze time complexity of building max heap
Building max heap of 1 million elements is O(n), extractingktimes is O(k log n), which is costly.Step 2: Use min heap of size
Maintain a min heap of sizekkwhile iterating. This keeps topklargest elements efficiently in O(n log k).Step 3: Compare with sorting
Sorting entire array is O(n log n), slower than min heap approach for smallk.Final Answer:
Build a min heap of sizekand maintain it while iterating -> Option AQuick Check:
Min heap sizek= efficient for smallk[OK]
k for large arrays and small k [OK]- Building max heap of entire array for large data
- Sorting entire array unnecessarily
- Ignoring heap size optimization
Ready to prove it?
Pass the test and this pattern moves unknown
