Write a function to find the top k frequent elements in an array.
HardProblem Statement
Write a function to find the top k frequent elements in an array.
Sample Input
A hardcoded array of integers and an integer k, e.g., [1, 1, 1, 2, 2, 3] and k = 2.
Sample Output
Top 2 frequent elements: [1, 2]
Limits
Time: 2s · Memory: 256 MB
Code Editor
00:00
fun topKFrequent(nums: Array<Int>, k: Int): List<Int> {
val frequencyMap = nums.groupingBy { it }.eachCount()
return frequencyMap.entries.sortedByDescending { it.value }.take(k).map { it.key }
}
fun main() {
val nums = arrayOf(1, 1, 1, 2, 2, 3)
val k = 2
println("Top $k frequent elements: ${topKFrequent(nums, k)}")
}
Input
A hardcoded array of integers and an integer k, e.g., [1, 1, 1, 2, 2, 3] and k = 2.
Expected Output
Top 2 frequent elements: [1, 2]