Similar Problems

Similar Problems not available

Synonymous Sentences - Leetcode Solution

Companies:

LeetCode:  Synonymous Sentences Leetcode Solution

Difficulty: Medium

Topics: hash-table union-find string array backtracking  

The Synonymous Sentences problem on Leetcode can be solved using a graph-based approach. The problem statement is as follows:

Given a list of pairs of synonyms synonyms and a sentence text, return all the possible synonymous sentences which can be formed from text using the given synonyms.

For example, if synonyms = [["happy","joy"],["sad","sorrow"],["joy","cheerful"]] and text = "I am happy today but was sad yesterday", the output would be:

["I am joy today but was sorrow yesterday", "I am cheerful today but was sad yesterday"]

To solve this problem, we can first create a graph where each word is a node and the synonyms are edges between them. We can use a dictionary to store this graph where the keys are the nodes and the values are lists of synonyms. We can use the given synonyms list to create this graph.

Next, we can tokenize the given text and perform a depth-first search (DFS) on each node in the tokenized text. For each node, we can explore the synonyms using the graph we created earlier and generate all possible combinations of synonymous sentences. We can use a set to avoid duplicates while generating synonymous sentences.

Finally, we can return all the generated synonymous sentences.

Here is the Python implementation of the above approach:

from collections import defaultdict

class Solution:
    def generateSentences(self, synonyms: List[List[str]], text: str) -> List[str]:
        graph = defaultdict(set)
        # create graph
        for u, v in synonyms:
            graph[u].add(v)
            graph[v].add(u)
        
        def dfs(node, sentence, result):
            # if node is not in graph, add current sentence to result
            if node not in graph:
                result.add(" ".join(sentence))
                return
            # explore synonyms of node
            for neighbor in graph[node]:
                dfs(neighbor, sentence + [neighbor], result)
        
        result = set()
        tokens = text.split()
        # perform dfs on each node in tokenized text
        for i, token in enumerate(tokens):
            dfs(token, [token], result)
        
        return sorted(list(result))

Time Complexity: The time complexity of the above approach is O(n * s), where n is the number of tokens in the given text and s is the size of the synonyms list (to create the graph).

Space Complexity: The space complexity of the above approach is O(s + n), where s is the size of the synonyms list (to create the graph) and n is the number of tokens in the given text (for the DFS call stack and the set to store resulting sentences).

Synonymous Sentences Solution Code

1