We use a hash map where the key is the sorted version of a string (or a character frequency tuple). All anagrams will have the same key.
- Initialize a hash map
ans = defaultdict(list). - For each string
sinstrs:- Create a key:
sorted_s = "".join(sorted(s)). - Append
stoans[sorted_s].
- Create a key:
- Return
ans.values().
- Time Complexity: O(N * K log K), where K is the max length of a string.
- Space Complexity: O(N * K).
from collections import defaultdict
def group_anagrams(strs):
ans = defaultdict(list)
for s in strs:
key = "".join(sorted(s))
ans[key].append(s)
return list(ans.values())