Top K Frequent Elements

Given a non-empty array of integers, return the k most frequent elements. Tags: Heap

Try It!

Discussion

Video

Solution

import heapq
from collections import Counter

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        counter = Counter(nums)
        heap = []
        for num in counter:
            count = counter[num]
            heapq.heappush(heap, (-count, num))
        
        ans = []
        for i in range(k):
            neg_count, num = heapq.heappop(heap)
            ans.append(num)
        return ans