Problem overview
The method groupByFirstLetter receives an Array[String] of lowercase words and returns a mutable.Map[String, mutable.ArrayBuffer[String]]. Each key is a first letter, written as a one-character string, and its value holds all the words that start with that letter, in the order they have in words. The order of the map's entries doesn't matter. A word that appears twice appears twice in its group.
For Array("apple", "banana", "avocado", "blueberry", "cherry") the result has three groups: a holds apple and avocado, b holds banana and blueberry, and c holds cherry.
Approach
This is the counting-dictionary pattern with a buffer in place of a number. Visit each word once. Work out its first letter. If the map has no group for that letter yet, create an empty one. Then append the word to the group. Because words are visited in order and appended at the end, each group keeps the order of words.
Step by step
- Create the map.
mutable.Map[String, mutable.ArrayBuffer[String]]()in avalnamedgroups. The values are buffers because words keep being added to them. - Loop over the words with
for (word <- words). - Take the first letter.
word.substring(0, 1)is the text from index 0 up to, but not including, index 1: a one-characterString. Store it infirst. - Create a missing group. If
!groups.contains(first), setgroups(first)to a new emptymutable.ArrayBuffer[String](). - Append the word.
groups(first) += wordadds it to the end of that group. - Return
groups.
The solution in Scala
class Solution {
def groupByFirstLetter(words: Array[String]): mutable.Map[String, mutable.ArrayBuffer[String]] = {
val groups = mutable.Map[String, mutable.ArrayBuffer[String]]()
for (word <- words) {
val first = word.substring(0, 1)
if (!groups.contains(first)) {
groups(first) = mutable.ArrayBuffer[String]()
}
groups(first) += word
}
return groups
}
}
substringversuscharAt."dog".charAt(0)gives theChar'd', while"dog".substring(0, 1)gives theString"d". The map's keys are strings, sosubstringmatches the type.- Buffers are shared, not copied.
groups(first)returns the buffer stored in the map, not a copy of it, so+=changes the buffer that lives inside the map. There's no need to put it back. - The
!operator.!groups.contains(first)is true when the key is absent. The new empty buffer is created once per letter, on its first word. - The import. The lesson's file already imports
scala.collection.mutable. In a file of your own, addimport scala.collection.mutable. - A shorter form.
groups.getOrElseUpdate(word.substring(0, 1), mutable.ArrayBuffer[String]()) += wordfinds the group or creates it in one call. ForArray("dog", "cat", "deer")it buildsHashMap(c -> ArrayBuffer(cat), d -> ArrayBuffer(dog, deer)).
Following the loop
Real output for Array("dog", "cat", "deer", "cow", "duck"):
HashMap(c -> ArrayBuffer(cat, cow), d -> ArrayBuffer(dog, deer, duck))
The map's printed order is not the order of first appearance (the first word was "dog"), which doesn't matter for the lesson, but the order inside each group does: "dog" comes before "deer" and "duck" because it comes before them in words.
Edge cases and common mistakes
- One word.
Array("hello")givesHashMap(h -> ArrayBuffer(hello)). - Skipping the group creation. Without the
if,groups(first)throws aNoSuchElementExceptionthe first time a letter appears. - Recreating the group every time. Setting
groups(first)to a new buffer on every word, outside anif, throws away the earlier words. - Using
charAt(0)as the key. AChardoesn't matchStringkeys, so the code wouldn't compile against this signature. - Empty words.
"".substring(0, 1)throws aStringIndexOutOfBoundsException. The lesson promises every word has at least one letter.
Testing
Array("apple", "banana", "avocado", "blueberry", "cherry")givesHashMap(a -> ArrayBuffer(apple, avocado), b -> ArrayBuffer(banana, blueberry), c -> ArrayBuffer(cherry)).Array("dog", "cat", "deer", "cow", "duck")givesHashMap(c -> ArrayBuffer(cat, cow), d -> ArrayBuffer(dog, deer, duck)).Array("hello")givesHashMap(h -> ArrayBuffer(hello)).
