Back to Problem
Official 2239 views

Editorial: Top K Frequent Elements

by admin ·

19

1 Intuition

Count, then rank.

2 Approach

Build a frequency map and sort distinct values by (-frequency, value). A bucket sort by frequency brings this to linear time.

3 Complexity Analysis

Time O(n log n) with sorting (O(n) with buckets), Space O(n).

4 Solution Code

class Solution:
    def topKFrequent(self, nums: list[int], k: int) -> list[int]:
        count = {}
        for x in nums:
            count[x] = count.get(x, 0) + 1
        return sorted(count, key=lambda v: (-count[v], v))[:k]

5 Code Walkthrough

The reference solution below implements the approach step by step.