Start learning free

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

Letter Count in Go: Counting with map[rune]int

Practice Read the full explanation

Given a string word, return a map that maps each letter of word to the number of times it appears in word.

Every letter of word is a key, and its value is how many times that letter appears. The order of the entries doesn't matter.

 

Example 1:

Input: word = "banana"
Output: {"b": 1, "a": 3, "n": 2}
Explanation: "b" appears once, "a" three times and "n" twice.

Example 2:

Input: word = "hello"
Output: {"h": 1, "e": 1, "l": 2, "o": 1}
Explanation: "l" appears twice; every other letter appears once.

Example 3:

Input: word = "a"
Output: {"a": 1}
Explanation: A single letter appears once.

 

Constraints:

  • word has at least one letter.
  • word is made of lowercase English letters, a to z.
  • Only the letters of word are keys: a letter that doesn't appear has no entry.
STEP 1 OF 5
    Ctrl + Enter to check

    GO · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Letter Count in Go, explained

    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

    1. Create the map. map[rune]int{} is an empty map whose keys are runes and whose values are integers.
    2. Loop over the string. for _, letter := range word visits each character. Ranging over a string produces the position and the character as a rune, Go's type for one Unicode character. The position is not needed, so _ drops it.
    3. Check whether the letter is known. if _, ok := counts[letter]; ok looks 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 _.
    4. Known letter: add 1 to counts[letter].
    5. New letter: in the else branch, set counts[letter] to 1.
    6. Return counts after 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 rune is an integer type, so printing the map for "banana" with fmt.Println shows map[97:3 98:1 110:2]: 97, 98 and 110 are the code points of a, b and n. To show a key as a letter, use string(r) or fmt.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 explicit if and else to make the logic visible.
    • A nil map can't be written to. var counts map[rune]int can be read, but assigning to it panics. Create the map with map[rune]int{} or make.
    • Printing order. fmt prints maps sorted by key, but range over 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, because l appears twice but is one key with the value 2.
    • Using map[string]int with letter. 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" gives map[97:3 98:1 110:2].
    • "hello" gives map[101:1 104:1 108:2 111:1].
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free