Skip to content

Commit 2315484

Browse files
committed
Top K Frequent Elements solution
1 parent 78064bb commit 2315484

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
var topKFrequent = function (nums, k) {
2+
let obj = {};
3+
for (const num of nums) {
4+
obj[num] ? obj[num]++ : (obj[num] = 1);
5+
}
6+
let sorted = Object.entries(obj).sort((a, b) => b[1] - a[1]);
7+
let result = [];
8+
for (let i = 0; i < k; i++) {
9+
result.push(sorted[i][0]);
10+
}
11+
return result;
12+
};
13+
14+
// test cases
15+
console.log(topKFrequent([1, 1, 1, 2, 2, 3], 2)); // [1, 2]
16+
console.log(topKFrequent([1], 1)); // [1]
17+
18+
// space - O(n) - mapping the object in [key, freq]
19+
// time - O(nlogn) - sorting the mapped objects in the order of frequency

0 commit comments

Comments
 (0)