Explain top-K.
Skip to solutionKEEP THE
hardDSA
How do you find the top K frequent elements?
175 views
01
Understand the problem
heaptop-k
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Nudge consolestandby
Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.
03
Study the solution
Count frequencies in a hash map, then keep a min-heap of size K by frequency (O(n log k)), or use bucket sort by frequency for O(n). Quickselect on frequencies is another average-O(n) approach.
Solution ready — 2 min read
Classified // press E to declassify
04
Read the code
Heap + bucket sort
Run Playgroundfrom collections import Counter
import heapq
def top_k_frequent(nums, k):
counts = Counter(nums)
# O(n log k) with a heap:
return heapq.nlargest(k, counts.keys(), key=counts.get)
def top_k_bucket(nums, k):
counts = Counter(nums)
buckets = [[] for _ in range(len(nums) + 1)]
for val, freq in counts.items():
buckets[freq].append(val)
result = []
for freq in range(len(buckets) - 1, 0, -1):
for val in buckets[freq]:
result.append(val)
if len(result) == k:
return result
return result
# --- demo ---
print(top_k_frequent([1, 1, 1, 2, 2, 3], 2)) # [1, 2]
print(top_k_bucket([1, 1, 1, 2, 2, 3], 2)) # [1, 2]05
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.
Transmission complete // awaiting log
KEEP THE
STREAK ALIVE.
Dossier 125 of 127 decoded in the Data Structures & Algorithms track. One more won't hurt.