Start learning free

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

Word Frequency in Kotlin: split and a Counting Map

Practice Read the full explanation

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

    KOTLIN · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Word Frequency in Kotlin, explained

    Problem overview

    The function wordFrequency receives a sentence of lowercase words separated by single spaces and returns a map from each word to the number of times it appears. For "the cat and the hat" the map is {the=2, cat=1, and=1, hat=1}. The order of the entries doesn't matter.

    Approach: split, then count

    The problem has two parts. First, cut the sentence into words. Then count them the same way you would count letters: each word is a key, and its value is how many times it has come up. The first time a word appears it gets 1, and every later time its count goes up by one.

    Step by step

    1. Split the sentence. sentence.split(" ") cuts it at every space and returns a List<String>. Store it in words.
    2. Create the counting map with mutableMapOf<String, Int>(): empty to begin with, words as keys and counts as values.
    3. Loop over the words with for (word in words).
    4. Seen before. If counts.containsKey(word), set counts[word] to counts[word]!! + 1.
    5. First time. In the else, set counts[word] = 1.
    6. Return the map.

    The solution in Kotlin

    class Solution {
        fun wordFrequency(sentence: String): MutableMap<String, Int> {
            val words = sentence.split(" ")
            val counts = mutableMapOf<String, Int>()
            for (word in words) {
                if (counts.containsKey(word)) {
                    counts[word] = counts[word]!! + 1
                } else {
                    counts[word] = 1
                }
            }
            return counts
        }
    }
    

    Kotlin details worth knowing:

    • split takes the separator as an argument. "go go go".split(" ") is [go, go, go]. A single word, "hello", gives a list with one item.
    • Nullable lookup. counts[word] has the type Int?, since a missing key gives null. The !! turns it into a plain Int and is safe because containsKey was checked first.
    • The same job in one line. counts[word] = (counts[word] ?: 0) + 1 does both branches at once: ?: uses 0 when the key is missing.
    • The lesson's map type. The function returns a MutableMap<String, Int>. HashMap in the statement is the Java name for the same kind of structure; mutableMapOf builds a LinkedHashMap, which remembers insertion order.

    Tracing the loop

    For "the cat and the hat", the map after each word is:

    the -> {the=1}
    cat -> {the=1, cat=1}
    and -> {the=1, cat=1, and=1}
    the -> {the=2, cat=1, and=1}
    hat -> {the=2, cat=1, and=1, hat=1}

    Only the fourth word finds its key already there, so only that pass takes the if branch. This is the same pattern as counting the letters of a word. Here the keys are strings made by split instead of characters made by a loop over a string.

    Edge cases and common mistakes

    • Repeated word. "go go go" gives {go=3}: one key, and the count goes up twice after the first entry.
    • One word. "hello" gives {hello=1}.
    • Extra spaces. The lesson promises single spaces. Elsewhere, "a b" (two spaces) splits into [a, , b], and the empty string between the spaces becomes a key of its own. split(" ") on an empty string gives [""], so the map is {=1}.
    • Splitting on the wrong thing. Without the " " separator the sentence is not cut into words at all.
    • Resetting the count. Writing counts[word] = 1 unconditionally would leave every count at 1.

    Words and keys

    A map key must be the same value every time the same word shows up, and strings compare by their content in Kotlin, so two separate "the" strings from the split land on the same key. That is why the map ends with one the entry that counted both occurrences, not two entries.

    Testing

    • "the cat and the hat" gives {the=2, cat=1, and=1, hat=1}.
    • "go go go" gives {go=3}.
    • "hello" gives {hello=1}.
    • "a b" gives {a=1, =1, b=1}, which shows why single spaces matter.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free