Kotlin Program to Find Most Frequent Character
groupingBy and eachCount(), then find the max count with maxByOrNull, like: val mostFrequent = input.groupingBy { it }.eachCount().maxByOrNull { it.value }?.key.Examples
How to Think About It
Algorithm
Code
fun main() {
val input = "kotlin programming"
val frequency = input.groupingBy { it }.eachCount()
val mostFrequent = frequency.maxByOrNull { it.value }?.key
println(mostFrequent)
}Dry Run
Let's trace the input "kotlin programming" through the code
Input string
input = "kotlin programming"
Count characters
frequency = {k=2, o=1, t=1, l=1, i=2, n=2, =1, p=1, r=2, g=2, a=1, m=2}
Find max frequency
maxByOrNull finds 'k' with count 2 (first of the highest)
Output result
mostFrequent = 'k'
| Character | Count |
|---|---|
| k | 2 |
| o | 1 |
| t | 1 |
| l | 1 |
| i | 2 |
| n | 2 |
| 1 | |
| p | 1 |
| r | 2 |
| g | 2 |
| a | 1 |
| m | 2 |
Why This Works
Step 1: Count characters
The groupingBy and eachCount() functions count how many times each character appears.
Step 2: Find max count
The maxByOrNull function finds the character with the highest count.
Step 3: Return result
The program returns the character key with the maximum count as the most frequent character.
Alternative Approaches
fun main() {
val input = "hello"
val countMap = mutableMapOf<Char, Int>()
for (ch in input) {
countMap[ch] = countMap.getOrDefault(ch, 0) + 1
}
val mostFrequent = countMap.maxByOrNull { it.value }?.key
println(mostFrequent)
}fun main() {
val input = "kotlin programming"
val mostFrequent = input.asSequence()
.groupingBy { it }
.eachCount()
.maxByOrNull { it.value }
?.key
println(mostFrequent)
}Complexity: O(n) time, O(k) space
Time Complexity
Counting characters requires one pass through the string, so it is O(n), where n is the string length.
Space Complexity
The map stores counts for each unique character, so space is O(k), where k is the number of unique characters.
Which Approach is Fastest?
Using groupingBy with eachCount() is concise and efficient; manual counting is similar but more verbose.
| Approach | Time | Space | Best For |
|---|---|---|---|
| groupingBy + eachCount | O(n) | O(k) | Concise and readable for most cases |
| Manual map counting | O(n) | O(k) | Clear for beginners, more control |
| Sequences | O(n) | O(k) | Large strings with lazy processing |
groupingBy and eachCount() to count characters easily in Kotlin.