Group Anagrams

Medium Sorting AI round

strs is a list of words, each made of lowercase letters. A word may be empty, and the same word may appear more than once.

Two words are anagrams when they hold exactly the same letters, each letter the same number of times. Put every word of strs into a group with its anagrams, so that each word is in exactly one group, and two words that are not anagrams are never in the same group.

Return the groups, each as a list of its words. The groups may come in any order, and so may the words inside each group.

Example 1

Input: strs = ["spare","pears","cat","reaps","act","tac","bold"]
One right answer: [["spare","pears","reaps"],["cat","act","tac"],["bold"]]

spare, pears and reaps are made of the same five letters, and so are cat, act and tac. bold has no anagram in the list, so it is a group of one.

Example 2

Input: strs = ["pop","pop","opp","top"]
One right answer: [["pop","pop","opp"],["top"]]

Example 3

Input: strs = ["","a",""]
One right answer: [["",""],["a"]]

Constraints

  • 1 ≤ strs.length ≤ 8000
  • 0 ≤ strs[i].length ≤ 30
  • strs[i] holds only the letters a to z

Watch the explanation

More Sorting

All Sorting problems