Problem overview
The function groupByFirstLetter receives an array of lowercase words and returns a map. Each key is a first letter, written as a one-character string, and its value is the list of words that start with it, in the order they have in words. For ["apple", "banana", "avocado", "blueberry", "cherry"] the result is {a=[apple, avocado], b=[banana, blueberry], c=[cherry]}. The order of the entries doesn't matter.
Approach: find the group, create it if needed
Each word belongs to exactly one group, so one pass is enough. For every word, take its first letter. If no group exists for that letter yet, create an empty one. Then add the word to its group. Words arrive in the order of words and are appended at the end, so every group keeps that order.
Step by step
- Create the map
groupswithmutableMapOf<String, MutableList<String>>(). The values areMutableLists because words keep being added to them. - Loop over the words.
- Take the first letter as a string:
word.substring(0, 1)is the slice from index 0 up to, but not including, index 1. - Create the group when it's missing. If
!groups.containsKey(first), setgroups[first]to a newmutableListOf(). - Add the word with
groups.getValue(first).add(word). - Return
groups.
The solution in Kotlin
class Solution {
fun groupByFirstLetter(words: Array<String>): Map<String, List<String>> {
val groups = mutableMapOf<String, MutableList<String>>()
for (word in words) {
val first = word.substring(0, 1)
if (!groups.containsKey(first)) {
groups[first] = mutableListOf()
}
groups.getValue(first).add(word)
}
return groups
}
}
Kotlin details worth knowing:
substringversusword[0]. The keys are strings, andword[0]gives aChar. Slicing gives aStringdirectly. ACharkey would also work, but then the map type would beMap<Char, ...>instead.- Type inference for the empty list.
mutableListOf()has no type argument here. Kotlin infersStringfrom the map's declared value type,MutableList<String>. getValueversus[].groups[first]is a nullableMutableList<String>?, so callingaddon it needs!!or?..getValuereturns the plain list and throwsNoSuchElementExceptionwhen the key is missing, which can't happen right after the check.- Lists are shared, not copied.
getValue(first)returns the list stored in the map, soaddchanges the map's own list. - Return type. The declared type is
Map<String, List<String>>. The map being returned hasMutableListvalues, and that is accepted because aMapis read-only in its values' type too:MutableList<String>counts asList<String>. - Shorter forms.
groups.getOrPut(first) { mutableListOf() }.add(word)does the check and the creation in one call.words.groupBy { it.substring(0, 1) }does the whole job.
Tracing the loop
For ["apple", "banana", "avocado", "blueberry", "cherry"], the map after each word is:
apple -> {a=[apple]}
banana -> {a=[apple], b=[banana]}
avocado -> {a=[apple, avocado], b=[banana]}
blueberry -> {a=[apple, avocado], b=[banana, blueberry]}
cherry -> {a=[apple, avocado], b=[banana, blueberry], c=[cherry]}
apple, banana and cherry each start a group. avocado and blueberry find theirs already there and are appended to its end, which is why each group keeps the order of words.
Edge cases and common mistakes
- One word.
["hello"]gives{h=[hello]}. - Repeated words.
["to", "to", "tea"]gives{t=[to, to, tea]}. Nothing is removed. - Forgetting to create the group.
getValuewould then throw for the first word of each letter. - Replacing the group every time. If the creation step ran for every word, each new word would wipe the group of its letter. The
ifmakes it run once per letter.
Reading the result
Once the map is built, groups["a"] gives the list of words starting with a, or null when there is none. The key is a one-character string, so groups["a"] works and groups['a'] does not, because a Char can't be a key of a Map<String, ...>.
Testing
["apple", "banana", "avocado", "blueberry", "cherry"]gives{a=[apple, avocado], b=[banana, blueberry], c=[cherry]}.["dog", "cat", "deer", "cow", "duck"]gives{d=[dog, deer, duck], c=[cat, cow]}.["hello"]gives{h=[hello]}.["to", "to", "tea"]gives{t=[to, to, tea]}.
