|
| 1 | +''' |
| 2 | +# Leetcode 347. Top K Frequent Elements |
| 3 | +
|
| 4 | +use **Counter** to count the frequency of each element in the list 🚀 |
| 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!) |
| 8 | +
|
| 9 | +## Time and Space Complexity |
| 10 | +
|
| 11 | +### solution 1: topKFrequent() |
| 12 | +
|
| 13 | +``` |
| 14 | +TC: O(n log n) |
| 15 | +SC: O(n) |
| 16 | +``` |
| 17 | +
|
| 18 | +#### TC is O(n log n): |
| 19 | +- iterating through the list just once to count the frequency of each element. = O(n) |
| 20 | +- sorting the elements by their frequency in descending order. = O(n log n) |
| 21 | +
|
| 22 | +#### SC is O(n): |
| 23 | +- using a Counter to store the frequency of each element. = O(n) |
| 24 | +- sorted() creates a new list that holds the elements of frequency_map. = O(n) |
| 25 | +- 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) |
| 43 | +''' |
| 44 | + |
| 45 | +class Solution: |
| 46 | + def topKFrequent(self, nums: List[int], k: int) -> List[int]: |
| 47 | + frequency_map = Counter(nums) # TC: O(n), SC: O(n) |
| 48 | + sorted_frequencies = sorted(frequency_map.items(), key=lambda x: x[1], reverse=True) # TC: O(n log n), SC: O(n) |
| 49 | + |
| 50 | + result = [] # SC: O(k) |
| 51 | + for e in sorted_frequencies: # TC: O(k) |
| 52 | + result.append(e[0]) |
| 53 | + |
| 54 | + 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