Kotlin Program to Find Frequency of Elements
groupingBy with eachCount() to find frequency of elements like this: val freq = list.groupingBy { it }.eachCount().Examples
How to Think About It
Algorithm
Code
fun main() {
val list = listOf(1, 2, 2, 3, 3, 3)
val frequency = list.groupingBy { it }.eachCount()
println(frequency)
}Dry Run
Let's trace the list [1, 2, 2, 3, 3, 3] through the code
Start with list
list = [1, 2, 2, 3, 3, 3]
Group elements and count
groupingBy { it } creates groups by element value
Count each group
eachCount() counts how many times each element appears
Result map
frequency = {1=1, 2=2, 3=3}
| Element | Count |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
Why This Works
Step 1: Grouping elements
The groupingBy function groups elements by their value so we can count them easily.
Step 2: Counting occurrences
The eachCount() function counts how many elements are in each group, giving the frequency.
Step 3: Result as map
The result is a map where keys are elements and values are their counts.
Alternative Approaches
fun main() {
val list = listOf(1, 2, 2, 3, 3, 3)
val freqMap = mutableMapOf<Int, Int>()
for (item in list) {
freqMap[item] = freqMap.getOrDefault(item, 0) + 1
}
println(freqMap)
}fun main() {
val list = listOf(1, 2, 2, 3, 3, 3)
val freq = list.fold(mutableMapOf<Int, Int>()) { acc, i ->
acc[i] = acc.getOrDefault(i, 0) + 1
acc
}
println(freq)
}Complexity: O(n) time, O(n) space
Time Complexity
The program loops through the list once, so time grows linearly with the number of elements.
Space Complexity
A map stores counts for each unique element, so space depends on how many different elements exist.
Which Approach is Fastest?
Using groupingBy with eachCount() is concise and optimized internally, usually faster and clearer than manual counting.
| Approach | Time | Space | Best For |
|---|---|---|---|
| groupingBy + eachCount | O(n) | O(n) | Simple and efficient frequency count |
| Manual mutableMap counting | O(n) | O(n) | Learning how counting works step-by-step |
| fold with mutableMap | O(n) | O(n) | Functional style but less readable |
groupingBy { it }.eachCount() for a clean and efficient frequency count in Kotlin.