Problem overview
The method groupByFirstLetter receives a list of lowercase words and returns a dictionary. Each key is a first letter, written as a one-character string, and its value is the list of all the words that start with that letter. Inside each group the words keep the order they have in the input. The order of the dictionary's entries doesn't matter.
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 {'d': ['dog', 'deer', 'duck'], 'c': ['cat', 'cow']}. A word that appears twice is listed twice in its group.
Approach: a dictionary whose values are lists
Counting with a dictionary stores a number under each key. Grouping works the same way, except that each value is a list that collects items. For every word, find its group, creating the group first if this is the first word with that letter, and add the word to it.
One pass over the words is enough, since each word belongs to exactly one group. The words arrive in input order and are appended at the end of their group's list, so each group keeps that order.
Step by step
- Create an empty dictionary named
groups. Later, keys are letters and values are lists of words. - Loop over
wordswithfor word in words. - Take the first letter:
first = word[0]. It is the key of the group this word belongs to. - Create the group when it is missing.
if first not in groups:is true when the key is absent, and its body setsgroups[first] = []. The first word with a new letter starts the group. Later words with the same letter find it already there. - Append the word with
groups[first].append(word). This line sits after theif, so it runs for every word, whether the group was just created or already existed. - Return
groupsafter the loop.
The solution in Python
class Solution:
def groupByFirstLetter(self, words: List[str]) -> Dict[str, List[str]]:
groups = {}
for word in words:
first = word[0]
if first not in groups:
groups[first] = []
groups[first].append(word)
return groups
Python details to keep in mind:
word[0]is a string. Indexing a string gives a one-character string, which is what the keys should be. It works because every word has at least one letter. On an empty string,""[0]raisesIndexError: string index out of range.not inis the opposite ofin.first not in groupsis true whenfirstis not a key.groups[first]is the list itself. It isn't a copy, so appending to it changes the list stored in the dictionary. There is no need to assign it back.- Each group needs its own list. Because
[]is evaluated each time theifbody runs, every letter gets a fresh list. Sharing one list between groups would mix the words up. - A built-in shortcut.
groups.setdefault(first, []).append(word)orcollections.defaultdict(list)replaces theif. The explicit check shows the two cases clearly, and it is how most beginners first write it.
Edge cases and common mistakes
- Appending to a missing group. Without the
if,groups[first].append(word)raisesKeyErroron the first word of each letter. - Resetting the group every time. If
groups[first] = []ran for every word, instead of only when the key is missing, each group would end up holding just its last word. Keep that line inside theif. - Repeated words.
["no", "net", "no"]gives{'n': ['no', 'net', 'no']}: nothing is removed, and the order is kept. - One word.
["hello"]gives{'h': ['hello']}.
Testing
["apple", "banana", "avocado", "blueberry", "cherry"]gives{'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}.["dog", "cat", "deer", "cow", "duck"]gives{'d': ['dog', 'deer', 'duck'], 'c': ['cat', 'cow']}.["hello"]gives{'h': ['hello']}.["no", "net", "no"]gives{'n': ['no', 'net', 'no']}.
