LeetCode 1258. Synonymous Sentences Solution in Java, C++, Python & Go | Explanation + Code

CoderIndeed
0
1258. Synonymous Sentences

Description

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.

Return all possible synonymous sentences sorted lexicographically.

 

Example 1:

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"]

Example 2:

Input: synonyms = [["happy","joy"],["cheerful","glad"]], text = "I am happy today but was sad yesterday"
Output: ["I am happy today but was sad yesterday","I am joy today but was sad yesterday"]

 

Constraints:

  • 0 <= synonyms.length <= 10
  • synonyms[i].length == 2
  • 1 <= si.length, ti.length <= 10
  • si != ti
  • text consists of at most 10 words.
  • All the pairs of synonyms are unique.
  • The words of text are separated by single spaces.

Solutions

Solution 1: Union-Find + DFS

We can notice that the synonyms in the problem are transitive, i.e., if a and b are synonyms, and b and c are synonyms, then a and c are also synonyms. Therefore, we can use a union-find set to find the connected components of synonyms, where all the words in each connected component are synonyms and are sorted in lexicographical order.

Next, we split the string text into a word array sentence by spaces. For each word sentence[i], if it is a synonym, we replace it with all the words in the connected component, otherwise, we do not replace it. In this way, we can get all the sentences. This can be implemented by DFS search.

We design a function dfs(i), which represents starting from the ith word of sentence, replacing it with all the words in the connected component, and then recursively processing the following words.

If i is greater than or equal to the length of sentence, it means that we have processed all the words, and at this time, we add the current sentence to the answer array. Otherwise, if sentence[i] is not a synonym, we do not replace it, directly add it to the current sentence, and then recursively process the following words. Otherwise, we replace sentence[i] with all the words in the connected component, and also recursively process the following words.

Finally, return the answer array.

The time complexity is O(n2), and the space complexity is O(n). Where n is the number of words.

PythonJavaC++Go
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(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !