Start learning free

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

Letter Count in Scala: Counting with a Mutable Map

Practice Read the full explanation

Given a string word, return a mutable.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

    SCALA · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Letter Count in Scala, explained

    Problem overview

    The method letterCount receives a string word and returns a scala.collection.mutable.Map[Char, Int]: each letter of the word is a key, and its value is how many times it appears. The order of entries doesn't matter, and letters that don't appear have no entry.

    For "banana" the map has three entries: b maps to 1, a to 3 and n to 2. The keys are Char values (single characters in single quotes, like 'b'), not one-letter strings.

    Approach

    This is a counting dictionary. Start with an empty map and visit each letter once. If the letter is already a key, add 1 to its count. If not, this is its first appearance, so its count starts at 1.

    Step by step

    1. Create the map. val counts = scala.collection.mutable.Map[Char, Int]() is empty and can change.
    2. Loop over the letters. A for loop over a String visits its characters one at a time, each a Char.
    3. Known letter. If counts.contains(letter), set counts(letter) to counts(letter) + 1.
    4. New letter. In the else, set counts(letter) = 1.
    5. Return the map after the loop.

    The solution in Scala

    class Solution {
        def letterCount(word: String): scala.collection.mutable.Map[Char, Int] = {
            val counts = scala.collection.mutable.Map[Char, Int]()
            for (letter <- word) {
                if (counts.contains(letter)) {
                    counts(letter) = counts(letter) + 1
                } else {
                    counts(letter) = 1
                }
            }
            return counts
        }
    }
    
    • Parentheses read and write. counts(letter) reads a value, and counts(letter) = 1 writes one, adding the key if it isn't there. Scala maps use parentheses, not square brackets.
    • A missing key throws. Reading counts('z') when 'z' isn't a key throws a NoSuchElementException with the message key not found: z. That is why the code checks contains first.
    • Safer reads. counts.get('z') returns an Option, which is None for a missing key, and counts.getOrElse('z', 0) gives 0. With it, the loop body could be the single line counts(letter) = counts.getOrElse(letter, 0) + 1. For "aab" it gives a mapped to 2 and b to 1.
    • Printing order. A mutable map's entries print in hash order, not in the order of insertion. letterCount("banana") prints as HashMap(a -> 3, b -> 1, n -> 2). The lesson's tests ignore the order.

    Char keys, not String keys

    Looping over a String gives Char values, and the map type Map[Char, Int] is written to match. A Char is a single character in single quotes, 'a', while "a" is a one-character String. They are different types, so counts("a") on this map doesn't compile: the compiler reports Found: ("a" : String) and Required: Char. Use counts('a'), which reads 1 when the map holds a -> 1.

    The pattern itself, count by key with a first-time branch, appears again and again: counting words, counting numbers, grouping. Once it is familiar, only the key type changes.

    Following the loop

    Here is the map after each letter of "banana". The entry order is the one Scala prints, which is not the order of the letters:

    lettercounts afterwards
    bHashMap(b -> 1)
    aHashMap(a -> 1, b -> 1)
    nHashMap(a -> 1, b -> 1, n -> 1)
    aHashMap(a -> 2, b -> 1, n -> 1)
    nHashMap(a -> 2, b -> 1, n -> 2)
    aHashMap(a -> 3, b -> 1, n -> 2)

    Edge cases and common mistakes

    • Reading before setting. Doing counts(letter) += 1 for a letter that isn't a key yet throws, so the first appearance needs its own branch (or getOrElse).
    • Using an immutable Map. The default Map can't be changed with counts(letter) = 1. The type has to be the mutable one.
    • Single letter. "a" gives one entry, a mapped to 1.
    • Counting only letters that appear. The map has no entries for absent letters, so asking about one needs getOrElse.

    Testing

    • "banana" gives HashMap(a -> 3, b -> 1, n -> 2).
    • "hello" gives HashMap(e -> 1, h -> 1, l -> 2, o -> 1).
    • "a" gives HashMap(a -> 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