#40MediumHeap / Priority Queue

Kth Largest Element in an Array

Return the kth largest element in an unsorted array.

Constraints

  • •1 ≤ k ≤ nums.length ≤ 10⁵
Solution inPython
Python
import heapq

def findKthLargest(nums: list[int], k: int) -> int:
    return heapq.nlargest(k, nums)[-1]
How it works

heapq.nlargest(k, nums)[-1] uses a min-heap of size k internally. The last element of the k largest is the kth largest. O(n log k) time. Alternative: heapq.nsmallest on the negated array.