Kth Largest Element in an Array

Find the kth largest via min-heap of size k or quickselect for average O(n).

Medium
Time O(n) avg via quickselect Space O(1)
LeetCode
4 min read
top-k heaps quickselect

Problem#

Return the kth largest element of nums (sorted descending, 1-indexed).

Examples#

  • [3,2,1,5,6,4], k = 25
  • [3,2,3,1,2,4,5,5,6], k = 44

Constraints#

  • 1 <= k <= nums.length <= 10^5.

Approach#

Min-heap size k — O(n log k). Simple, robust.
Quickselect — O(n) average. Partition around a pivot; recurse on the side containing position n - k.

Solution#

Kth Largest Element (quickselect)
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int target = nums.size() - k;
int lo = 0, hi = nums.size() - 1;
while (lo < hi) {
int p = partition(nums, lo, hi);
if (p == target) return nums[p];
if (p < target) lo = p + 1; else hi = p - 1;
}
return nums[lo];
}
private:
int partition(vector<int>& a, int lo, int hi) {
int pivot = a[hi];
int i = lo;
for (int j = lo; j < hi; ++j)
if (a[j] < pivot) swap(a[i++], a[j]);
swap(a[i], a[hi]);
return i;
}
};

Editorial#

Quickselect partitions around a pivot until the pivot lands at the target index. Each recursion halves the expected work (average O(n)); worst-case is O(n²) on adversarial pivot, mitigated by random or median-of-three pivot choice. For deterministic O(n log k), use the bounded min-heap.

Complexity#

  • Time: O(n) average, O(n²) worst-case.
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.