# 49. Group Anagrams

• Time: $O(nk\log k)$, where $n = |\texttt{strs}|$ and $k = |\texttt{strs[i]}|$
• Space: $O(nk)$
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Solution { public: vector> groupAnagrams(vector& strs) { vector> ans; unordered_map> keyToAnagrams; for (const string& str : strs) { string key = str; sort(key.begin(), key.end()); keyToAnagrams[key].push_back(str); } for (const auto& [_, anagrams] : keyToAnagrams) ans.push_back(anagrams); return ans; } }; 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Solution { public List> groupAnagrams(String[] strs) { Map> keyToAnagrams = new HashMap<>(); for (final String str : strs) { char[] chars = str.toCharArray(); Arrays.sort(chars); String key = String.valueOf(chars); keyToAnagrams.computeIfAbsent(key, k -> new ArrayList<>()).add(str); } return new ArrayList<>(keyToAnagrams.values()); } } 
 1 2 3 4 5 6 7 8 9 class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: dict = collections.defaultdict(list) for str in strs: key = ''.join(sorted(str)) dict[key].append(str) return dict.values()