Start learning free

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

Letter Count in Swift: Counting with a Dictionary

Practice Read the full explanation

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

    SWIFT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Letter Count in Swift, explained

    Problem overview

    The function letterCount receives a string, word, and returns a dictionary that maps each letter to the number of times it appears. Only letters that occur become keys, and the order of the entries doesn't matter.

    For "banana" the result holds three entries: "b" appears once, "a" three times and "n" twice. For "hello", "l" is 2 and every other letter is 1.

    Approach: a counting dictionary

    Counting how often things occur is one of the most common uses of a dictionary. Each distinct item is a key, and its value is the number of times the loop has seen it so far. At the start the dictionary is empty. For every letter, one of two things is true: the letter is already a key, so its count goes up by one, or it is new, so it enters the dictionary with a count of 1.

    The type of the keys is Character, Swift's type for a single character. A for-in loop over a string produces its characters one at a time, so each loop variable is already a Character.

    Step by step

    1. Create counts as an empty [Character: Int] with var, since it changes in the loop.
    2. Loop over the string with for letter in word.
    3. Look up the letter with if let count = counts[letter]. This runs the body only when the letter is already a key, and gives its current count a name. The body stores count + 1.
    4. Handle the first sighting in the else branch, where counts[letter] becomes 1.
    5. Return counts after the loop.

    The solution in Swift

    class Solution {
        func letterCount(_ word: String) -> [Character: Int] {
            var counts: [Character: Int] = [:]
            for letter in word {
                if let count = counts[letter] {
                    counts[letter] = count + 1
                } else {
                    counts[letter] = 1
                }
            }
            return counts
        }
    }
    

    Optionals and dictionaries

    The key to this lesson is that a dictionary subscript returns an optional. counts[letter] has the type Int?: it holds the count when the key exists and is nil when it doesn't. A missing key is not an error, which is why a new letter can be detected with if let. The else branch runs exactly when the lookup gave nil.

    Assigning through the subscript does two jobs. counts[letter] = 1 adds the key when it is absent, and counts[letter] = count + 1 replaces the value when it is present. The same assignment syntax covers both.

    Swift also lets you shorten the whole branch with a default: counts[letter, default: 0] += 1 reads 0 for a missing key and then adds one. The lesson spells out both branches so the optional is visible. Reading a missing key without a default gives nil; for example, with a [Character: Int] dictionary that has no "z", counts["z"] is nil and counts["z", default: 0] is 0.

    Edge cases and common mistakes

    • Forcing the lookup with !. counts[letter]! + 1 crashes the program the first time a letter appears, because the value is nil.
    • Printing order. A Swift dictionary doesn't keep insertion order, and the order can change from one run to the next. The lesson's tests compare entries, not the order they print in.
    • A single letter. "a" gives one entry, "a": 1.
    • Letters that don't appear. They get no entry at all, not an entry with 0. Looking one up gives nil.
    • Using String keys. The return type is [Character: Int]. A string key such as "a" in a literal is read as a Character when the dictionary's type says so.

    Testing

    Entries are listed in alphabetical order here for readability.

    • "banana" gives a: 3, b: 1, n: 2.
    • "hello" gives e: 1, h: 1, l: 2, o: 1.
    • "a" gives a: 1.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free