Synonymous Sentences Problem
Description
LeetCode Problem 1258.
You are given a list of equivalent string pairs synonyms where synonyms[i] = [s_i, t_i] indicates that s_i and t_i 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 <= 10synonyms[i].length == 21 <= s_i.length,t_i.length <= 10s_i != t_itextconsists of at most10words.- All the pairs of
synonymsare unique. - The words of
textare separated by single spaces.
Solution
Approach: Union-Find, Then Try Every Choice
Synonymy is transitive here: in Example 1, happy ~ joy and joy ~ cheerful make happy, joy and cheerful all interchangeable. So the words split into groups, and any word of a group can replace any other.
- Group the words with union-find. Each word starts as its own root. For each pair
[s, t], join the roots ofsandt. Then collect every word under its root. - Build every sentence by backtracking. Split
textinto words.build(i)chooses a word for positioni: ifwords[i]is in some group, every word of that group is an option, otherwise the only option is the word itself. When all positions are chosen, join them with spaces and record the sentence. - Sort the sentences, since the answer must be in lexicographic order.
The tricky case is the second example: cheerful ~ glad forms its own group, but neither word is in the text, so it adds nothing. Only words that appear in some pair have alternatives, and a word with no pair stays as it is.
Complexity: O(S · L · log S) time for building and sorting, where S is the number of sentences produced and L their length, plus near-linear time for the union-find. The output takes O(S · L) space.
class Solution:
def generateSentences(self, synonyms: List[List[str]], text: str) -> List[str]:
# Union-find: synonyms are transitive, so each connected group of words is interchangeable.
parent = {}
def find(x: str) -> str:
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for a, b in synonyms:
parent.setdefault(a, a)
parent.setdefault(b, b)
parent[find(a)] = find(b)
group = {} # root -> every word in its group
for w in parent:
group.setdefault(find(w), []).append(w)
words = text.split(" ")
sentences, chosen = [], []
def build(i: int) -> None:
if i == len(words):
sentences.append(" ".join(chosen))
return
options = group[find(words[i])] if words[i] in parent else [words[i]]
for w in options:
chosen.append(w)
build(i + 1)
chosen.pop()
build(0)
return sorted(sentences)