/49. Group Anagrams

49. Group Anagrams

Medium
Arrays72.3% acceptance

Given a list of lowercase English strings string_list, group the strings into lists such that each group contains strings that are anagrams of each other. Return a list of groups, where each group is a list of anagrams. The order of groups and the order of strings within each group does not matter.

Example 1

Input: [abc, cab, bca, xyz, zyx, yxz, foo]

Output: [[abc, cab, bca], [xyz, zyx, yxz], [foo]]

Explanation: Three groups: anagrams of abc, anagrams of xyz, and foo alone.

Example 2

Input: [mno, nom, onm, pqr, rpq, qpr, stu]

Output: [[mno, nom, onm], [pqr, rpq, qpr], [stu]]

Explanation: Three groups: anagrams of mno, anagrams of pqr, and stu alone.

Example 3

Input: ['']

Output: [['']]

Explanation: Empty string forms its own group.

Example 4

Input: [a, b, c]

Output: [[a], [b], [c]]

Explanation: No anagrams, each string is its own group.

Constraints

  • 1 <= len(string_list) <= 104
  • 0 <= len(s) <= 100 for each s in string_list
  • Each s in string_list consists of lowercase English letters
Python (current runtime)

Case 1

Input: ['rat', 'tar', 'art', 'dog', 'god', 'odg', 'cat']

Expected: [['rat', 'tar', 'art'], ['dog', 'god', 'odg'], ['cat']]

Case 2

Input: ['apple', 'papel', 'leapp', 'banana', 'ananab', 'xyz']

Expected: [['apple', 'papel', 'leapp'], ['banana', 'ananab'], ['xyz']]

Case 3

Input: ['a', 'b', 'c', 'a']

Expected: [['a', 'a'], ['b'], ['c']]

Case 4

Input: ['abc', 'def', 'ghi']

Expected: [['abc'], ['def'], ['ghi']]