Kth Largest Element in an Array
Medium
Topics
Given an integer array nums and an integer k (passed as target), return the k-th largest element in the array (in sorted order, not distinct).
Example 1
larger valuesthe 2th largest
The 2th largest is 5 — by position in sorted order, so duplicates each take a position.
Cells are the array values; the small numbers underneath are indices.
Input: nums = [3,2,1,5,6,4], k = 2 Output: 5
Example 2
larger valuesthe 4th largest
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 Output: 4
Constraints
- 1 <= k <= nums.length <= 10^4
- -10^4 <= nums[i] <= 10^4
Editorial — intuition, approach, complexity and pitfalls
Intuition
We only need the k-th largest, not a full sort. A min-heap of size k keeps exactly the k largest values seen; its root (the smallest of those) is the k-th largest overall.
Quickselect gives O(n) average time, but the heap is simpler and robust.
Approach
- Push each element into a min-heap.
- Whenever the heap exceeds size k, pop the smallest.
- After all elements, the heap holds the k largest and its root is the answer.
Walkthrough
nums = [3,2,1,5,6,4], k = 2
keep 2 largest: heap ends as [5, 6]; root 5 -> 2nd largest = 5Complexity
- Time — O(n log k): n elements, each an O(log k) heap op. Quickselect is O(n) average.
- Space — O(k): the heap holds at most k elements.
Common Pitfalls
sorted(nums)[-k], counting from the back. Indexing from the front gives the k-th smallest, and on the largest valid k it walks off the list withIndexError.- Sorting is O(n log n) for an O(n)-average problem. Quickselect, or a size-k min-heap at O(n log k), is the answer an interviewer is usually after -- the sort is here for clarity.
Full Solution — all languages
class Solution:
def findKthLargest(self, nums, target):
return sorted(nums)[-target]import java.util.*;
class Solution {
public int findKthLargest(int[] nums, int target) {
Arrays.sort(nums);
return nums[nums.length - target];
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int findKthLargest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
return nums[(int)nums.size() - target];
}
};/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/ var findKthLargest = function(nums, target) {
nums.sort((a, b) => a - b);
return nums[nums.length - target];
};