← All questions

Group Anagrams

Medium Arrays & Strings

Given a list of strings, group the ones that are anagrams of each other. An anagram is a rearrangement of the same letters. Return the groups in any order.

Examples

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

Input:  [""]
Output: [[""]]

Constraints

  • 1 <= len(strs) <= 10^4
  • 0 <= len(strs[i]) <= 100, lowercase English letters.

Solution

Approach strategy: Two words are anagrams iff they share the same multiset of letters. So we need a canonical form that is identical for every member of a group and different across groups.

Full worked solution, code, and complexity analysis available in the interactive view.

Related problems