Kth largest of n values, k much smaller than n. With heapq, which is O(n log k)?
Show answer
Answer
Keep a min heap of size k, pop when size exceeds k, answer is heap[0]
A size k min heap keeps the k largest and its root is the kth largest. Pushing all n values one by one is O(n log n) before any pop. A size k max heap evicts the wrong items. Sorting is O(n log n).
Source: Python heapq documentation