Problem overview
The method groupByFirstLetter receives an array of lowercase words and returns a HashMap<String, List<String>>. Each key is a first letter, written as a one-character string, and its value is the list of all words that start with that letter, in the order they have in words.
For ["apple", "banana", "avocado", "blueberry", "cherry"] the result is {a=[apple, avocado], b=[banana, blueberry], c=[cherry]}. For ["dog", "cat", "deer", "cow", "duck"] it is {c=[cat, cow], d=[dog, deer, duck]}: "dog" comes before "deer" and "duck" in the input, so it comes first in its group too. One word, ["hello"], makes one group, {h=[hello]}. A word that appears twice appears twice in its group, and the order of the entries in the map doesn't matter.
Approach: a map whose values are lists
This is a counting loop in which the value is a list instead of a number. For each word, find the group of its first letter and append the word to it. The first word with a new letter has no group yet, so the group must be created before it is used. After that, the loop is a single pass: each word belongs to exactly one group.
The order inside a group needs no extra work. The loop meets the words in their original order, and add appends at the end of a list, so each group keeps the input order.
Step by step
- Create the map.
HashMap<String, List<String>> groups = new HashMap<>();maps a one-letterStringto aListof words. - Loop over the words with
for (String word : words). - Take the first letter with
word.substring(0, 1), the characters from index 0 up to, but not including, index 1. The keys are strings, so slicing is simpler thancharAt(0), which gives achar. - Create the group if it's missing. If
!groups.containsKey(first), put a new emptyArrayListunderfirst. A later word with the same letter finds the list already there. - Add the word.
groups.get(first)returns the list stored in the map, not a copy, so callingaddon it changes the list inside the map. - Return
groupsafter the loop.
The solution in Java
class Solution {
public HashMap<String, List<String>> groupByFirstLetter(String[] words) {
HashMap<String, List<String>> groups = new HashMap<>();
for (String word : words) {
String first = word.substring(0, 1);
if (!groups.containsKey(first)) {
groups.put(first, new ArrayList<>());
}
groups.get(first).add(word);
}
return groups;
}
}
Java details worth knowing:
new ArrayList<>()insideput. The empty diamond is filled in from the map's declared value type,List<String>, so the compiler knows it is anArrayList<String>. The map's declared type is the interfaceList, which is why any list implementation fits.getwithout the check. For a missing key,getreturnsnull. Callingaddon it would throw aNullPointerException, which is why the group is created first.- Lists are references. The map holds a reference to each list. Because
getreturns that same reference, noputis needed afteradd. - Shorter forms.
groups.computeIfAbsent(first, k -> new ArrayList<>()).add(word);does the check, the creation and the add in one statement. On the second example it also gives{c=[cat, cow], d=[dog, deer, duck]}. The lesson's version spells out each case. substringon an empty string."".substring(0, 1)throws aStringIndexOutOfBoundsException. The lesson guarantees that every word has at least one letter.
Complexity
Time: O(n) for n words, ignoring the length of the words: each word costs a constant number of map and list operations on average. Space: O(n), because every word ends up in one list.
Edge cases and common mistakes
- Replacing the list. Putting a new
ArrayListfor every word, without thecontainsKeycheck, leaves only the last word of each group. - Forgetting the
!. Without it the group is created only when it already exists, and the firstgetreturnsnull. - Using
charAt(0)as the key. That is achar, and it would be boxed into aCharacter. The map's key type isString, so the call doesn't match. - Repeated words.
["go", "go"]gives{g=[go, go]}. Both stay, because a list keeps duplicates. - Counting instead of grouping. If the values were numbers, you would lose the words themselves. The point of the list is to keep them.
Testing
["apple", "banana", "avocado", "blueberry", "cherry"]gives{a=[apple, avocado], b=[banana, blueberry], c=[cherry]}.["dog", "cat", "deer", "cow", "duck"]gives{c=[cat, cow], d=[dog, deer, duck]}.["hello"]gives{h=[hello]}.["go", "go"]gives{g=[go, go]}.
