Problem overview
The function letterCount takes a string, word, and returns a map from each letter to the number of times it appears. Only letters that occur are keys, and the order of entries doesn't matter. For "banana" the answer holds three entries: b once, a three times and n twice.
The word has at least one letter and contains only lowercase letters a to z.
Approach: a counting dictionary
A map is the natural tool for counting. Each distinct letter is a key and its value is how many times it has been seen so far. Walk through the word once. For every letter, either it is already a key, and its count goes up by one, or it is new, and it starts at 1. After the last letter, the map holds the final counts.
Step by step
- Create the map.
map[rune]int{}is an empty map whose keys are runes and whose values are integers. - Loop over the string.
for _, letter := range wordvisits each character. Ranging over a string produces the position and the character as arune, Go's type for one Unicode character. The position is not needed, so_drops it. - Check whether the letter is known.
if _, ok := counts[letter]; oklooks the letter up. The two-value lookup returns the stored value and a boolean,ok, that is true only when the key exists. The value isn't needed here, so it goes to_. - Known letter: add 1 to
counts[letter]. - New letter: in the
elsebranch, setcounts[letter]to 1. - Return
countsafter the loop.
The solution in Go
func letterCount(word string) map[rune]int {
counts := map[rune]int{}
for _, letter := range word {
if _, ok := counts[letter]; ok {
counts[letter] += 1
} else {
counts[letter] = 1
}
}
return counts
}
Go details worth knowing
- Runes print as numbers. A
runeis an integer type, so printing the map for"banana"withfmt.Printlnshowsmap[97:3 98:1 110:2]: 97, 98 and 110 are the code points ofa,bandn. To show a key as a letter, usestring(r)orfmt.Printf("%c", r). - Looking up with a character literal. A rune literal such as
'a'is written with single quotes. For the map of"banana",counts['a']is 3. - Missing keys read as zero.
counts['z']gives 0 for"banana", with no error, and doesn't add an entry. That is why the two-value lookup is needed when you must tell "absent" from "present with value 0". For plain counting,counts[letter]++alone gives the same result, because an absent key starts at 0. The lesson's steps use the explicitifandelseto make the logic visible. - A nil map can't be written to.
var counts map[rune]intcan be read, but assigning to it panics. Create the map withmap[rune]int{}ormake. - Printing order.
fmtprints maps sorted by key, butrangeover a map visits entries in random order. Don't rely on the order in your own loops.
Edge cases and common mistakes
- A one-letter word.
"a"gives a single entry with the value 1. - Repeated letters share one key.
"hello"has four keys, becauselappears twice but is one key with the value 2. - Using
map[string]intwithletter. The loop variable is a rune, so using it as a key of a string-keyed map doesn't compile. Match the key type to what the loop gives you. - Forgetting the
else. Without it, a new letter would never be added, and every count would stay absent.
Testing
These inputs give the counts below; keys are shown as code points, as fmt.Println prints them.
"banana"givesmap[97:3 98:1 110:2]."hello"givesmap[101:1 104:1 108:2 111:1].
