LeetCode #49: Group Anagrams — combines hash maps with string manipulation. A great Medium problem.
Given a list of strings, group the anagrams together. Two strings are anagrams if they have the same characters.
Example:["eat","tea","tan","ate","nat","bat"]
→ [["eat","tea","ate"], ["tan","nat"], ["bat"]]
Key Insight: Anagrams have the same sorted character sequence. sorted('eat') = ['a','e','t'] and sorted('tea') = ['a','e','t']. Use sorted string as hash map key!
💭 Now it's your turn! Using the approach above, implement your solution in the editor. You've got this! 💪
Complexity: Time O(n · k log k) where k is max string length, Space O(n·k)
from collections import defaultdict
def groupAnagrams(strs):
groups = defaultdict(list)
for s in strs:
key = tuple(sorted(s)) # Sorted chars as key
groups[key].append(s)
return list(groups.values())
Run your code
['ate', 'eat', 'tea']
['bat']
['nat', 'tan']