LeetCode 49 Group Anagrams - Implementation

The approach

Use sorted characters as the key. All anagrams share the same sorted form. Group strings by their sorted key.

Here's the solution:

function groupAnagrams(strs):
    groups = {}
    for s in strs:
        key = tuple(sorted(s))
        if key not in groups:
            groups[key] = []
        groups[key].append(s)
    return list(groups.values())

O(nklogk)O(n \cdot k \log k) time, O(nk)O(n \cdot k) space where kk is max string length.