Skip to content

Commit 06d5ee3

Browse files
committed
feat: [Week 01-3] solve Top K Frequent Elements
1 parent cc39916 commit 06d5ee3

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

top-k-frequent-elements/Chaedie.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""
2+
Solution:
3+
1. make a dictionary of (index, Frequency)
4+
2. sort the items of dictionary by Frequency
5+
3. return list of Top k Frequent Elements
6+
7+
Time Complexity:
8+
1. iterate nums for counting -> O(n)
9+
2. sort -> O(n log n)
10+
3. iterate list for making return value -> O(n)
11+
12+
So Time complexity of this solution is O(n log n)
13+
14+
Space Complexity:
15+
1. dictionary for counting frequency of nums -> O(n)
16+
2. sorted List -> O(n)
17+
18+
Space complexity of this solution is O(n)
19+
"""
20+
21+
22+
class Solution:
23+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
24+
counts = defaultdict(int)
25+
for num in nums:
26+
counts[num] += 1
27+
28+
result = sorted(counts.items(), key=lambda x: x[1], reverse=True)
29+
return list(map(lambda x: x[0], result[:k]))

0 commit comments

Comments
 (0)