Start learning free

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

Word Frequency in Scala: split and a Mutable Map

Practice Read the full explanation

Given a string sentence, count how many times each word appears in it. Return a mutable.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

    SCALA · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Word Frequency in Scala, explained

    Problem overview

    The method wordFrequency receives a sentence: lowercase words separated by single spaces, at least one word. It returns a scala.collection.mutable.Map[String, Int] in which every word is a key and the value is how many times it appears. The order of the entries doesn't matter.

    For "the cat and the hat" the map has four entries: the maps to 2, and cat, and and hat map to 1. For "go go go" there is a single key, go, with the value 3.

    Approach

    There are two jobs: cut the sentence into words, then count them. Because the words are separated by exactly one space, splitting at every space gives the words directly. Counting uses the standard counting-dictionary pattern: for each word, add 1 to its entry if it has one, and create the entry with the value 1 if it doesn't.

    Step by step

    1. Split the sentence. sentence.split(" ") returns an Array[String] with one element per word. Store it in words.
    2. Create the map. scala.collection.mutable.Map[String, Int](), stored in a val named counts. It has to be mutable because entries are added and changed.
    3. Loop over the words with for (word <- words).
    4. Seen before. If counts.contains(word), run counts(word) += 1.
    5. First time. Otherwise counts(word) = 1.
    6. Return the map.

    The solution in Scala

    class Solution {
        def wordFrequency(sentence: String): scala.collection.mutable.Map[String, Int] = {
            val words = sentence.split(" ")
            val counts = scala.collection.mutable.Map[String, Int]()
            for (word <- words) {
                if (counts.contains(word)) {
                    counts(word) += 1
                } else {
                    counts(word) = 1
                }
            }
            return counts
        }
    }
    
    • split(" ") on a string. It returns an array. "the cat and the hat".split(" ").toList is List(the, cat, and, the, hat).
    • counts(word) += 1. Scala rewrites this as counts(word) = counts(word) + 1: it reads the value, adds 1 and writes it back. It only works when the key already exists, which is why the contains check comes first.
    • Missing keys throw. Reading counts("zebra") for an absent key throws a NoSuchElementException. counts.get("zebra") returns None instead, and counts.getOrElse("zebra", 0) returns 0.
    • Printing. A mutable map prints in hash order, so wordFrequency("the cat and the hat") shows as HashMap(the -> 2, and -> 1, cat -> 1, hat -> 1). Entries aren't kept in sentence order.

    Why a map

    A map answers "what is the count for this word?" directly, by key, without scanning anything. The alternative, keeping two parallel arrays of words and counts, would need a search through the words for every word in the sentence. The map does the lookup by hashing the key, which is why the same loop works on a sentence of ten words or ten thousand.

    Because the keys are strings, two words are the same key exactly when their characters are equal: Scala's == and a map's key lookup compare string contents, not references. The words here are lowercase, so "The" and "the" never meet.

    Edge cases and common mistakes

    • One word. "hello" splits into a one-element array and gives HashMap(hello -> 1).
    • Repeated word. "go go go" gives HashMap(go -> 3): one key, not three.
    • Double spaces. The lesson promises single spaces. If a sentence had two in a row, split(" ") would produce an empty string between them: "a b".split(" ").toList is List(a, , b), and the empty string would be counted as a word.
    • Forgetting the else. Without the first-time branch, a new word is never added, and nothing is counted.
    • Immutable map. The default Map has no counts(word) = 1. Use the scala.collection.mutable one.

    Testing

    • "the cat and the hat" gives HashMap(the -> 2, and -> 1, cat -> 1, hat -> 1).
    • "go go go" gives HashMap(go -> 3).
    • "hello" gives HashMap(hello -> 1).
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free