Problem overview
The method wordFrequency receives a sentence: lowercase words separated by single spaces, at least one word. It returns a scala.collection.mutable.Map[String, Int] in which every word is a key and the value is how many times it appears. The order of the entries doesn't matter.
For "the cat and the hat" the map has four entries: the maps to 2, and cat, and and hat map to 1. For "go go go" there is a single key, go, with the value 3.
Approach
There are two jobs: cut the sentence into words, then count them. Because the words are separated by exactly one space, splitting at every space gives the words directly. Counting uses the standard counting-dictionary pattern: for each word, add 1 to its entry if it has one, and create the entry with the value 1 if it doesn't.
Step by step
- Split the sentence.
sentence.split(" ")returns anArray[String]with one element per word. Store it inwords. - Create the map.
scala.collection.mutable.Map[String, Int](), stored in avalnamedcounts. It has to be mutable because entries are added and changed. - Loop over the words with
for (word <- words). - Seen before. If
counts.contains(word), runcounts(word) += 1. - First time. Otherwise
counts(word) = 1. - Return the map.
The solution in Scala
class Solution {
def wordFrequency(sentence: String): scala.collection.mutable.Map[String, Int] = {
val words = sentence.split(" ")
val counts = scala.collection.mutable.Map[String, Int]()
for (word <- words) {
if (counts.contains(word)) {
counts(word) += 1
} else {
counts(word) = 1
}
}
return counts
}
}
split(" ")on a string. It returns an array."the cat and the hat".split(" ").toListisList(the, cat, and, the, hat).counts(word) += 1. Scala rewrites this ascounts(word) = counts(word) + 1: it reads the value, adds 1 and writes it back. It only works when the key already exists, which is why thecontainscheck comes first.- Missing keys throw. Reading
counts("zebra")for an absent key throws aNoSuchElementException.counts.get("zebra")returnsNoneinstead, andcounts.getOrElse("zebra", 0)returns 0. - Printing. A mutable map prints in hash order, so
wordFrequency("the cat and the hat")shows asHashMap(the -> 2, and -> 1, cat -> 1, hat -> 1). Entries aren't kept in sentence order.
Why a map
A map answers "what is the count for this word?" directly, by key, without scanning anything. The alternative, keeping two parallel arrays of words and counts, would need a search through the words for every word in the sentence. The map does the lookup by hashing the key, which is why the same loop works on a sentence of ten words or ten thousand.
Because the keys are strings, two words are the same key exactly when their characters are equal: Scala's == and a map's key lookup compare string contents, not references. The words here are lowercase, so "The" and "the" never meet.
Edge cases and common mistakes
- One word.
"hello"splits into a one-element array and givesHashMap(hello -> 1). - Repeated word.
"go go go"givesHashMap(go -> 3): one key, not three. - Double spaces. The lesson promises single spaces. If a sentence had two in a row,
split(" ")would produce an empty string between them:"a b".split(" ").toListisList(a, , b), and the empty string would be counted as a word. - Forgetting the
else. Without the first-time branch, a new word is never added, and nothing is counted. - Immutable map. The default
Maphas nocounts(word) = 1. Use thescala.collection.mutableone.
Testing
"the cat and the hat"givesHashMap(the -> 2, and -> 1, cat -> 1, hat -> 1)."go go go"givesHashMap(go -> 3)."hello"givesHashMap(hello -> 1).
