#K73217. Group Anagrams
Group Anagrams
Group Anagrams
Given a list of words, group 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. Each group must be printed in a separate line after sorting the words in the group in lexicographical order. Finally, sort the groups by the lexicographically smallest word in each group.
The problem can be formalized as follows:
Given a set ( S = {w_1, w_2, \ldots, w_n} ), where each word ( w_i ) is a string, partition ( S ) into subsets ( S_1, S_2, \ldots, S_k ) such that for any two words in the same subset, they are anagrams, and words from different subsets are not anagrams. Then, for each subset, sort the words, and finally, sort the subsets by the first element.
inputFormat
The input consists of two lines:
- The first line contains an integer ( n ) indicating the number of words.
- The second line contains ( n ) words separated by spaces.
outputFormat
Output the anagram groups, one group per line. In each line, print the words in that group sorted in lexicographical order, and the groups themselves should be sorted in ascending order by their first word.## sample
6
eat tea tan ate nat bat
ate eat tea
bat
nat tan
</p>