Python ||🔥 Extremely SHORT (5 lines!) & EASY 🔥|| Fully exploit Python
Group Anagrams - LeetCodeLevel up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.https://leetcode.com/problems/group-anagrams/solutions/4684931/python-extremely-short-5-lines-easy-fully-exploit-pythonIntuition
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.
Approach
- Sort a string
s
using''.join(sorted(s))
, wheresorted(s)
returns a list. - In order to reduce the underlying time constant for comparing in the Python dictionary, we can use the hashes of strings as the keys (see Code).
- As to generating the final output from our
mp: dict
,list(mp.values())
is enough!
Code
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())