#K53932. Grouping Strings by First Character
Grouping Strings by First Character
Grouping Strings by First Character
You are given a list of n strings. Your task is to group these strings by their first character. For each string, consider its first character and add it to the group corresponding to that character.
The output should be a JSON object (dictionary) where each key is a character and the associated value is an array of strings (in the order they appear in the input) that start with that character. Note: The keys in the output must be sorted in lexicographical order.
For example, if the input is:
6 apple apricot banana blueberry cherry cantaloupe
Then the output should be:
{"a": ["apple", "apricot"], "b": ["banana", "blueberry"], "c": ["cherry", "cantaloupe"]}
Use standard input (stdin) and output (stdout) for reading input and printing the result.
In mathematical notation, if you let \( S = [s_1, s_2, \ldots, s_n] \) be the array of strings, then the task is to compute the function
\( group(s) = \{ c : [s_i \in S \mid s_i[0]=c] \} \)
inputFormat
The input is given via standard input and has the following format:
- The first line contains an integer n, the number of strings.
- Each of the next n lines contains a single string.
outputFormat
Output to standard output a single line containing the JSON representation of a dictionary where:
- Each key is a first character from one or more input strings.
- Each value is an array of strings (in the order they appear in the input) that start with that key.
- The keys must be sorted in lexicographical order.
6
apple
apricot
banana
blueberry
cherry
cantaloupe
{"a": ["apple", "apricot"], "b": ["banana", "blueberry"], "c": ["cherry", "cantaloupe"]}