We use a hash map where the key is either the sorted version of the string or a frequency tuple.
- Initialize
ans = defaultdict(list). - For each string
sinstrs:- Count character frequencies (a-z) into a tuple of size 26.
- Use this tuple as a key in
ansand appendsto the list.
- Return
ans.values().
- Time Complexity: O(N * K), where K is the length of the string.
- Space Complexity: O(N * K).
from collections import defaultdict
def group_anagrams(strs):
ans = defaultdict(list)
for s in strs:
count = [0] * 26
for char in s:
count[ord(char) - ord('a')] += 1
ans[tuple(count)].append(s)
return list(ans.values())