Kth Largest Element in an Array
Advertisement
Problem
Find the kth largest element in an unsorted array. Not necessarily distinct.
Two approaches:
- Min-heap of size k — O(n log k)
- Quickselect — O(n) average, O(n²) worst
Solutions
// C — nth_element approach (quickselect)
int compare(const void* a, const void* b) { return *(int*)b - *(int*)a; }
int findKthLargest(int* nums, int n, int k) {
qsort(nums, n, sizeof(int), compare);
return nums[k-1];
}
// C++ — nth_element O(n) average
int findKthLargest(vector<int>& nums, int k) {
nth_element(nums.begin(), nums.begin() + k - 1, nums.end(), greater<int>());
return nums[k-1];
}
// Or min-heap:
int findKthLargestHeap(vector<int>& nums, int k) {
priority_queue<int, vector<int>, greater<int>> minH;
for (int n : nums) {
minH.push(n);
if ((int)minH.size() > k) minH.pop();
}
return minH.top();
}
// Java — min-heap
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> minH = new PriorityQueue<>();
for (int n : nums) {
minH.offer(n);
if (minH.size() > k) minH.poll();
}
return minH.peek();
}
// JavaScript — sort descending
function findKthLargest(nums, k) {
nums.sort((a, b) => b - a);
return nums[k - 1];
}
# Python — heapq.nlargest
import heapq
def findKthLargest(nums, k):
return heapq.nlargest(k, nums)[-1]
# Or min-heap:
def findKthLargestHeap(nums, k):
heap = nums[:k]
heapq.heapify(heap)
for n in nums[k:]:
if n > heap[0]:
heapq.heapreplace(heap, n)
return heap[0]
Complexity
- Heap: O(n log k) time, O(k) space
- Quickselect: O(n) avg time, O(1) space
- Sort: O(n log n)
Key Insight
Min-heap of size k: root is always the kth largest. If new element > root, replace root and fix heap.
Advertisement
← Previous
Top K Frequent ElementsNext →
Find K Closest Elements