Top K Frequent Elements

LeetCode

LeetCode: https://leetcode.com/problems/top-k-frequent-elements/

Given an integer array nums and an integer k, return the k most frequent elements.

1import heapq
2
3def topKFrequent(nums: List[int], k: int) -> List[int]:
4 freq = {}
5 for x in nums:
6 freq[x] = freq.get(x, 0) + 1
7
8 heap = []
9 for x, f in freq.items():
10 heapq.heappush(heap, (f, x))
11 if len(heap) > k:
12 heapq.heappop(heap)
13
14 return [x for (_, x) in heap]
1
0
1
1
1
2
2
3
2
4
3
5
k=2
Step 1 / 3
Step 1:
Count frequencies, then keep a min-heap of size k by frequency.
Focus: select @ [0, 3, 5]
k=2