Problem overview
The method GroupByFirstLetter receives a string[] named words of lowercase words. It returns a Dictionary<string, List<string>>: 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 words, and a word that appears twice appears twice in its group.
For ["apple", "banana", "avocado", "blueberry", "cherry"] the groups are a with apple and avocado, b with banana and blueberry, and c with cherry. For ["dog", "cat", "deer", "cow", "duck"], d holds dog, deer, duck and c holds cat, cow. One word, ["hello"], makes one group, h.
Approach: a dictionary whose values are lists
Each word belongs to exactly one group, so one pass over words is enough. For every word, take its first letter and look for that letter's group. If the group doesn't exist yet, create an empty list for it. Then add the word to the list.
The value type is a List<string>, which can grow, because the number of words per letter isn't known in advance. Adding the words in the order the loop meets them keeps each group in the original order.
The key is a string, so the first letter has to be a string too. The expression word[0] is a char, and a char can't be used as a key of a Dictionary<string, ...>. The lesson takes word.Substring(0, 1) instead: the part of the word that starts at position 0 and is 1 character long. For "hello" both word[0] and the substring look like h, but only the substring has the right type.
Step by step
- Create an empty
Dictionary<string, List<string>>namedgroups. - Write a
foreachloop with astringnamedwordoverwords. - Take the first letter as a string:
string first = word.Substring(0, 1);. - If
groupsdoesn't containfirst(!groups.ContainsKey(first)), setgroups[first]to a new, emptyList<string>. The first word with a new letter starts that letter's group. - Add the word to its group with
groups[first].Add(word). This runs for every word, whether its group is new or not. - Return
groupsafter the loop.
The solution in C#
class Solution {
public Dictionary<string, List<string>> GroupByFirstLetter(string[] words) {
Dictionary<string, List<string>> groups = new Dictionary<string, List<string>>();
foreach (string word in words) {
string first = word.Substring(0, 1);
if (!groups.ContainsKey(first)) {
groups[first] = new List<string>();
}
groups[first].Add(word);
}
return groups;
}
}
Details worth knowing:
groups[first]gives the list that is stored in the dictionary, not a copy. CallingAddon it changes the list inside the dictionary, so no assignment back is needed.- The
ifcreates the list but doesn't add the word. TheAddline sits after theif, so the first word of a group is added too. - Reading
groups[first]before the group exists would throw aKeyNotFoundException. TheContainsKeycheck prevents it.
Complexity
Every word is handled once with constant-time work on average (a substring of length 1, a dictionary lookup and a list append), so the time is O(n) for n words. The groups together hold all the words, so the space is O(n).
Edge cases and common mistakes
- Using
word[0]as the key. It is achar, which doesn't matchDictionary<string, ...>, and the code doesn't compile. - Putting
Addinside theif. The first word of every group would be added, and the later words would be lost. - Creating a new list every time. Without the
ContainsKeycheck, each word would replace its group with a fresh list holding only that word. - Repeated words. They are kept, each in its place.
