Last active
April 16, 2024 13:31
-
-
Save yevmoroz/8b9944abc4967957024f308ad34492ee to your computer and use it in GitHub Desktop.
leetcode frequent words
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function topKFrequentWords(words, k) { | |
const freq = new Map(); | |
for (const word of words) { | |
if (!freq.has(word)) { | |
freq.set(word, 1); | |
} else { | |
freq.set(word, freq.get(word) + 1); | |
} | |
} | |
const sorted = [...freq.entries()].sort((a, b) => b[1] !== a[1] ? b[1] - a[1] : a[0].localeCompare(b[0])); | |
const result = []; | |
for (let i = 0; i < k; i++) { | |
result.push(sorted[i][0]) | |
} | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment