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
- Create
groups, an emptymap[string][]string{}: string keys, slices of strings as values. - Loop over the words with
for _, word := range words. - Take the first letter with
first := word[0:1], a slice of the string from position 0 up to, but not including, position 1. - 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. - Return
groups.
Tracing the example
For ["dog", "cat", "deer", "cow", "duck"], the map after each word is:
| word | groups afterwards |
|---|---|
| dog | map[d:[dog]] |
| cat | map[c:[cat] d:[dog]] |
| deer | map[c:[cat] d:[dog deer]] |
| cow | map[c:[cat cow] d:[dog deer]] |
| duck | map[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 notword[0]. Indexing a string gives abyte, 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 anilslice, andappendon a nil slice works: it creates a new slice. So the first word for a letter needs no special case. - Store the result back.
appendmay return a slice with a new backing array, sogroups[first]has to be assigned. Callingappend(groups[first], word)alone changes nothing and doesn't compile. - Order of keys.
fmt.Printlnprints 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"]givesmap[h:[hello]]. - Duplicates.
["hi", "hi", "ho"]givesmap[h:[hi hi ho]]: each occurrence is added. - Using
word[0]as the key gives abyte, and the code doesn't compile withmap[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, checklen(word)first. - Sorting the result is not needed and would break the input order inside the groups.
Testing
["apple", "banana", "avocado", "blueberry", "cherry"]givesmap[a:[apple avocado] b:[banana blueberry] c:[cherry]].["dog", "cat", "deer", "cow", "duck"]givesmap[c:[cat cow] d:[dog deer duck]].["hello"]givesmap[h:[hello]].
