Skip to content

Commit 1a5f3fd

Browse files
Create Top K Frequent Words.md
1 parent a41ca7e commit 1a5f3fd

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

JS-Algo/Top K Frequent Words.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#### Given an array of strings `words` and an integer `k`, return the `k` most frequent strings.
2+
3+
Return the answer **sorted** by **the frequency** from highest to lowest. Sort the words with the same frequency by their **lexicographical order.**
4+
5+
<img width="482" alt="Screen Shot 2021-11-07 at 11 40 52 PM" src="https://user-images.githubusercontent.com/37787994/140695569-19b04861-cb4a-484c-bcf5-0ee9961e77cb.png">
6+
7+
```JS
8+
/**
9+
* @param {string[]} words
10+
* @param {number} k
11+
* @return {string[]}
12+
*/
13+
// O(n log n)
14+
var topKFrequent = function(words, k) {
15+
const map = {};
16+
for(let word of words) {
17+
map[word] = map[word] + 1 || 1;
18+
}
19+
let res = Object.keys(map).sort((a, b) => {
20+
let diff = map[b] - map[a];
21+
if(diff === 0) {
22+
/*
23+
sorting descend in an alphabetic order. i.e. a -> b -> c -> d
24+
localeCompare() returns one of 3 numbers indicating the sort order.
25+
-1 if sorted before
26+
1 if sorted after
27+
0 if equal
28+
*/
29+
return a.localeCompare(b);
30+
}
31+
else {
32+
return diff;
33+
}
34+
})
35+
return res.slice(0, k);
36+
};
37+
```

0 commit comments

Comments
 (0)