from collections import defaultdict from typing import Dict, List class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: if len(strs) <= 1: return [strs] result: List[List[str]] = [] char_counter: Dict[str, Dict[str, int]] = dict() for word in strs: sorted_word: str = "".join(sorted(word)) # Get by sorted_word key sorted_entry = char_counter.get(sorted_word) if sorted_entry: char_counter[sorted_word].append(word) else: char_counter[sorted_word] = [word] for value in char_counter.values(): result.append(value) return result class NeetcodeSolution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: ans = defaultdict(list) for s in strs: count = [0] * 26 for c in s: count[ord(c) - ord("a")] += 1 ans[tuple(count)].append(s) return ans.values() s = Solution() strs = ["act", "pots", "tops", "cat", "stodsafjoooop", "hat"] print(s.groupAnagrams(strs))