NeetCode #164LC-1258MediumArrays & Hashing
← Back to All Problems#164 · #1258 · Synonymous Sentences(近义词句子)
📌 Problem Statement & Constraints
Given a list of synonym pairs and a sentence
text, generate all possible sentences by replacing words with their synonyms. Return the results sorted lexicographically. Constraints: 0 <= synonyms.length <= 10, 1 <= text.length <= 10; synonym pairs are symmetric and transitive.💡 Core Algorithmic Approaches
- Synonyms are symmetric and transitive, so group them with union-find.
- For each group, collect all words and sort them so the generated sentences come out in lexicographic order.
- Split the text into words; each word maps either to its synonym group (sorted) or to a single-element list of itself.
- The answer is the Cartesian product of those lists, joined by spaces and sorted.
💻 Benchmark Python3 Implementation
class Solution:
def generateSentences(self, synonyms: List[List[str]], text: str) -> List[str]:
from collections import defaultdict
from itertools import product
parent = {}
def find(x: str) -> str:
parent.setdefault(x, x)
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for a, b in synonyms:
ra, rb = find(a), find(b)
if ra != rb:
parent[ra] = rb
groups = defaultdict(list)
for w in parent:
groups[find(w)].append(w)
for g in groups.values():
g.sort() # sorted -> lexicographic output
options = []
for w in text.split():
if w in parent:
options.append(groups[find(w)])
else:
options.append([w]) # unchanged word
return sorted(" ".join(combo) for combo in product(*options))⚡ Complexity Deep Dive
⏱️ Time Complexity
O(m * alpha + P log P) where m is the number of synonym pairs and P is the size of the Cartesian product (bounded by the problem's small constraints).
💾 Space Complexity
O(P * L) for the output.
⚠️ Interview Pitfalls & Follow-ups
- Ignoring transitivity:
a~bandb~cimpliesa~c, which union-find handles but a direct pair map would not. - Forgetting that synonymy is symmetric: the pairs must be unioned in both directions, which
union(a, b)does. - Not sorting the groups: the output must be lexicographically sorted, and sorting the groups first makes the Cartesian product naturally ordered.
- Replacing words that have no synonyms: they must pass through unchanged, which the single-element list handles.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Arrays & Hashing Problems
中文速览与面试要点
近义词句子
给你一个近义词表 synonyms 和一个句子 text,synonyms 表中是一些近义词对 [word1, word2] 。近义词关系是 可传递 的(若 a 与 b 近义、b 与 c 近义,则 a 与 c 近义)。请你返回所有可能的近义句子。句子是一系列由空格分隔的单词,text 中的每个单词都可以替换为它的任意近义词(也可保留原词)。返回的结果需按 字典序 排序。约束:1 ≤ synonyms.length ≤ 10;1 ≤ text.length ≤ 100;所有单词由小写英文字母组成。
核心要点
- 并查集求近义词连通分量(标准解) :近义词关系可传递,因此用并查集把所有近义词合并成若干组。
- 每组内部排序 :对每个连通分量内的单词按字典序排序,便于后续生成有序结果。
- 回溯生成所有句子 :按 text 的单词顺序,对每个位置枚举「该单词所属组内的所有候选」(若单词不在任何组中,则只有它自己),回溯拼接。
- 结果天然有序 :由于每个位置都按字典序枚举候选,深度优先的回溯会按字典序产生结果,无需最后排序。
常见陷阱
- 把近义词关系当作不可传递 :题目明确说明可传递,必须用并查集求连通分量,而非简单的双向映射。
- 忘记 parent.setdefault(x, x) :并查集的 find 中若不初始化未知键,会抛 KeyError。
- 结果未按字典序 :若组内未排序,回溯产生的结果顺序不确定。对每组排序即可保证整体字典序。
- 对 text 中不在近义词表中的单词也尝试替换 :这类单词只能保留原词,必须单独处理。
- 忘记恢复现场( path.pop() ) :回溯时若不弹出,path 会不断累积,结果错误。
参考实现
from collections import defaultdict
class Solution:
def generateSentences(self, synonyms: list[list[str]], text: str) -> list[str]:
parent = {}
def find(x: str) -> str:
parent.setdefault(x, x)
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for a, b in synonyms:
ra, rb = find(a), find(b)
if ra != rb:
parent[ra] = rb
groups = defaultdict(list)
for w in list(parent):
groups[find(w)].append(w)
for k in groups:
groups[k].sort() # 组内按字典序,保证结果有序
words = text.split()
res = []
def dfs(i: int, path: list) -> None:
if i == len(words):
res.append(' '.join(path))
return
w = words[i]
if w in parent:
for cand in groups[find(w)]: # 枚举该组内所有近义词
path.append(cand)
dfs(i + 1, path)
path.pop()
else:
path.append(w) # 无近义词,只能保留原词
dfs(i + 1, path)
path.pop()
dfs(0, [])
return res