Practice · Hashing · 4 of 7

Group Anagrams

You are given a list of lowercase words strs. Two words are anagrams if one is a rearrangement of the other's letters, using each letter exactly as often ("listen" and "silent").

Group the words so that each group holds words that are all anagrams of each other, and no two groups could be merged. Return the groups as a list of lists. The order of the groups, and of the words inside each group, doesn't matter.

Example 1

Input
strs = ["tea", "ate", "tan", "eat", "nat", "bat"]
Output
[["tea", "ate", "eat"], ["tan", "nat"], ["bat"]]

Example 2

Input
strs = ["", "b", ""]
Output
[["", ""], ["b"]]
The empty word is an anagram of itself.

Constraints

  • strs holds 1 to 10⁴ words.
  • Each word has 0 to 100 lowercase English letters.
Brush up firstHash Table visualiser