Group Anagrams

medium

Group strings that are anagrams of each other

Group Anagrams

Key Insight

Use sorted string as key. All anagrams sort to the same key.

Step 1Sort Each Word
Sort each word to get key
Array
eat
0
tea
1
tan
2
ate
3
nat
4
bat
5
HashMap
Empty

"eat" -> "aet", "tea" -> "aet", "tan" -> "ant"

1 / 4

Learn the Pattern

Practice the Code

Step-by-Step Walkthrough: Group Anagrams

Use sorted string as key. All anagrams sort to the same key.

  1. Sort Each Word

    "eat" -> "aet", "tea" -> "aet", "tan" -> "ant"

  2. Group by Key

    Use sorted string as hash map key.

  3. Continue Grouping

    "tea" sorts to "aet" - add to existing group.

  4. Result

    Return all groups as array of arrays.