Skip to content

Commit 9a395e9

Browse files
committed
add solution: top-k-frequent-elements
1 parent be09081 commit 9a395e9

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

top-k-frequent-elements/dusunax.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
'''
2+
# Leetcode 347. Top K Frequent Elements
3+
4+
use **Counter** to count the frequency of each element in the list 🚀
5+
use **sorted()** to sort the elements by their frequency in descending order.
6+
7+
## Time and Space Complexity
8+
9+
```
10+
TC: O(n log n)
11+
SC: O(n)
12+
```
13+
14+
### TC is O(n log n):
15+
- iterating through the list just once to count the frequency of each element. = O(n)
16+
- sorting the elements by their frequency in descending order. = O(n log n)
17+
18+
### SC is O(n):
19+
- using a Counter to store the frequency of each element. = O(n)
20+
- sorted() creates a new list that holds the elements of frequency_map. = O(n)
21+
- result list that holds the top k frequent elements. = O(k)
22+
'''
23+
24+
class Solution:
25+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
26+
frequency_map = Counter(nums) # TC: O(n), SC: O(n)
27+
sorted_frequencies = sorted(frequency_map.items(), key=lambda x: x[1], reverse=True) # TC: O(n log n), SC: O(n)
28+
29+
result = [] # SC: O(k)
30+
for e in sorted_frequencies: # TC: O(k)
31+
result.append(e[0])
32+
33+
return result[0:k]

0 commit comments

Comments
 (0)