Intuitively, we can think of each group as an equivalent class.
Moreover, let the sorted equivalent of any word in a class symbolize the class, which forms a mapping so that we can implement directly using dict
in Python.
s
using ''.join(sorted(s))
, where sorted(s)
returns a list.mp: dict
, list(mp.values())
is enough!class Solution:
def groupAnagrams(self, strs: list[str]) -> list[list[str]]:
mp = {}
for s in strs:
h = hash(''.join(sorted(s)))
mp[h] = mp.get(h, []) + [s]
return list(mp.values())