Start learning free

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

Group Words by First Letter in Go: map[string][]string

Practice Read the full explanation

Given an array words of lowercase words, group the words by their first letter. Return a 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 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 5
    Ctrl + Enter to check

    GO · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Group Words By First Letter in Go, explained

    Problem overview

    The function groupByFirstLetter takes a slice of lowercase words and returns a map[string][]string. Each key is a first letter, written as a one-character string, and its value is the slice of all words that start with that letter, in the order they have in words. Duplicates stay as many times as they appear.

    For ["dog", "cat", "deer", "cow", "duck"] the result is map[c:[cat cow] d:[dog deer duck]]. "dog" comes before "deer" and "duck" in the input, so it comes first in the d group.

    Approach: a map of slices

    Each word belongs to exactly one group, so one pass over words is enough. For every word, work out its first letter, then add the word to the end of that letter's slice. Since words are visited in input order and always added at the end, each group keeps the input order.

    The one apparent problem is the first word for a letter: its group doesn't exist yet. Go solves this for free, as described below.

    Step by step

    1. Create groups, an empty map[string][]string{}: string keys, slices of strings as values.
    2. Loop over the words with for _, word := range words.
    3. Take the first letter with first := word[0:1], a slice of the string from position 0 up to, but not including, position 1.
    4. Append to the group. groups[first] = append(groups[first], word) reads the current group, adds the word, and stores the longer slice back under the same key.
    5. Return groups.

    Tracing the example

    For ["dog", "cat", "deer", "cow", "duck"], the map after each word is:

    wordgroups afterwards
    dogmap[d:[dog]]
    catmap[c:[cat] d:[dog]]
    deermap[c:[cat] d:[dog deer]]
    cowmap[c:[cat cow] d:[dog deer]]
    duckmap[c:[cat cow] d:[dog deer duck]]

    "dog" and "cat" each start a new group. The later words extend a group that already exists, always at the end.

    The solution in Go

    func groupByFirstLetter(words []string) map[string][]string {
        groups := map[string][]string{}
        for _, word := range words {
            first := word[0:1]
            groups[first] = append(groups[first], word)
        }
        return groups
    }
    

    Go details worth knowing

    • Why word[0:1] and not word[0]. Indexing a string gives a byte, a number: "go"[0] is 103. Slicing gives a string: "go"[0:1] is "g". The map's keys are strings, so the slice is what fits. For lowercase a-z, one byte is one letter.
    • Missing keys give the zero value. Reading groups[first] for a letter not yet in the map gives a nil slice, and append on a nil slice works: it creates a new slice. So the first word for a letter needs no special case.
    • Store the result back. append may return a slice with a new backing array, so groups[first] has to be assigned. Calling append(groups[first], word) alone changes nothing and doesn't compile.
    • Order of keys. fmt.Println prints a map sorted by key, while ranging over it visits the keys in random order. Only the order inside each slice is guaranteed here.

    Edge cases and common mistakes

    • One word. ["hello"] gives map[h:[hello]].
    • Duplicates. ["hi", "hi", "ho"] gives map[h:[hi hi ho]]: each occurrence is added.
    • Using word[0] as the key gives a byte, and the code doesn't compile with map[string][]string.
    • Empty words. word[0:1] on an empty string panics. The lesson guarantees every word has at least one letter; in your own code, check len(word) first.
    • Sorting the result is not needed and would break the input order inside the groups.

    Testing

    • ["apple", "banana", "avocado", "blueberry", "cherry"] gives map[a:[apple avocado] b:[banana blueberry] c:[cherry]].
    • ["dog", "cat", "deer", "cow", "duck"] gives map[c:[cat cow] d:[dog deer duck]].
    • ["hello"] gives map[h:[hello]].
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free