#49 Group Anagrams

MediumArrays & Hashing~20 min

You're given an array of strings strs. Partition it into groups so that every group contains words that are anagrams of each other, the same letters rearranged. Return the list of groups; the order of groups and the order within a group don't matter.

Examples

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

eat/tea/ate share the letters {a, e, t}; tan/nat share {a, n, t}; bat stands alone.

Inputstrs = [""]
Output[[""]]

The empty string is an anagram of itself, one group of one.

Constraints

  • 1 ≤ strs.length ≤ 10⁴
  • 0 ≤ strs[i].length ≤ 100
  • strs[i] consists of lowercase English letters

The explainer is the good part.

Sign in for the full intuition build-up, every approach from naive to optimal with complexity analysis, progressive hints, and commented solutions in Python, JavaScript, and Java. All free.

Want a taste first? Try a free sample: Two Sum or Valid Parentheses.