Tensorum
LeetCode 347 · Top K

Top K Frequent Elements

LeetCode 347 · Medium · solution, intuition & step-by-step walkthrough

Counter + size-k min-heap on frequency.

MediumArrayHash TableDivide and ConquerSortingHeap (Priority Queue)
7 msruntime · beats 38%
20.8 MBmemory · beats 100%
1approach
10accepted runs · last 1 Jan 2026

This is how I solved Top K Frequent Elements (LeetCode 347), a medium problem from the Top K pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Count each value, then keep the k most frequent with a min-heap of (count, value) bounded at size k — the least frequent of the kept ones is always on top and gets evicted first.

Approach

  1. 1

    Count frequencies.

  2. 2

    Push (count, num); pop when the heap exceeds k.

  3. 3

    Return the values left in the heap.

How I solved it

Counter + min-heapPythonO(n log k) time
class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        freq_mpp = Counter(nums)
        min_heap = []
        for num,count in freq_mpp.items():
            heapq.heappush(min_heap,(count,num))
            if len(min_heap)>k:
                heapq.heappop(min_heap)
        return [num for count,num in min_heap]
Loading the step-through…

Top K Frequent Elements — FAQ

What is the intuition behind Top K Frequent Elements?

Count each value, then keep the k most frequent with a min-heap of (count, value) bounded at size k — the least frequent of the kept ones is always on top and gets evicted first.

How do you solve Top K Frequent Elements (LeetCode 347)?

1. Count frequencies. 2. Push (count, num); pop when the heap exceeds k. 3. Return the values left in the heap.

What is the time and space complexity of Top K Frequent Elements?

Time: O(n log k). Space: O(n). (Accepted approach: Counter + min-heap.)

What are common mistakes in Top K Frequent Elements?

Bucket sort by frequency gives O(n).