Skip to content

Commit 3dff920

Browse files
committed
update solution: top-k-frequent-elements
1 parent 24792fe commit 3dff920

File tree

1 file changed

+39
-3
lines changed

1 file changed

+39
-3
lines changed

top-k-frequent-elements/dusunax.py

Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,44 @@
22
# Leetcode 347. Top K Frequent Elements
33
44
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.
5+
6+
- **solution 1**: use **sorted()** to sort the elements by their frequency in descending order.
7+
- **solution 2**: use **bucket sort** to sort the elements by their frequency in descending order. (efficient!)
68
79
## Time and Space Complexity
810
11+
### solution 1: topKFrequent()
12+
913
```
1014
TC: O(n log n)
1115
SC: O(n)
1216
```
1317
14-
### TC is O(n log n):
18+
#### TC is O(n log n):
1519
- iterating through the list just once to count the frequency of each element. = O(n)
1620
- sorting the elements by their frequency in descending order. = O(n log n)
1721
18-
### SC is O(n):
22+
#### SC is O(n):
1923
- using a Counter to store the frequency of each element. = O(n)
2024
- sorted() creates a new list that holds the elements of frequency_map. = O(n)
2125
- result list that holds the top k frequent elements. = O(k)
26+
27+
### solution 2: topKFrequentBucketSort()
28+
29+
```
30+
TC: O(n)
31+
SC: O(n)
32+
```
33+
34+
#### TC is O(n):
35+
- iterating through the list just once to count the frequency of each element. = O(n)
36+
- creating **buckets** to store the elements by their frequency. = O(n)
37+
- iterating through the buckets in reverse order to get only the top k frequent elements. = O(n)
38+
39+
#### SC is O(n):
40+
- using a Counter to store the frequency of each element. = O(n)
41+
- using buckets to store the elements by their frequency. = O(n)
42+
- result list that holds only the top k frequent elements. = O(k)
2243
'''
2344

2445
class Solution:
@@ -31,3 +52,18 @@ def topKFrequent(self, nums: List[int], k: int) -> List[int]:
3152
result.append(e[0])
3253

3354
return result[0:k]
55+
56+
def topKFrequentBucketSort(self, nums: List[int], k: int) -> List[int]:
57+
frequency_map = Counter(nums)
58+
n = len(nums)
59+
buckets = [[] for _ in range(n + 1)]
60+
61+
for num, freq in frequency_map.items():
62+
buckets[freq].append(num)
63+
64+
result = []
65+
for i in range(len(buckets) - 1, 0, -1):
66+
for num in buckets[i]:
67+
result.append(num)
68+
if len(result) == k:
69+
return result

0 commit comments

Comments
 (0)