SDE & MLE Prep

49. Group Anagrams

Problem

Group the strings in strs so that words that are anagrams of each other end up in the same group. Groups and the words inside them may be in any order.

Example: ["eat","tea","tan","ate","nat","bat"] → [["bat"],["nat","tan"],["ate","eat","tea"]]

Constraints: up to 10⁴ strings of length ≤ 100, lowercase letters.

Every anagram shares a canonical key: the sorted word (O(k log k)) or the 26-letter count tuple (O(k)). Group words by key.

"eat" -> key "aet" ┐
"tea" -> key "aet" ├─> ["eat","tea","ate"]
"ate" -> key "aet" ┘
"tan" -> key "ant" ──> ["tan","nat"]   ...

Complexity: O(n·k) with count keys (n words, length k).

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        groups = defaultdict(list)
        for w in strs:
            key = [0] * 26
            for ch in w:
                key[ord(ch) - 97] += 1
            groups[tuple(key)].append(w)
        return list(groups.values())