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));
15
We use an object to count frequencies, sort keys by frequency, and take the top k.
This approach involves using bucket sort where we create buckets for frequency counts and then extract the top k frequent elements.
Time Complexity: O(n + k).
Space Complexity: O(n).
1function topKFrequent(nums, k) {
2 const freqMap = {};
3 nums.forEach(num => {
4 freqMap[num] = (freqMap[num] || 0) + 1;
5 });
6
7 const buckets = Array(nums.length + 1).fill().map(() => []);
8 Object.keys(freqMap).forEach(num => {
9 buckets[freqMap[num]].push(parseInt(num));
10 });
11
12 const result = [];
13 for (let i = buckets.length - 1; i >= 0 && result.length < k; i--) {
14 if (buckets[i].length > 0) {
15 result.push(...buckets[i]);
16 }
17 }
18 return result.slice(0, k);
19}
20
21const nums = [1, 1, 1, 2, 2, 3];
22const k = 2;
23console.log(topKFrequent(nums, k));
24
In JavaScript, elements are counted via a map and ordered into buckets representing frequencies, making it possible to fetch the most frequent.