This problem follows the Bucket Sort / Heap pattern, commonly found in the Arrays & Hashing category. Recognizing this pattern is key to solving it efficiently in an interview setting.
Count frequencies, then use bucket sort where index = frequency.
Bucket sort by frequency avoids the O(n log n) of sorting — since frequency can be at most n, you get O(n) time.
count = Counter(nums)
buckets = [[] for _ in range(len(nums) + 1)]
for num, freq in count.items():
buckets[freq].append(num)
result = []
for i in range(len(buckets) - 1, 0, -1):
for num in buckets[i]:
result.append(num)
if len(result) == k: return resultPractice Top K Frequent Elements and similar Arrays & Hashing problems with flashcards. Build pattern recognition through active recall.
Practice this problem