Start learning free

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

Group Words by First Letter in Scala: Map of ArrayBuffers

Practice Read the full explanation

Given an array words of lowercase words, group the words by their first letter. Return a mutable.Map 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 mutable.Map 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

    SCALA · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Group Words By First Letter in Scala, explained

    Problem overview

    The method groupByFirstLetter receives an Array[String] of lowercase words and returns a mutable.Map[String, mutable.ArrayBuffer[String]]. Each key is a first letter, written as a one-character string, and its value holds all the words that start with that letter, in the order they have in words. The order of the map's entries doesn't matter. A word that appears twice appears twice in its group.

    For Array("apple", "banana", "avocado", "blueberry", "cherry") the result has three groups: a holds apple and avocado, b holds banana and blueberry, and c holds cherry.

    Approach

    This is the counting-dictionary pattern with a buffer in place of a number. Visit each word once. Work out its first letter. If the map has no group for that letter yet, create an empty one. Then append the word to the group. Because words are visited in order and appended at the end, each group keeps the order of words.

    Step by step

    1. Create the map. mutable.Map[String, mutable.ArrayBuffer[String]]() in a val named groups. The values are buffers because words keep being added to them.
    2. Loop over the words with for (word <- words).
    3. Take the first letter. word.substring(0, 1) is the text from index 0 up to, but not including, index 1: a one-character String. Store it in first.
    4. Create a missing group. If !groups.contains(first), set groups(first) to a new empty mutable.ArrayBuffer[String]().
    5. Append the word. groups(first) += word adds it to the end of that group.
    6. Return groups.

    The solution in Scala

    class Solution {
        def groupByFirstLetter(words: Array[String]): mutable.Map[String, mutable.ArrayBuffer[String]] = {
            val groups = mutable.Map[String, mutable.ArrayBuffer[String]]()
            for (word <- words) {
                val first = word.substring(0, 1)
                if (!groups.contains(first)) {
                    groups(first) = mutable.ArrayBuffer[String]()
                }
                groups(first) += word
            }
            return groups
        }
    }
    
    • substring versus charAt. "dog".charAt(0) gives the Char 'd', while "dog".substring(0, 1) gives the String "d". The map's keys are strings, so substring matches the type.
    • Buffers are shared, not copied. groups(first) returns the buffer stored in the map, not a copy of it, so += changes the buffer that lives inside the map. There's no need to put it back.
    • The ! operator. !groups.contains(first) is true when the key is absent. The new empty buffer is created once per letter, on its first word.
    • The import. The lesson's file already imports scala.collection.mutable. In a file of your own, add import scala.collection.mutable.
    • A shorter form. groups.getOrElseUpdate(word.substring(0, 1), mutable.ArrayBuffer[String]()) += word finds the group or creates it in one call. For Array("dog", "cat", "deer") it builds HashMap(c -> ArrayBuffer(cat), d -> ArrayBuffer(dog, deer)).

    Following the loop

    Real output for Array("dog", "cat", "deer", "cow", "duck"):

    HashMap(c -> ArrayBuffer(cat, cow), d -> ArrayBuffer(dog, deer, duck))
    

    The map's printed order is not the order of first appearance (the first word was "dog"), which doesn't matter for the lesson, but the order inside each group does: "dog" comes before "deer" and "duck" because it comes before them in words.

    Edge cases and common mistakes

    • One word. Array("hello") gives HashMap(h -> ArrayBuffer(hello)).
    • Skipping the group creation. Without the if, groups(first) throws a NoSuchElementException the first time a letter appears.
    • Recreating the group every time. Setting groups(first) to a new buffer on every word, outside an if, throws away the earlier words.
    • Using charAt(0) as the key. A Char doesn't match String keys, so the code wouldn't compile against this signature.
    • Empty words. "".substring(0, 1) throws a StringIndexOutOfBoundsException. The lesson promises every word has at least one letter.

    Testing

    • Array("apple", "banana", "avocado", "blueberry", "cherry") gives HashMap(a -> ArrayBuffer(apple, avocado), b -> ArrayBuffer(banana, blueberry), c -> ArrayBuffer(cherry)).
    • Array("dog", "cat", "deer", "cow", "duck") gives HashMap(c -> ArrayBuffer(cat, cow), d -> ArrayBuffer(dog, deer, duck)).
    • Array("hello") gives HashMap(h -> ArrayBuffer(hello)).
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free