Start learning free

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

Letter Count in Kotlin: Counting with a MutableMap

Practice Read the full explanation

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

    KOTLIN · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Letter Count in Kotlin, explained

    Problem overview

    The function letterCount receives a string, word, and returns a map from each letter to the number of times it appears. For "banana" the map holds b with 1, a with 3 and n with 2. A letter that isn't in the word has no entry, and the order of the entries doesn't matter.

    Approach: a counting dictionary

    A map stores key-value pairs, and counting is one of its classic uses. Each letter is a key, and its value is how many times the loop has seen that letter so far. The loop visits every letter once. A letter seen before gets its count raised by one, and a letter seen for the first time starts at 1.

    Step by step

    1. Create the map. mutableMapOf<Char, Int>() is empty and can change. The type arguments say that keys are Char and values are Int. Store it in a val: the name stays tied to this map while its entries 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.containsKey(letter), set counts[letter] to its current value plus 1.
    4. New letter. In the else branch, set counts[letter] = 1.
    5. Return the map after the loop.

    The solution in Kotlin

    class Solution {
        fun letterCount(word: String): MutableMap<Char, Int> {
            val counts = mutableMapOf<Char, Int>()
            for (letter in word) {
                if (counts.containsKey(letter)) {
                    counts[letter] = counts[letter]!! + 1
                } else {
                    counts[letter] = 1
                }
            }
            return counts
        }
    }
    

    Kotlin details worth knowing:

    • Assigning with brackets. counts[letter] = 1 adds the key when it's missing and replaces the value when it exists. Both branches use the same syntax.
    • Why !!. counts[letter] has the type Int?, because a missing key gives null. Adding 1 to a nullable value doesn't compile. !! says "this isn't null", and it is safe here because containsKey just confirmed the key. If the value were null, !! would throw an exception.
    • A shorter form. counts[letter] = (counts[letter] ?: 0) + 1 replaces the whole if and else: the Elvis operator ?: supplies 0 when the key is missing. counts.getOrDefault(letter, 0) + 1 works too.
    • Keys are Char, not String. A character literal uses single quotes. With the map above, counts['b'] is 1 and counts['z'] is null. Asking for counts["b"] with a string key doesn't compile:
    error: type inference failed. The value of the type parameter 'K' must be mentioned in input types (argument types, receiver type, or expected type). Try to specify it explicitly.
    • Printing and order. mutableMapOf keeps entries in insertion order, so println shows the letters in the order they first appeared. The lesson doesn't depend on that order.

    Tracing the loop

    For "banana", the map after each letter is:

    b -> {b=1}
    a -> {b=1, a=1}
    n -> {b=1, a=1, n=1}
    a -> {b=1, a=2, n=1}
    n -> {b=1, a=2, n=2}
    a -> {b=1, a=3, n=2}

    The first three letters are new, so each goes through the else branch. The last three are repeats and go through the if branch. The same two-branch pattern, check, then increase or start at one, counts anything: words, numbers or any other keys.

    Edge cases and common mistakes

    • One letter. "a" gives a map with one entry, a with 1.
    • Forgetting the else. Without it, a letter's first appearance is never recorded, so no letter would get a count.
    • Creating the map inside the loop. Each pass would start from an empty map and discard the earlier counts.
    • Counting every letter of the alphabet. Only the letters in the word are keys.

    Testing

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