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)

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d5-2-data-1.txt

7
listen tea silent eat dog enlist ate
What your program must print for d5-2-data-1.txt
Groups: 3
eilnst: listen silent enlist
aet: tea eat ate
dgo: dog
Largest group: eilnst (3)

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d5-2-data-1.txt

Windows PowerShell does not understand <:

Get-Content d5-2-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

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.