Start learning free

LESSON 232 OF 291 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Group Words by First Letter in Kotlin: A Map of Lists

Practice Read the full explanation

Given an array words of lowercase words, group the words by their first letter. Return a HashMap where each key is a first letter, written as a one-character string, and its value is an array of all the words that start with that letter.

Inside each group, keep the words in the order they have in words. The order of the entries in the HashMap doesn't matter.

Example 1:

Input: words = ["apple", "banana", "avocado", "blueberry", "cherry"]
Output: {"a": ["apple", "avocado"], "b": ["banana", "blueberry"], "c": ["cherry"]}
Explanation: "apple" and "avocado" start with "a", "banana" and "blueberry" start with "b", and "cherry" is alone under "c".

Example 2:

Input: words = ["dog", "cat", "deer", "cow", "duck"]
Output: {"d": ["dog", "deer", "duck"], "c": ["cat", "cow"]}
Explanation: "dog" comes before "deer" and "duck" in words, so it comes first in the "d" group too.

Example 3:

Input: words = ["hello"]
Output: {"h": ["hello"]}
Explanation: One word makes one group.

Rules:

  • words has at least one word.
  • Every word has at least one letter and only lowercase letters a-z.
  • A word that appears more than once in words appears as many times in its group.
STEP 1 OF 6
    Ctrl + Enter to check

    KOTLIN · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Group Words By First Letter in Kotlin, explained

    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

    1. Create the map groups with mutableMapOf<String, MutableList<String>>(). The values are MutableLists because words keep being added to them.
    2. Loop over the words.
    3. Take the first letter as a string: word.substring(0, 1) is the slice from index 0 up to, but not including, index 1.
    4. Create the group when it's missing. If !groups.containsKey(first), set groups[first] to a new mutableListOf().
    5. Add the word with groups.getValue(first).add(word).
    6. 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:

    • substring versus word[0]. The keys are strings, and word[0] gives a Char. Slicing gives a String directly. A Char key would also work, but then the map type would be Map<Char, ...> instead.
    • Type inference for the empty list. mutableListOf() has no type argument here. Kotlin infers String from the map's declared value type, MutableList<String>.
    • getValue versus []. groups[first] is a nullable MutableList<String>?, so calling add on it needs !! or ?.. getValue returns the plain list and throws NoSuchElementException when 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, so add changes the map's own list.
    • Return type. The declared type is Map<String, List<String>>. The map being returned has MutableList values, and that is accepted because a Map is read-only in its values' type too: MutableList<String> counts as List<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. getValue would 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 if makes 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]}.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free