Hash Map Grouping Process

Input Array of Words

eat
tea
tan
ate
nat
bat

We start with an array of words that we want to group by anagrams.

Sort Each Word Alphabetically

eat
aet

For each word, we sort its characters alphabetically to create a key.

This way, all anagrams will have the same key.

Sort Each Word Alphabetically

eat
aet
tea
aet

Notice how "eat" and "tea" both produce the same sorted key "aet".

Sort Each Word Alphabetically

eat
aet
tea
aet
tan
ant

The word "tan" gets sorted to "ant", which is a different key.

Sort Each Word Alphabetically

eat
aet
tea
aet
tan
ant
ate
aet

"ate" also sorts to "aet", making it an anagram of "eat" and "tea".

Sort Each Word Alphabetically

eat
aet
tea
aet
tan
ant
ate
aet
nat
ant

"nat" sorts to "ant", matching with "tan".

Sort Each Word Alphabetically

eat
aet
tea
aet
tan
ant
ate
aet
nat
ant
bat
abt

Finally, "bat" sorts to "abt", creating a new key.

Building the Hash Map

Key: "aet"
Value: [ "eat" ]

We start building our hash map using the sorted keys.

The first entry is "aet" → [ "eat" ]

Building the Hash Map

Key: "aet"
Value: [ "eat", "tea" ]

When we process "tea", we find the key "aet" already exists.

So we add "tea" to the existing list for "aet".

Building the Hash Map

Key: "aet"
Value: [ "eat", "tea" ]
Key: "ant"
Value: [ "tan" ]

Next, we process "tan" and create a new entry with key "ant".

Building the Hash Map

Key: "aet"
Value: [ "eat", "tea", "ate" ]
Key: "ant"
Value: [ "tan" ]

For "ate", we add it to the existing list for key "aet".

Building the Hash Map

Key: "aet"
Value: [ "eat", "tea", "ate" ]
Key: "ant"
Value: [ "tan", "nat" ]

For "nat", we add it to the existing list for key "ant".

Final Hash Map

Key: "aet"
Value: [ "eat", "tea", "ate" ]
Key: "ant"
Value: [ "tan", "nat" ]
Key: "abt"
Value: [ "bat" ]

Finally, we add "bat" with its key "abt" to complete our hash map.

Result: Grouped Anagrams

Group 1: (Key "aet")
[ "eat", "tea", "ate" ]
Group 2: (Key "ant")
[ "tan", "nat" ]
Group 3: (Key "abt")
[ "bat" ]

The values from our hash map give us the grouped anagrams!

Each group contains words that are anagrams of each other.

Step 1 of 14