Return the k-th largest element in the array (1-indexed: k=1 is the maximum).
Assume 1 <= k <= len(nums).
kthLargest(nums, k)
Input format: nums | k.
[3, 2, 1, 5, 6, 4], k=2 // → 5
[3, 2, 3, 1, 2, 4, 5, 5, 6], k=4 // → 4
[1], k=1 // → 1
The obvious approach: sort descending, read off index k-1. Correct, but it does more work than needed — full sorting establishes order among every element when you only need one specific rank.
Sorting costs O(n log n) because it figures out the relative order of all n elements, including relationships you'll never use (is the 37th largest bigger than the 52nd?). If k is small relative to n, most of that effort is wasted.
Maintain a running min-heap of just the k largest values seen so far:
A heap of size k gives O(log k) insertion and removal, bounded by log k rather than log n. Across n elements: O(n log k) total — better than O(n log n) whenever k is much smaller than n.
A sorted array of k candidates would cost O(k) per insert/evict (shifting), giving O(nk) overall — worse than O(n log k) for larger k. The heap's weaker "only track the minimum" guarantee is exactly what keeps both operations cheap.
import heapq
def kth_largest(nums, k):
return heapq.nlargest(k, nums)[-1]
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.