Start learning free

LESSON 213 OF 500 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Group Words by First Letter in C++

Practice

Given a vector words of lowercase words, group the words by their first letter. Return an unordered_map where each key is a first letter, written as a one-character string, and its value is a vector 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 unordered_map 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

    Group Words By First Letter in C++

    Keep going with C++500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free