Skip to content

Instantly share code, notes, and snippets.

@Turskyi
Created April 18, 2022 02:48
Show Gist options
  • Save Turskyi/ab9ef69232abd94c9087d400d7e7ae60 to your computer and use it in GitHub Desktop.
Save Turskyi/ab9ef69232abd94c9087d400d7e7ae60 to your computer and use it in GitHub Desktop.
Given a list of words, return the top k frequently occurring words.
/*
Given an array of strings words and an integer k, return the k most frequent strings.
["i","love","leetcode","i","love","coding"], k = 2
Output: ["i","love"]
* */
fun topKFrequent(words: Array<String>, k: Int): List<String> {
return words.groupingBy { it }.eachCount()
.toList()
.sortedBy { (s, _) -> s }
.sortedByDescending { (_, v) -> v }
.map { it.first }
.take(k)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment