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
- Split the sentence.
sentence.split(" ")cuts it at every space and returns aList<String>. Store it inwords. - Create the counting map with
mutableMapOf<String, Int>(): empty to begin with, words as keys and counts as values. - Loop over the words with
for (word in words). - Seen before. If
counts.containsKey(word), setcounts[word]tocounts[word]!! + 1. - First time. In the
else, setcounts[word] = 1. - 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:
splittakes 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 typeInt?, since a missing key givesnull. The!!turns it into a plainIntand is safe becausecontainsKeywas checked first. - The same job in one line.
counts[word] = (counts[word] ?: 0) + 1does both branches at once:?:uses 0 when the key is missing. - The lesson's map type. The function returns a
MutableMap<String, Int>.HashMapin the statement is the Java name for the same kind of structure;mutableMapOfbuilds aLinkedHashMap, 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] = 1unconditionally 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.
