THINK FIRST·CODE LATER

← All labs

Group anagrams

Problem

Two words are anagrams if one is a rearrangement of the letters of the other (listen / silent). Their signature — the letters sorted alphabetically — is then the same: eilnst.

The input is an integer n followed by n words. Convert each word to lower case and group the words by signature:

  • Groups are printed in the order in which their first word appeared.
  • Inside a group, words appear in input order; a word that is already in its group is ignored (no duplicates).
  • Finally print the largest group's signature and size; on a tie, the group that appeared first wins. If n is 0 print Largest group: none.

Use a Map<String, Set<String>> — which implementations give you the two required orders for free?

For the input

7
listen tea silent eat dog enlist ate

the output must be exactly:

Groups: 3
eilnst: listen silent enlist
aet: tea eat ate
dgo: dog
Largest group: eilnst (3)

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.