InterviewHubPRO
Section Overview
Q67

Question 67 of 100

Part 8: Heaps, Priority Queues & Tries (65 - 72)

67%
DSA Patterns (Multi-Lang)•Part 8: Heaps, Priority Queues & Tries (65 - 72)

Top K Frequent Elements.

In Simple Words: Bucket Sort in $O(N)$ time:

  1. Count frequencies with Hash Map.
  2. Group elements into an array of buckets where index is the frequency: buckets[freq] = [elements].
  3. Iterate buckets backwards from $N$ down to 1 until $K$ elements are collected.
  • Time: $O(N)$ | Space: $O(N)$
Multi-Language Solutions
Switch tabs or choose All
def topKFrequent(nums: list[int], k: int) -> list[int]:
    count = {}
    for n in nums: count[n] = count.get(n, 0) + 1
    buckets = [[] for _ in range(len(nums) + 1)]
    for n, c in count.items():
        buckets[c].append(n)
    res = []
    for i in range(len(buckets) - 1, 0, -1):
        for n in buckets[i]:
            res.append(n)
            if len(res) == k:
                return res
    return res