Start learning free

LESSON 233 OF 292 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Group Words by First Letter in Swift: A Dictionary of Arrays

Practice Read the full explanation

Given an array words of lowercase words, group the words by their first letter. Return a Dictionary where each key is a first letter, written as a one-character string, and its value is an array of all the words that start with that letter.

Inside each group, keep the words in the order they have in words. The order of the entries in the Dictionary doesn't matter.

Example 1:

Input: words = ["apple", "banana", "avocado", "blueberry", "cherry"]
Output: {"a": ["apple", "avocado"], "b": ["banana", "blueberry"], "c": ["cherry"]}
Explanation: "apple" and "avocado" start with "a", "banana" and "blueberry" start with "b", and "cherry" is alone under "c".

Example 2:

Input: words = ["dog", "cat", "deer", "cow", "duck"]
Output: {"d": ["dog", "deer", "duck"], "c": ["cat", "cow"]}
Explanation: "dog" comes before "deer" and "duck" in words, so it comes first in the "d" group too.

Example 3:

Input: words = ["hello"]
Output: {"h": ["hello"]}
Explanation: One word makes one group.

Rules:

  • words has at least one word.
  • Every word has at least one letter and only lowercase letters a-z.
  • A word that appears more than once in words appears as many times in its group.
STEP 1 OF 5
    Ctrl + Enter to check

    SWIFT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Group Words By First Letter in Swift, explained

    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

    1. Create groups as an empty [String: [String]] with var: each key is a one-letter string and each value an array of words.
    2. Loop over words with for word in words.
    3. Take the first letter as String(word.prefix(1)).
    4. Append to the group with groups[first, default: []].append(word).
    5. 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 a Substring. word.prefix(1) takes the first character, but its type is Substring, not String. Wrapping it in String(...) makes a real string, which is the key type of the dictionary. Strings can't be indexed with an integer in Swift, so word[0] doesn't compile; prefix is the usual way to take the start.
    • The default: subscript. groups[first, default: []] returns the array stored under first, or a fresh empty array when the key is missing. Used with append, 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 to group would change only the copy. The default: form edits the stored array in place, which is why the lesson uses it.
    • Without default. The plain subscript groups[first] returns an optional array, nil for a new letter, and you would need an if let and an else to 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 a Character key 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, as word[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"].
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free