215. Kth Largest Element in an Array
Asked at 37Meta94Apple68Amazon63Microsoft61Bloomberg57Google55Spotify83LinkedIn61Infosys45tcs42Pocket Gems100Avito96Texas Instruments88Alibaba68BNY Mellon65Morgan Stanley64TikTok63SAP62Walmart Labs60Zoho60Autodesk59Flipkart59Coupang58Qualcomm58ServiceNow55Accenture54eBay53IBM50Deloitte50Oracle49Goldman Sachs47Adobe44Salesforce41Nvidia39Visa39DE Shaw38Uber22
Problem
Return the k-th largest element of nums (in sorted order, so duplicates count; not the k-th distinct value).
Example: nums = [3,2,1,5,6,4], k = 2 → 5; nums = [3,2,3,1,2,4,5,5,6], k = 4 → 4
Constraints: n ≤ 10⁵. Can you do it without sorting?
Min-heap of size k → root is the k-th largest. Interview follow-up: quickselect (partition around a pivot, recurse into one side) for average O(n).
Complexity: heap O(n log k); quickselect O(n) average.
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
h = []
for x in nums:
heappush(h, x)
if len(h) > k:
heappop(h)
return h[0]
assert Solution().findKthLargest([3, 2, 1, 5, 6, 4], 2) == 5
assert Solution().findKthLargest([3, 2, 3, 1, 2, 4, 5, 5, 6], 4) == 4
class Solution {
// quickselect with 3-way partition (random pivot): average O(n)
public int findKthLargest(int[] nums, int k) {
int target = nums.length - k, lo = 0, hi = nums.length - 1;
Random rnd = new Random(7);
while (true) {
int pivot = nums[lo + rnd.nextInt(hi - lo + 1)];
int lt = lo, i = lo, gt = hi; // [lo,lt) < p, [lt,i) == p, (gt,hi] > p
while (i <= gt) {
if (nums[i] < pivot) swap(nums, lt++, i++);
else if (nums[i] > pivot) swap(nums, i, gt--);
else i++;
}
if (target < lt) hi = lt - 1;
else if (target > gt) lo = gt + 1;
else return pivot;
}
}
private void swap(int[] a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; }
}
type IntHeap []int // min-heap
func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x any) { *h = append(*h, x.(int)) }
func (h *IntHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
func findKthLargest(nums []int, k int) int {
h := &IntHeap{} // the k largest seen so far
for _, x := range nums {
heap.Push(h, x)
if h.Len() > k {
heap.Pop(h)
}
}
return (*h)[0]
}