SDE & MLE Prep

215. Kth Largest Element in an Array

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]