Start learning free

LESSON 231 OF 289 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Group Words by First Letter in C#: Dictionary of Lists

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 6
    Ctrl + Enter to check

    C# · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Group Words By First Letter in C#, explained

    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

    1. Create an empty Dictionary<string, List<string>> named groups.
    2. Write a foreach loop with a string named word over words.
    3. Take the first letter as a string: string first = word.Substring(0, 1);.
    4. If groups doesn't contain first (!groups.ContainsKey(first)), set groups[first] to a new, empty List<string>. The first word with a new letter starts that letter's group.
    5. Add the word to its group with groups[first].Add(word). This runs for every word, whether its group is new or not.
    6. Return groups after 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. Calling Add on it changes the list inside the dictionary, so no assignment back is needed.
    • The if creates the list but doesn't add the word. The Add line sits after the if, so the first word of a group is added too.
    • Reading groups[first] before the group exists would throw a KeyNotFoundException. The ContainsKey check 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 a char, which doesn't match Dictionary<string, ...>, and the code doesn't compile.
    • Putting Add inside the if. The first word of every group would be added, and the later words would be lost.
    • Creating a new list every time. Without the ContainsKey check, each word would replace its group with a fresh list holding only that word.
    • Repeated words. They are kept, each in its place.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free