Problem overview
The function groupByFirstLetter receives an array of lowercase words and returns a dictionary. Each key is a first letter, written 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 had in words, and a word that appears twice appears twice in its group. 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"] and "c": ["cherry"].
Approach: a dictionary whose values are arrays
Each word belongs to exactly one group, so one pass over words is enough. For every word, find its first letter and append the word to the array stored under that letter. The first word with a new letter has to create the array; later words with the same letter find it waiting.
The order inside a group comes for free. The loop meets the words in their original order and appends each one to the end of its group's array.
Step by step
- Create
groupsas an empty[String: [String]]withvar: each key is a one-letter string and each value an array of words. - Loop over
wordswithfor word in words. - Take the first letter as
String(word.prefix(1)). - Append to the group with
groups[first, default: []].append(word). - Return
groups.
The solution in Swift
class Solution {
func groupByFirstLetter(_ words: [String]) -> [String: [String]] {
var groups = [String: [String]]()
for word in words {
let first = String(word.prefix(1))
groups[first, default: []].append(word)
}
return groups
}
}
Swift details
prefix(1)gives aSubstring.word.prefix(1)takes the first character, but its type isSubstring, notString. Wrapping it inString(...)makes a real string, which is the key type of the dictionary. Strings can't be indexed with an integer in Swift, soword[0]doesn't compile;prefixis the usual way to take the start.- The
default:subscript.groups[first, default: []]returns the array stored underfirst, or a fresh empty array when the key is missing. Used withappend, it changes the array stored in the dictionary itself: the first word for a letter creates the entry, and the next ones extend it. - Value types. Arrays copy on assignment in Swift. Writing
var group = groups[first]and appending togroupwould change only the copy. Thedefault:form edits the stored array in place, which is why the lesson uses it. - Without
default. The plain subscriptgroups[first]returns an optional array,nilfor a new letter, and you would need anif letand anelseto handle both cases.
Edge cases and common mistakes
- One word.
["hello"]gives one group, "h": ["hello"]. - Order inside a group. For
["dog", "cat", "deer", "cow", "duck"], the "d" group is ["dog", "deer", "duck"], in the order of the input, and the "c" group is ["cat", "cow"]. - Repeated words. They stay in the group as many times as they appear.
- Keys as
Character. The return type is[String: [String]], so aCharacterkey doesn't fit. - An empty word. The lesson promises every word has a letter. For an empty string,
prefix(1)returns an empty string and the word would be grouped under the key"". It doesn't crash, asword[word.startIndex]would.
Testing
Groups are listed in alphabetical order here for readability.
["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"].
