19. Kth Largest Element in an Array
mediumAsked at ChimeFind the kth largest element in an unsorted array without fully sorting it.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in sorted order, not the kth distinct element. Solve it without sorting the full array if possible.
Constraints
1 <= k <= nums.length <= 10^5-10^4 <= nums[i] <= 10^4
Examples
Example 1
nums = [3,2,1,5,6,4], k = 25Example 2
nums = [3,2,3,1,2,4,5,5,6], k = 44Approaches
1. Sort the array
Sort descending and return index k-1. Easiest but ignores the constraint.
- Time
- O(n log n)
- Space
- O(1)
nums.sort((a, b) => b - a);
return nums[k - 1];Tradeoff:
2. Min-heap of size k
Maintain a min-heap of size k; the root after processing all elements is the kth largest. Uses O(n log k) time and O(k) extra space.
- Time
- O(n log k)
- Space
- O(k)
// pseudo-heap using sorted insert
function findKthLargest(nums, k) {
const heap = [];
for (const n of nums) {
if (heap.length < k) {
heap.push(n); heap.sort((a,b)=>a-b);
} else if (n > heap[0]) {
heap[0] = n; heap.sort((a,b)=>a-b);
}
}
return heap[0];
}Tradeoff:
Chime-specific tips
Chime asks this when they want to test top-k transaction amounts for fraud heuristics; mention that the heap pattern keeps memory bounded as the stream grows.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Kth Largest Element in an Array and other Chime interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →