Problem
Return the kth largest element in an unsorted integer array. This is the kth element in sorted descending order, not a distinct-value rank.
Examples
Example 1
`nums = [3, 2, 1, 5, 6, 4], k = 2``5`Example 2
`nums = [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4``4`Constraints
1 <= k <= nums.length <= 10^5-10^4 <= nums[i] <= 10^4
Hints
Hint 1
Duplicates count. For [3,2,1,5,6,4] and k = 2 the answer is 5, because the descending order is 6, 5, 4, 3, 2, 1.
Hint 2
"Kth largest" is a heap of size k, or Quickselect if you can rearrange the input.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Sort descending and pick index k-1. That is O(n log n).
Optimal. A min-heap of size k: the root is the kth largest after one pass. Average linear Quickselect is faster when mutation is allowed.
Alternative. A max-heap of all n elements, then pop k times, is O(n + k log n) and uses more memory.
Complexity
- Time
- O(n log k)
The heap scan is O(n log k) time and O(k) space. Quickselect is O(n) average time and O(1) extra space, but O(n²) in the worst case unless you add a fallback.
- Space
- O(k)
Code
import heapq
def find_kth_largest(nums: list[int], k: int) -> int:
heap: list[int] = []
for x in nums:
heapq.heappush(heap, x)
if len(heap) > k:
heapq.heappop(heap)
return heap[0]
if __name__ == "__main__":
assert find_kth_largest([3, 2, 1, 5, 6, 4], 2) == 5
assert find_kth_largest([3, 2, 3, 1, 2, 4, 5, 5, 6], 4) == 4
print("ok")import java.util.PriorityQueue;
public class KthLargestElementInAnArray {
static int findKthLargest(int[] nums, int k) {
var heap = new PriorityQueue<Integer>();
for (int x : nums) {
heap.offer(x);
if (heap.size() > k) heap.poll();
}
return heap.peek();
}
public static void main(String[] args) {
if (findKthLargest(new int[] {3, 2, 1, 5, 6, 4}, 2) != 5) throw new AssertionError();
if (findKthLargest(new int[] {3, 2, 3, 1, 2, 4, 5, 5, 6}, 4) != 4) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official samples: [3,2,1,5,6,4] with k = 2 returns 5, and [3,2,3,1,2,4,5,5,6] with k = 4 returns 4.
- k can be 1 (the maximum) or n (the minimum).
Follow-ups
- Kth Largest Element in a Stream keeps the same size-k min-heap as values arrive.
- If they want average linear time, I would explain Quickselect and the pivot-partition step.
Interview script
"A full sort is fine for a first version. For the interview I keep a min-heap of size k so the root is the kth largest, in n log k time. If they want average linear time, I switch to Quickselect."
Source: LeetCode 215: Kth Largest Element in an Array Source: Java SE 17 API: PriorityQueue
Sources (2)
- LeetCode 215: Kth Largest Element in an Arrayleetcode.com
- Java SE 17 API: PriorityQueuedocs.oracle.com