Problem overview
The method groupByFirstLetter receives an array of lowercase words and returns an object. Each key is a first letter, as a one-character string, and its value is the array 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. The order of the keys 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 single word, ["hello"], makes one group: {"h": ["hello"]}.
Approach
Each word belongs to exactly one group, so one pass over words is enough. For each word:
- find its group's key, which is the first letter;
- if that group doesn't exist yet, create it as an empty array;
- push the word onto the group.
Because the words are visited in order and each one goes to the end of its group, every group keeps the order of the input.
The values here are arrays, not numbers. That changes the "first time" case compared with counting: the new entry starts as an empty array [], and the word is pushed afterwards by code that is shared with the "group already exists" case. So the check comes first and the push comes after it, with no else.
Step by step
- Create the empty object.
groupsis declared withconstand the type{ [key: string]: string[] }: string keys, arrays of strings as values. - Loop over the words with
for (const word of words). - Get the first letter.
const first: string = word[0]is the key of this word's group. - Create the group when it's missing.
if (!(first in groups))setsgroups[first] = []. The parentheses matter:!must turn the wholefirst in groupscheck around. - Push the word.
groups[first].push(word)runs for every word, after the group is guaranteed to exist. - Return
groupsafter the loop.
The solution in TypeScript
class Solution {
groupByFirstLetter(words: string[]): { [key: string]: string[] } {
const groups: { [key: string]: string[] } = {};
for (const word of words) {
const first: string = word[0];
if (!(first in groups)) {
groups[first] = [];
}
groups[first].push(word);
}
return groups;
}
}
Details worth knowing:
word[0]is a string. Indexing a string gives a one-character string, which works as an object key. Every word has at least one letter, soword[0]exists.!(first in groups). Without the parentheses,!first in groupsapplies!tofirstbeforeinruns, which is a different check.- Arrays are references.
groups[first]is the array stored in the object, not a copy. Pushing onto it changes the array insidegroups, so nothing needs to be assigned back. - Types are erased.
string[]in the index signature is checked by the compiler only. At run time the values are ordinary arrays.
Edge cases and common mistakes
- Pushing before the group exists.
groups[first]would beundefined, andundefined.push(word)throws aTypeError. The check that creates the group has to come first. - Replacing the group every time. Setting
groups[first] = []without the check would empty the group at each word, leaving one word per group. - Repeated words. They are kept:
["go", "go", "gum"]gives{"g": ["go", "go", "gum"]}. - Sharing one array. Creating a fresh
[]for each key avoids groups that accidentally share a list.
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"]}.["go", "go", "gum"]gives{"g":["go","go","gum"]}.
