Synonymous Sentences — LeetCode 1258 Python Solution
MediumLeetCode PremiumSortUnion FindArrayHash TableStringBacktracking
- Problem
- #1258
- Pattern
- Union-Find
- Reading time
- 9 min
- Source
- leetcode.com
The problem
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.
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
Python
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(n) auxiliary |
Pattern: Union-Find
Merge groups and ask whether two things are connected, both in near-constant time. LeetCode 1258. Synonymous Sentences is filed here because LeetCode tags it Union Find, which is the vocabulary this hub collects.
The union-find guide has the Python template for the pattern and the 83 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1258. Synonymous Sentences?
- LeetCode 1258. Synonymous Sentences is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1258. Synonymous Sentences?
- The Python solution on this page runs in O(n^2).
- What is the space complexity of LeetCode 1258. Synonymous Sentences?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1258. Synonymous Sentences cover?
- LeetCode 1258. Synonymous Sentences is tagged Sort, Union Find, Array, Hash Table, String and Backtracking on LeetCode.
- Is LeetCode 1258. Synonymous Sentences a premium problem?
- Yes. LeetCode 1258. Synonymous Sentences is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.