Skip to content

Commit 5744078

Browse files
committed
Add solution for Top K Frequent Elements
1 parent 8b69386 commit 5744078

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"""
2+
# Intuition
3+
N is can be up to 100000, so time complexity should be O(N log N) at least.
4+
Calculate the frequency of its elements using dictionary, sort it, and list top K ones.
5+
6+
# Approach
7+
1. for n in nums:
8+
1-1. if n in map: map[n] += 1
9+
2. sort it by its value
10+
3. slice and return top K
11+
12+
# Complexity
13+
Let:
14+
- N = len(nums)
15+
- M = number of unique elements in nums
16+
17+
Time complexity:
18+
- O(N) + O(M log M) + O(K)
19+
- O(N log N) when all elements are unique.
20+
21+
Space complexity:
22+
- O(M) + O(M) + O(K)
23+
- Overall: O(N) in the worst case.
24+
"""
25+
26+
from collections import defaultdict
27+
28+
29+
class Solution:
30+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
31+
dic = defaultdict(int)
32+
for n in nums:
33+
dic[n] += 1
34+
value_sorted = sorted(dic.items(), key=lambda x: -x[1])
35+
return [i[0] for i in value_sorted[:k]]

0 commit comments

Comments
 (0)