Skip to content

Commit fc077de

Browse files
authored
Add optimized solution with O(n)
The changes include a new solution that does the job in O(n) as described in the video without sorting the frequency array taking O(logN)
1 parent 6c3cd43 commit fc077de

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

Diff for: javascript/0347-top-k-frequent-elements.js

+42-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/**
2-
* Set - Frequency Counter
2+
* Set - Frequency Counter | Using sort
33
* Time O(NlogN) | Space O(N)
44
* https://leetcode.com/problems/top-k-frequent-elements/
55
* @param {number[]} nums
@@ -22,3 +22,44 @@ var topKFrequent = function(nums, k) {
2222
}
2323
return output;
2424
};
25+
26+
/**
27+
* Without Sort
28+
* Time O(N) | Space O(k)
29+
* https://leetcode.com/problems/top-k-frequent-elements/
30+
* @param {number[]} nums
31+
* @param {number} k
32+
* @return {number[]}
33+
*/
34+
35+
var topKFrequent = function(nums, k) {
36+
const mp = new Map();
37+
const arr = new Array(nums.length + 1).fill(0);
38+
const ans = [];
39+
40+
nums.forEach(el => {
41+
const val = mp.get(el) || 0;
42+
mp.set(el, val + 1);
43+
});
44+
45+
for ( let [key, value] of mp ) {
46+
const prev = arr[value] || [];
47+
prev.push(key);
48+
arr[value] = prev;
49+
}
50+
51+
52+
arr.reverse();
53+
for (let el of arr) {
54+
if (k < 1) break;
55+
if (el) {
56+
for (let el2 of el) {
57+
if (k < 1) break;
58+
ans.push(el2);
59+
k--;
60+
}
61+
}
62+
}
63+
64+
return ans;
65+
};

0 commit comments

Comments
 (0)