Top K Frequent Elements
Picture
In [a,a,a,b,b,c], frequencies are a:3, b:2, c:1. The raw input order is not the priority.
Predict
Which heap root is useful when keeping the k largest frequencies?
Walk through the small example
The smallest current winner. Counting separates identity from priority; a size-k heap keeps only candidates that can still be winners.
Mental model and complete Python solution
The heap is not the answer set because it is sorted. It is useful because its root is the easiest winner to replace—the smallest frequency currently admitted.
What the function promises: Return k items ordered by decreasing frequency, then increasing first-seen position. Require 0 <= k <= distinct item count.
from heapq import heappush, heapreplace
def top_k_frequent(values, k):
first, counts = {}, {}
for i, value in enumerate(values):
first.setdefault(value, i)
counts[value] = counts.get(value, 0) + 1
if not 0 <= k <= len(counts):
raise ValueError("Invalid k")
heap = []
for value, count in counts.items():
entry = (count, -first[value], value)
if len(heap) < k:
heappush(heap, entry)
elif entry[:2] > heap[0][:2]:
heapreplace(heap, entry)
return [value for _, _, value in sorted(heap, reverse=True)]
assert top_k_frequent(['a','a','a','b','b','c'], 2) == ['a','b']
assert top_k_frequent([], 0) == []
Work and storage: O(n + u log k) time and O(u + k) space for u distinct values.
When to recognize it: Counting separates identity from priority; a size-k heap keeps only candidates that can still be winners.
Check before applying it: Tie ordering must be defined, and heap tuples may compare items unexpectedly when priorities tie.
Change one rule
The key range is small and k may be large.
See what changes
Place values into buckets indexed by frequency, then scan buckets downward.
Connect
dictionaries: Count each value before selecting by frequency.
Kth Largest Element: Partitioning can select a rank when all items are already stored.