Skip to Content

Top K Frequent Elements

Home | Coding Interviews | Stacks and Queues | Top K Frequent Elements

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

#Heap/priority queue solution
def topKFrequent_heap(self, nums: List[int], k: int) -> List[int]:
    result = []
    max_heap = [(-val, key) for key,val in collections.Counter(nums).items()]
    heapq.heapify(max_heap)
    for _ in range(k):
        result.append(heapq.heappop(max_heap)[1])
    return result

#Bucket Sort style solutions
class BucketSortSolution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        cnt = Counter(nums)
        buckets = [[] for _ in range(len(nums) + 1)]
        for val, freq in cnt.items():
            buckets[freq].append(val)
        
        return list(chain(*buckets[::-1]))[:k]

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

Heap solution:

Bucket sort solution:

Posted by Jamie Meyer 19 days ago