Leetcode #1258: Synonymous Sentences
In this guide, we solve Leetcode #1258 Synonymous Sentences in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given a list of equivalent string pairs synonyms where synonyms[i] = [si, ti] indicates that si and ti are equivalent strings. You are also given a sentence text.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Sort, Union Find, Array, Hash Table, String, Backtracking
Intuition
Fast membership checks and value lookups are the heart of this problem, which makes a hash map the natural choice.
By storing what we have already seen (or counts/indexes), we can answer the question in one pass without backtracking.
Approach
Scan the input once, using the map to detect when the condition is satisfied and to update state as you go.
This keeps the solution linear while remaining easy to explain in an interview setting.
Steps:
- Initialize a hash map for seen items or counts.
- Iterate through the input, querying/updating the map.
- Return the first valid result or the final computed value.
Example
Input: synonyms = [["happy","joy"],["sad","sorrow"],["joy","cheerful"]], text = "I am happy today but was sad yesterday"
Output: ["I am cheerful today but was sad yesterday","I am cheerful today but was sorrow yesterday","I am happy today but was sad yesterday","I am happy today but was sorrow yesterday","I am joy today but was sad yesterday","I am joy today but was sorrow yesterday"]
Python Solution
class UnionFind:
def __init__(self, n):
self.p = list(range(n))
self.size = [1] * n
def find(self, x):
if self.p[x] != x:
self.p[x] = self.find(self.p[x])
return self.p[x]
def union(self, a, b):
pa, pb = self.find(a), self.find(b)
if pa != pb:
if self.size[pa] > self.size[pb]:
self.p[pb] = pa
self.size[pa] += self.size[pb]
else:
self.p[pa] = pb
self.size[pb] += self.size[pa]
class Solution:
def generateSentences(self, synonyms: List[List[str]], text: str) -> List[str]:
def dfs(i):
if i >= len(sentence):
ans.append(' '.join(t))
return
if sentence[i] not in d:
t.append(sentence[i])
dfs(i + 1)
t.pop()
else:
root = uf.find(d[sentence[i]])
for j in g[root]:
t.append(words[j])
dfs(i + 1)
t.pop()
words = list(set(chain.from_iterable(synonyms)))
d = {w: i for i, w in enumerate(words)}
uf = UnionFind(len(d))
for a, b in synonyms:
uf.union(d[a], d[b])
g = defaultdict(list)
for i in range(len(words)):
g[uf.find(i)].append(i)
for k in g.keys():
g[k].sort(key=lambda i: words[i])
sentence = text.split()
ans = []
t = []
dfs(0)
return ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.