hardDSA

How do you find the top K frequent elements?

175 views
01

Understand the problem

Explain top-K.

heaptop-k
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

Heap + bucket sort
Run Playground
from 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.