Kth Largest Element Using Max Heap in DSA C - Time & Space Complexity
We want to understand how the time needed to find the kth largest element grows as the input size changes.
How does the number of steps change when we use a max heap for this task?
Analyze the time complexity of the following code snippet.
void buildMaxHeap(int arr[], int n);
int extractMax(int arr[], int *n);
int kthLargest(int arr[], int n, int k) {
buildMaxHeap(arr, n);
int maxVal = -1;
for (int i = 0; i < k; i++) {
maxVal = extractMax(arr, &n);
}
return maxVal;
}
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: Building the max heap once, then extracting the max element k times.
- How many times: Building heap happens once over n elements; extractMax runs k times, each adjusting the heap.
Building the heap takes time proportional to the number of elements, and each extraction takes time proportional to the heap height.
| Input Size (n) | Approx. Operations |
|---|---|
| 10, k=3 | Build heap ~ 30 steps, Extract max 3 * 4 steps = 12 steps |
| 100, k=10 | Build heap ~ 700 steps, Extract max 10 * 7 steps = 70 steps |
| 1000, k=50 | Build heap ~ 10,000 steps, Extract max 50 * 10 steps = 500 steps |
Pattern observation: Building the heap grows roughly linearly with n, while each extraction grows with log n, repeated k times.
Time Complexity: O(n + k log n)
This means the time grows linearly with the input size to build the heap, plus k times the logarithm of n for extractions.
[X] Wrong: "Extracting the max k times takes O(k * n) time because each extraction scans the whole array."
[OK] Correct: Each extraction only adjusts the heap, which is a tree structure, so it takes O(log n) time, not scanning all elements.
Understanding this time complexity helps you explain why heaps are efficient for selection problems and shows your grasp of data structure operations.
"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 rootktimes to getkthlargestktimes, the last extracted element is thekthlargest.Final Answer:
Build a max heap and extract maxktimes -> Option BQuick Check:
Max heap extraction =kthlargest element [OK]
k times to find kth largest [OK]- Using min heap instead of max heap
- Extracting fewer or more than
ktimes - Sorting and picking wrong index
arr of size n?Solution
Step 1: Identify heapify starting point
Heapify must start from the last non-leaf node, which is at indexn/2 - 1, moving upwards.Step 2: Loop from
This ensures all subtrees satisfy max heap property, building the heap correctly.n/2 - 1down to 0Final Answer:
for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); -> Option CQuick Check:
Build max heap loop = fromn/2 - 1down [OK]
- Starting heapify from 0 upwards
- Starting heapify from last element
- Using wrong loop boundaries
int arr[] = {4, 10, 3, 5, 1};
int n = 5;
int k = 3;
buildMaxHeap(arr, n);
int result;
for (int i = 0; i < k; i++) {
result = extractMax(arr, &n);
}
printf("%d\n", result);
Assume buildMaxHeap and extractMax work correctly.Solution
Step 1: Build max heap from array
Max heap root is 10, heap structure after build: [10, 5, 3, 4, 1]Step 2: Extract max 3 times
1st extract: 10, 2nd extract: 5, 3rd extract: 4 (this is the 3rd largest)Final Answer:
4 -> Option DQuick Check:
3rd largest element = 4 [OK]
k times; last extracted is kth largest [OK]- Confusing 3rd largest with 3rd smallest
- Not updating heap size after extraction
- Assuming array is sorted after buildMaxHeap
int arr[] = {7, 2, 9, 4};
int n = 4;
int k = 2;
buildMaxHeap(arr, n);
int result = extractMax(arr, n);
for (int i = 1; i < k; i++) {
result = extractMax(arr, n);
}
printf("%d\n", result);Solution
Step 1: Check heap size update after extraction
Extracting max reduces heap size, butnis passed unchanged, so heap operations are incorrect.Step 2: Correct by passing pointer or updating
Heap size must decrease after each extraction to maintain heap property correctly.nFinal Answer:
Heap sizenis not updated after extraction -> Option AQuick Check:
Update heap size after extractMax [OK]
- Not decreasing heap size after extractMax
- Incorrect loop start index
- Assuming array must be sorted before heap
arr = {12, 3, 5, 7, 19, 0, 4}, write the steps to find the 4th largest element using a max heap. What is the 4th largest element?Solution
Step 1: Build max heap from the array
Heap root is 19, heap structure after build: [19, 12, 5, 7, 3, 0, 4]Step 2: Extract max 4 times
1st extract: 19, 2nd extract: 12, 3rd extract: 7, 4th extract: 5Step 3: Identify the 4th largest element
The 4th extracted max is 5 (since extraction order is 19, 12, 7, 5, the 4th largest is 5)Final Answer:
5 -> Option AQuick Check:
4th largest element = 5 [OK]
k times; last extracted is kth largest [OK]- Mixing extraction order and element values
- Counting extraction incorrectly
- Not building max heap properly
Ready to prove it?
Pass the test and this pattern moves unknown
