Practice Real Company Assessment Patterns • Latest 2025–2026 Mock Tests

Programming Exercises

Write a function to find the top k frequent elements in an array.

Hard

Problem 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)}") }
Log in or sign up to run or submit your code.Log inSign up
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]