Sponsored
Sponsored
This approach uses a hash map to count the frequency of each element. We then use a min-heap to keep track of the top k elements.
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(n) for storing frequencies.
1function topKFrequent(nums, k) {
2 const freqMap = {};
3 for (const num of nums) {
4 freqMap[num] = (freqMap[num] || 0) + 1;
5 }
6
7 const minHeap = Object.keys(freqMap).sort((a, b) => freqMap[b] - freqMap[a]).slice(0, k);
8
9 return minHeap.map(Number);
10}
11
12const nums = [1, 1, 1, 2, 2, 3];
13const k = 2;
14console.log(topKFrequent(nums, k));
15We use an object to count frequencies, sort keys by frequency, and take the top k.
We manually record each element's frequency and sort the list based on counts into a frequency bucket. Then, we retrieve the top k elements.