Problem Description
Given a list of equivalent string pairs (synonyms) and a sentence, generate all possible synonymous sentences by replacing words with any of their equivalent synonyms. The final list of sentences must be sorted in lexicographical order.
Key Insights
- Use Union Find (or DFS) to group words that are synonyms.
- Map each group to its set of equivalent words, then sort each set for lexicographical order.
- For every word in the sentence, determine if it belongs to a synonym group. If so, consider all replacements; otherwise, use the word itself.
- Use backtracking to generate all possible sentence combinations.
- Finally, sort the list of sentences before returning.
Space and Time Complexity
Time Complexity: In the worst-case scenario, every word in the sentence may have up to O(k) synonyms, leading to O(k^w) combinations where w is the number of words. Additionally, union-find operations and sorting have relatively low overhead given the small constraints. Space Complexity: O(N + W) where N is the total number of synonyms and W is the number of words in the sentence, used to store the union-find structure, synonym groups, and the recursion stack.
Solution
We first use a union-find data structure to group synonyms such that any two words in the same group are equivalent. After union-find processing, we create a map from the representative of each group to a sorted list of all words in that group. For each word in the given sentence, if it belongs to a group of synonyms, we substitute it with each possible synonym; if not, it remains unchanged. We use backtracking to generate all possible sentences and then sort them lexicographically before returning.