#K40352. Group Words by First Letter

    ID: 26623 Type: Default 1000ms 256MiB

Group Words by First Letter

Group Words by First Letter

In this problem, you are given a list of words and your task is to group them based on their first letter (case‐insensitive). For each word, consider the lowercase version of its first letter. Then, collect all words sharing the same first letter in the order they appear and finally output the groups as a JSON object with keys sorted in alphabetical order.

For example, given the words:

apple banana grape avocado blueberry cherry

The output should be:

{"a":["apple","avocado"],"b":["banana","blueberry"],"c":["cherry"],"g":["grape"]}

Note that the keys of the JSON object must be in lexicographical order. Here is a summary of the requirements in mathematical form:

$$\text{Output} = \{ k : [w_1, w_2, \ldots] \mid k = \text{lower}(w[0]), \; w \in \text{words} \} $$

All input is read from stdin and output must be written to stdout in the specified format.

inputFormat

The input will be provided via stdin. The first line contains an integer n (0 ≤ n ≤ 10^5) representing the number of words. If n > 0, the second line contains n words separated by spaces. If n is 0, there will be no second line.

outputFormat

Output a single JSON object (as a string) that maps each lowercase first letter to a list of words that start with that letter, preserving the order of their appearance in the input. The keys in the JSON object must be sorted in alphabetical order. If there are no words (n = 0), output an empty JSON object: {}.## sample

6
apple banana grape avocado blueberry cherry
{"a":["apple","avocado"],"b":["banana","blueberry"],"c":["cherry"],"g":["grape"]}