Top K & Running Median
The Top K pattern
"Find the K largest", "K most frequent", "K closest points"…
Trick: keep a min-heap of size K. For each new item:
- push it;
- if the heap has more than K items, pop the smallest.
At the end, the heap holds the K largest. O(n log K) time and O(K) memory, much better than sorting everything (O(n log n)) when K is small.
K most frequent elements
- Count with
Counter. - Use a heap on the counts, or simply
Counter.most_common(k).
The running median (two heaps)
Keep:
- a max-heap for the smaller half,
- a min-heap for the larger half,
- balanced so their sizes differ by at most 1.
The median is the top of the bigger heap, or the average of both tops. Each insert is O(log n) and each median read is O(1).
Merge K sorted lists
Push the first item of each list into a heap; repeatedly pop the smallest and push the next item from its list. O(N log K).
💡 Hearing "K largest", "K smallest", "most frequent" or "streaming" in a question is a strong hint to use a heap.
Example
import heapq
from collections import Counter
def top_k(nums, k):
heap = []
for x in nums:
heapq.heappush(heap, x)
if len(heap) > k:
heapq.heappop(heap) # drop the smallest
return sorted(heap, reverse=True)
def most_frequent(words, k):
return [w for w, _ in Counter(words).most_common(k)]
class RunningMedian:
def __init__(self):
self.low, self.high = [], [] # max-heap (negated), min-heap
def add(self, x):
heapq.heappush(self.low, -x)
heapq.heappush(self.high, -heapq.heappop(self.low))
if len(self.high) > len(self.low):
heapq.heappush(self.low, -heapq.heappop(self.high))
def median(self):
if len(self.low) > len(self.high):
return -self.low[0]
return (-self.low[0] + self.high[0]) / 2
print(top_k([3, 1, 5, 12, 2, 11], 3)) # [12, 11, 5]
print(most_frequent(["a", "b", "a", "c", "b", "a"], 2)) # ['a', 'b']
rm = RunningMedian()
for x in [5, 15, 1, 3]:
rm.add(x)
print(rm.median(), end=" ") # 5 10.0 5 4.0
print()