#K40072. Group Anagrams

    ID: 26561 Type: Default 1000ms 256MiB

Group Anagrams

Group Anagrams

Given a list of words, group the words that are anagrams of each other. Two words are considered anagrams if one can be rearranged to form the other. The grouping should be case-sensitive. In each group, the words should be sorted in lexicographical order (according to ASCII values), and then the groups themselves should be sorted based on the lexicographical order of their first word.

The input is read from standard input. The first line contains an integer n representing the number of words. The second line contains n words separated by spaces. The output should consist of one line per group, where the words in each group are separated by a single space.

For example, if the input is:

6
eat tea tan ate nat bat

Then the anagrams groups are:

  • Group 1: ate eat tea (all words that are anagrams of each other, sorted lexicographically)
  • Group 2: bat
  • Group 3: nat tan

After sorting the groups by their first element, the expected output will be:

ate eat tea
bat
nat tan

Note: Treat letters as case-sensitive.

inputFormat

The input is provided via standard input (stdin) in the following format:

  1. An integer n, representing the number of words.
  2. A single line containing n words separated by spaces.

Constraints:

  • 0 ≤ n ≤ 105
  • Each word consists of English letters.

outputFormat

Output the anagram groups to standard output (stdout). Each group should be printed on a separate line with its words separated by a single space. Within each group, the words must be sorted in lexicographical (ASCII) order. The groups themselves must be ordered by the lexicographical order of their first word.

If there are no words (n = 0), then output nothing.

## sample
6
eat tea tan ate nat bat
ate eat tea

bat nat tan

</p>