Created
April 18, 2022 02:48
-
-
Save Turskyi/ab9ef69232abd94c9087d400d7e7ae60 to your computer and use it in GitHub Desktop.
Given a list of words, return the top k frequently occurring 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
/* | |
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