#C10721. Group Anagrams

    ID: 39958 Type: Default 1000ms 256MiB

Group Anagrams

Group Anagrams

Given a list of words, group together the words that are anagrams of each other.

Two words are anagrams if one can be rearranged to form the other. For example, eat, tea and ate are anagrams of each other.

Your task is to form groups of anagrams. In each group, the words should be sorted in alphabetical order. Furthermore, the groups themselves should be sorted in ascending order based on the first word of each group.

The input is provided via standard input, and the output should be printed to standard output.

Note: If there is only one word and no anagrams exist, output the word on a single line.

In mathematical terms, if we let \( f(w) \) be a function that returns the sorted sequence of characters in the word \( w \), then two words \( w_i \) and \( w_j \) are anagrams if and only if \( f(w_i) = f(w_j) \). The grouping should satisfy this property.

inputFormat

The first line of input contains an integer ( n ) representing the number of words. The second line contains ( n ) space-separated words.

outputFormat

Print the groups of anagrams, one group per line. In each group, words are sorted in alphabetical order, and the groups are sorted by the alphabetical order of their first word. Words within a group are separated by a single space.## sample

6
eat tea tan ate nat bat
ate eat tea

bat nat tan

</p>