#C14864. Group Anagrams

    ID: 44560 Type: Default 1000ms 256MiB

Group Anagrams

Group Anagrams

You are given \(n\) words consisting of lowercase letters. Your task is to group the words that are anagrams of each other. Two words are anagrams if one can be rearranged to form the other. For each group, sort the words in lexicographical order. Then, sort all groups in ascending order based on the first word of each group, and output each group on a separate line with the words separated by a space.

Input Format: The first line contains an integer \(n\), the number of words. The second line contains \(n\) words separated by spaces.

Output Format: For each group, print a single line containing the sorted anagrams. The groups themselves must be printed in ascending lexicographical order of their first word.

For example, given the input:

7
bat tab cat act rat tar car

The groups are:

  • Group of "bat" and "tab" (sorted: "bat tab")
  • Group of "cat" and "act" (sorted: "act cat")
  • Group of "rat" and "tar" (sorted: "rat tar")
  • Group of "car" (sorted: "car")

After sorting the groups by the first word, the final output is:

act cat
bat tab
car
rat tar

inputFormat

The first line of input contains an integer \(n\) (\(1 \le n \le 10^5\)), representing the number of words. The second line contains \(n\) words separated by spaces. Each word consists of only lowercase English letters.

outputFormat

Output the grouped anagrams. Each group should be printed on a new line, where the words in the group are sorted in lexicographical order, and the groups are sorted based on their first word in lexicographical order. Words in each line are separated by a single space.

## sample
7
bat tab cat act rat tar car
act cat

bat tab car rat tar

</p>