← All coding problems
Group Anagrams
mediumArrays & Hashing+20 XPTime limit 2s
Group the words that are anagrams of each other (same letters, any order).
Input:
- line 1:
n - next
nlines: one word each (lowercase letters)
Output: one group per line, the words of a group separated by spaces. So that there is exactly one correct output:
- inside a group, sort the words alphabetically (keep duplicates);
- sort the groups by comparing them word by word (so the group whose first word is alphabetically smallest comes first).
Constraints: 1 ≤ n ≤ 10⁴, 1 ≤ word length ≤ 100.
Think about it: two words are anagrams exactly when their sorted letters (or their 26 letter counts) are equal — use that as a hash-map key.
Sample input 1
6 eat tea tan ate nat bat
Sample output 1
ate eat tea bat nat tan
Sample input 2
1 a
Sample output 2
a
📖 Stuck? Learn the pattern
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).