Loading
Loading
A heap of size k beats sorting everything you do not need.
When only the k best items matter, keep a heap holding exactly k candidates. Counter-intuitively you keep a min-heap to find the k largest: the smallest of your current winners sits at the top, ready to be evicted the moment something better arrives. The full input is never sorted.
For the k largest, keep a min-heap of size k. The root is the weakest survivor, so deciding whether to admit a newcomer is one comparison. For the k smallest, invert the comparator.
The shape, not a solution. Adapt the condition and the state to the problem in front of you.
import heapq def k_largest(nums, k): """A MIN-heap of size k: its root is the weakest element still in the set.""" heap = [] for value in nums: heapq.heappush(heap, value) if len(heap) > k: heapq.heappop(heap) # evicts the smallest, keeping the k largest return sorted(heap, reverse=True) def k_most_frequent(items, k): counts = {} for item in items: counts[item] = counts.get(item, 0) + 1 heap = [] for item, count in counts.items(): heapq.heappush(heap, (count, item)) if len(heap) > k: heapq.heappop(heap) return [item for _count, item in sorted(heap, reverse=True)]| Status | Problem | Difficulty | Role |
|---|---|---|---|
| Top Frequency Codes#21 | Medium | Primary | |
| K-th Loudest Reading#111 | Easy | Primary | |
| Nearest Charging Stations#113 | Medium | Primary | |
Sign in to keep a note here. It is free, and nobody else can see it.
Sign in| Top Search Terms#115 |
| Medium |
| Primary |
| K-th Smallest in a Sorted Grid#128 | Medium | Related |