SDE & MLE Prep

347. Top K Frequent Elements

Problem

Return the k values that occur most often in nums, in any order. The answer is guaranteed to be unique.

Example: nums = [1,1,1,2,2,3], k = 2 → [1,2]

Constraints: n ≤ 10⁵. Follow-up: beat O(n log n).

Count, then bucket sort by frequency: bucket[f] holds numbers appearing f times (f ≤ n). Walk buckets from high to low until k numbers are collected. (A size-k min-heap gives O(n log k).)

nums = [1,1,1,2,2,3]   counts {1:3, 2:2, 3:1}
bucket: 0:[] 1:[3] 2:[2] 3:[1] ...   read from the right -> [1, 2]

Complexity: O(n) time, O(n) space.

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        cnt = Counter(nums)
        bucket = [[] for _ in range(len(nums) + 1)]
        for x, f in cnt.items():
            bucket[f].append(x)
        res = []
        for f in range(len(bucket) - 1, 0, -1):
            for x in bucket[f]:
                res.append(x)
                if len(res) == k:
                    return res
        return res