CORE.DUMP

347. Top K Frequent Elements

Find the k most frequent elements in an array.

Medium#347HeapHash TableLeetCode

Approach: Min-Heap

Algorithm:

  1. Count the frequency of each element in the array.
  2. Use a min-heap to keep track of the k most frequent elements.
  3. Iterate through the frequency map and add elements to the heap, maintaining its size at k.
  4. Return the elements in the heap.
from collections import Counter
import heapq

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        count = Counter(nums)

        heap = []
        for num, freq in count.items():
            heapq.heappush(heap, (freq, num))
            if len(heap) > k:
                heapq.heappop(heap)

        return [num for _, num in heap]
  • Time: O(nlogk)O(n \log k) — where nn is the number of elements in the array, and we perform at most nn heap operations, each taking O(logk)O(\log k) time.
  • Space: O(n+k)O(n + k) — the frequency map holds up to nn entries and the heap holds up to kk elements.

Last updated on

On this page