Created
February 10, 2021 19:25
-
-
Save cesardeazevedo/0f51c45ffe596f61555ecb1f3251074e to your computer and use it in GitHub Desktop.
Top K Frequent Words
This file contains hidden or 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
const groupByFrequency = (acc, x) => ({ ...acc, [x]: (acc[x] || 0) + 1 }) | |
const sortFrequency = (a, b) => ( | |
b[1] === a[1] | |
? (b[0] < a[0] ? 1 : -1) // Sort same frequent words alphabetical | |
: (b[1] > a[1] ? 1 : -1) // Sort frequency from highest to lowest | |
) | |
function topKFrequent(words: string[], k: number): string[] { | |
return Object.entries(words.reduce(groupByFrequency, {})) | |
.sort(sortFrequency) | |
.map(x => x[0]) | |
.slice(0, k) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment