How would you find the K largest elements in an array?
Options and trade-offs:
- Sort then slice: O(n log n) time, simplest, fine for small n.
- Min-heap of size k: O(n log k) time, O(k) space. Preferred when k is small relative to n.
import heapq
def k_largest(nums, k):
return heapq.nlargest(k, nums) # maintains a size-k heap internally
- Quickselect: average O(n), worst O(n^2), mutates/partitions the array, good when k is close to n.
Follow-ups: streaming data (keep the heap across batches), finding the kth smallest, or using a bucket approach when values are bounded.