Problem Statement
Efficiently get the top k largest elements from a large list without fully sorting it. Which is best?
Explanation
heapq.nlargest uses a small heap of size k and runs faster than sorting everything when k is much smaller than n.
Full sorts are O(n log n). nlargest runs in O(n log k).
Code Solution
SolutionRead Only
import heapq best = heapq.nlargest(3, [5,1,8,4,9])
