Top k frequent
Write top_k(nums, k) that returns the k most frequent values in nums, most frequent first. You can assume the answer is unique.
top_k([1, 1, 1, 2, 2, 3], 2)
# [1, 2]
Show hint
Count with a dictionary, then you need the k largest counts. A heap does that without sorting everything.
Show solution
import heapq
from collections import Counter
def top_k(nums, k):
counts = Counter(nums)
return heapq.nlargest(k, counts, key=counts.get)
Counting is O(n). heapq.nlargest keeps a heap of size k, so selecting is O(m log k) for m distinct values, which beats a full O(m log m) sort when k is small. Counter(nums).most_common(k) is the built-in shortcut.
Want a problem like this every day? See today's problem and keep a streak going.