LC 347
LeetCode 347 · Medium

Top K Frequent Elements

Return the k most frequent elements.

Heap → · High frequency · Solve on LeetCode →

Try it

Step through the core mechanic. The simulator below runs the heap shape this problem is built on.

Walk the pattern

No dedicated step-through for this one yet. The shape is Heap — its pattern page has the interactive walkthrough, the reference implementation, and a five-problem progression that this problem sits inside.

The approach

Count with a hash map, then bucket-sort by frequency (index = count) for O(n), or push counts through a size-k heap for O(n log k).

AspectValue
PatternHeap
Recognise it byTop-K by count.
Time complexityO(n)
Space complexityO(n)
DifficultyMedium

Who asks it

Companies known to ask this problem, from public LeetCode company-tag aggregations. A signal of where to expect it, not a guarantee.