#347
Top K Frequent Elements
MediumArrayHash TableDivide and ConquerSortingHeap (Priority Queue)Bucket SortCountingQuickselectHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n log n) | O(n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using a bucket sort approach allows us to efficiently group elements by their frequency, enabling us to directly access the top k frequent elements without sorting all elements.
⚙️
Algorithm
3 steps- 1Step 1: Create a frequency map to count occurrences of each element in nums.
- 2Step 2: Create an array of buckets where the index represents frequency and each bucket contains the elements with that frequency.
- 3Step 3: Iterate through the buckets in reverse order to collect the top k elements.
solution.py14 lines
1# Full working Python code
2from collections import Counter
3
4def topKFrequent(nums, k):
5 count = Counter(nums)
6 buckets = [[] for _ in range(len(nums) + 1)]
7 for num, freq in count.items():
8 buckets[freq].append(num)
9 result = []
10 for i in range(len(buckets) - 1, 0, -1):
11 for num in buckets[i]:
12 result.append(num)
13 if len(result) == k:
14 return resultℹ
Complexity note: The time complexity is O(n) since we traverse the list a constant number of times, while the space complexity is O(n) for storing the frequency map and buckets.
- 1Using a frequency map helps in counting occurrences efficiently.
- 2Bucket sort allows direct access to the most frequent elements without full sorting.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.