Start learning free

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

Word Frequency in Go: strings.Split and a Map

Practice Read the full explanation

Given a string sentence, count how many times each word appears in it. Return a map where each word of the sentence is a key, and its value is the number of times that word appears.

The words are in lower case and separated by single spaces, and the sentence has at least one word. The order of the entries doesn't matter.

Example 1:

Input: sentence = "the cat and the hat"
Output: {"the": 2, "cat": 1, "and": 1, "hat": 1}
Explanation: "the" appears twice. Every other word appears once.

Example 2:

Input: sentence = "go go go"
Output: {"go": 3}
Explanation: The same word three times gives one key, "go", with the value 3.

Example 3:

Input: sentence = "hello"
Output: {"hello": 1}
Explanation: A sentence of one word: that word appears once.
STEP 1 OF 6
    Ctrl + Enter to check

    GO · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Word Frequency in Go, explained

    Problem overview

    The function wordFrequency takes a string, sentence, and returns a map[string]int: each word of the sentence is a key and its value is how many times the word appears. The words are lowercase and separated by single spaces, and there is at least one word. The order of entries doesn't matter.

    For "the cat and the hat" the result is map[and:1 cat:1 hat:1 the:2]: "the" appears twice and every other word once.

    Approach: split, then count

    The problem has two parts. First, turn the sentence into a slice of words. Then count the words with a map, the same way you would count letters: a known word gets +1, a new word starts at 1.

    Step by step

    1. Split the sentence. strings.Split(sentence, " ") cuts the string at every space and returns a []string. Because the words are separated by single spaces, the pieces are exactly the words.
    2. Create the map. map[string]int{} starts empty, since nothing has been counted.
    3. Loop over the words with for _, word := range words.
    4. Known word. if _, ok := counts[word]; ok is true when the word is already a key. Then add 1 to its count.
    5. New word. In the else branch, set counts[word] to 1.
    6. Return counts after the loop.

    Tracing the example

    Reading "the cat and the hat" one word at a time, the map changes like this:

    word readcounts afterwards
    themap[the:1]
    catmap[cat:1 the:1]
    andmap[and:1 cat:1 the:1]
    themap[and:1 cat:1 the:2]
    hatmap[and:1 cat:1 hat:1 the:2]

    The second "the" finds its key already present, so the count rises from 1 to 2 instead of a new key appearing. The table prints each map sorted by key, which is how fmt.Println shows maps.

    The solution in Go

    func wordFrequency(sentence string) map[string]int {
        words := strings.Split(sentence, " ")
        counts := map[string]int{}
        for _, word := range words {
            if _, ok := counts[word]; ok {
                counts[word] += 1
            } else {
                counts[word] = 1
            }
        }
        return counts
    }
    

    Go details worth knowing

    • The strings package. strings.Split lives in the standard library's strings package. The lesson's editor already has it available. In a program of your own, put import "strings" at the top of the file.
    • Single spaces only. strings.Split with " " makes an empty string for every extra space: splitting "a b" (two spaces) gives three pieces, with an empty one in the middle. This lesson promises single spaces, so that doesn't happen here. For messier text, strings.Fields splits on any run of white space and drops the empty pieces.
    • The two-value lookup. v, ok := m[k] gives the value and whether the key exists. Declaring it in the if header limits ok to the if and its else.
    • Shorter form. counts[word]++ does the same job in one line, since a missing key reads as 0. The explicit branches show what is happening.
    • Order. fmt.Println prints a map sorted by key, but a range over the map visits entries in random order.

    Edge cases and common mistakes

    • A repeated word gives one key. "go go go" returns map[go:3].
    • One word. "hello" returns map[hello:1].
    • Splitting on the wrong separator. Splitting on "" cuts the string into characters, not words, so the counts would be for letters.
    • Writing to a nil map. var counts map[string]int followed by counts[word] = 1 panics with "assignment to entry in nil map". Create the map with a literal or make.

    Testing

    • "the cat and the hat" gives map[and:1 cat:1 hat:1 the:2].
    • "go go go" gives map[go:3].
    • "hello" gives map[hello: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