Skip to content

Instantly share code, notes, and snippets.

@cesardeazevedo
Created February 10, 2021 19:25
Show Gist options
  • Save cesardeazevedo/0f51c45ffe596f61555ecb1f3251074e to your computer and use it in GitHub Desktop.
Save cesardeazevedo/0f51c45ffe596f61555ecb1f3251074e to your computer and use it in GitHub Desktop.
Top K Frequent Words
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