⚡Flashcard Drill➔
NeetCode #40LC-49MediumArrays & HashingBlind 75NC 150NC 250
← Back to All Problems

#40 · #49 · Group Anagrams(字母异位词分组)

📌 Problem Statement & Constraints

Given an array of strings strs, group the anagrams together. Return the groups in any order. Constraints: 1 <= strs.length <= 10^4, 0 <= strs[i].length <= 100; each string contains only lowercase English letters.

💡 Core Algorithmic Approaches

  1. Anagrams share the same multiset of characters, so any canonical form of that multiset works as a hash key.
  2. Option A: sort each string -- the sorted string is the key. Cost per string is O(k log k).
  3. Option B (better): build a 26-length count vector per string and use its tuple as the key. Cost per string is O(k).
  4. Group by appending to groups[key], then return the values. The tuple is required because lists are unhashable.

💻 Benchmark Python3 Implementation

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        from collections import defaultdict
        groups = defaultdict(list)
        for s in strs:
            # canonical key: 26-dimensional character-count vector
            key = [0] * 26
            for ch in s:
                key[ord(ch) - 97] += 1
            groups[tuple(key)].append(s)      # tuple is hashable
        return list(groups.values())


# Alternative key: the sorted string (shorter to write, slightly slower)
class Solution2:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        from collections import defaultdict
        groups = defaultdict(list)
        for s in strs:
            groups["".join(sorted(s))].append(s)
        return list(groups.values())

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n * k) with the counting key, where n is the number of strings and k the maximum length. The sorted-key variant is O(n * k log k).
💾 Space Complexity
O(n * k) for the output plus the grouping structure; the count vector itself is O(1) extra per string.

⚠️ Interview Pitfalls & Follow-ups

  • Using a list as the dictionary key: raises TypeError: unhashable type: 'list'. Convert to tuple.
  • Using the sorted string without joining: sorted(s) returns a list, which is again unhashable.
  • Assuming the empty string is special: "" has an all-zero count vector and groups with other empty strings; no special case needed.
  • Trying to compare pairwise with a custom anagram test: O(n^2 * k) and far more code.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

字母异位词分组

给你一个字符串数组 strs,请你将所有的字母异位词组合在一起,可以按任意顺序返回结果列表。字母异位词指由重新排列源单词的所有字母得到的新单词。约束:1 ≤ strs.length ≤ 10^4;0 ≤ strs[i].length ≤ 100;strs[i] 仅包含小写字母。

核心要点

  • 核心洞察 :互为异位词的字符串共享同一个「不变量」(签名)。把所有词按签名分组,同组即为异位词。
  • 签名方案一 · 排序 :把每个词排序后作为 key,如 eat / tea / ate 都得到 aet。时间 O(n · k log k)。
  • 签名方案二 · 计数编码(更优) :用长度 26 的计数数组拼成元组作为 key。时间 O(n · k),避免了排序。
  • 为什么元组能作 key 而列表不能 :Python 的 dict 键必须可哈希,list 不可哈希,tuple 可以。也可把计数数组转成带分隔符的字符串(如 1#0#2#... )。
  • 避免签名歧义 :若用字符串拼接,必须加分隔符;否则 [1, 11] 与 [11, 1] 会撞键。

常见陷阱

  • 计数编码漏加分隔符 :把计数数组直接 "".join(map(str, cnt)) 而不加分隔符,会导致 [1,11] 与 [11,1] 生成相同字符串而错误合并。用 tuple 则天然无此问题。
  • 以为排序签名一定更慢 :当 k 很小(如 k ≤ 5)时, sorted 的 C 层实现在常数上可能反超手写 26 次循环,实际选型应实测而非想当然。
  • 忽略空字符串 :strs[i] 长度可以为 0,空串的签名是全零数组,代码需能正确处理(本解天然正确)。
  • 被追问 大规模流式数据 时答不上来:可先用签名做一次局部聚合再落盘,或改用 MapReduce 按签名分桶并行。

参考实现

class Solution:
    def groupAnagrams(self, strs: list[str]) -> list[list[str]]:
        groups = {}                                  # 签名 -> 该组所有词
        for w in strs:
            cnt = [0] * 26
            for ch in w:
                cnt[ord(ch) - 97] += 1
            key = tuple(cnt)                         # tuple 可哈希,可作 dict 键
            groups.setdefault(key, []).append(w)
        return list(groups.values())

# 签名方案一(更短,稍慢):
# for w in strs: groups.setdefault(''.join(sorted(w)), []).append(w)