Skip to main content

Synonymous Sentences - Solution & Explanation

MediumPremiumFree on FleetCodeArrayHash TableStringBacktracking12 min readAsked at: Rippling, Cruise Automation, Moveworks
Practice this problem

Problem Statement

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.

Approach Overview

Problem Overview: You are given pairs of synonymous words and a sentence. Replace words with their synonyms to generate every possible sentence variation. The final output must contain all valid sentences sorted lexicographically.

Approach 1: Graph + Backtracking (Time: O(G + S * K^L), Space: O(G + L))

Model synonyms as an undirected graph using a hash table. Each word is a node and each synonym pair forms an edge. Traverse the graph with DFS or BFS to collect all words connected to a given synonym group. While processing the sentence, if a word appears in the graph, replace it with every synonym in its connected component and recursively build sentences using backtracking. This approach directly explores all combinations but repeatedly traverses synonym groups unless cached.

Approach 2: Union-Find + DFS (Time: O(P α(P) + C log C), Space: O(P + C))

Use Union-Find to group synonymous words efficiently. Each pair is unioned so all related words share the same root. After building groups, map each root to a sorted list of synonyms. While constructing sentences, iterate through the input words: if a word belongs to a synonym group, branch into every candidate word from that group and continue recursively using DFS. Sorting each group ensures the final results are generated in lexicographic order without an additional global sort. Union-Find avoids repeated graph traversal and handles large synonym networks efficiently.

Recommended for interviews: Union-Find + DFS is the expected solution. It separates two concerns cleanly: grouping synonyms with Union-Find and generating combinations with DFS. A basic graph + backtracking approach shows you understand the synonym connectivity, but the Union-Find version demonstrates stronger algorithmic design and scales better when the synonym list grows.

Solution

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(n^2), and the space complexity is O(n). Where n is the number of words.

Code

Python

Java

C++

Go

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Graph Traversal + BacktrackingO(G + S * K^L)O(G + L)Useful when modeling synonym relationships directly as a graph and the synonym network is small.
Union-Find + DFSO(P α(P) + C log C)O(P + C)Best general solution. Efficiently groups synonyms and generates combinations in lexicographic order.

Video Solution

1258 Synonymous Sentences (Biweekly Contest 13)Kelvin Chandra2,648 views views

Watch 5 more video solutions →

Frequently Asked Questions

Is Synonymous Sentences easy or hard?
Synonymous Sentences is usually classified as a medium difficulty problem. The challenge comes from combining two ideas: grouping words using Union-Find and generating all sentence permutations using DFS or backtracking.
Synonymous Sentences Python/Java solution
A typical implementation builds a Union-Find structure for all synonym pairs, maps each root to a sorted list of words, and then runs DFS over the sentence. Python, Java, C++, and Go implementations follow the same pattern: union operations for grouping and recursive generation for sentence combinations.
How to solve Synonymous Sentences in O(n)?
Building synonym groups with Union-Find is close to linear time because each union and find operation runs in nearly O(1) amortized time. After grouping, DFS or backtracking generates sentences by iterating through synonym lists for each word position. The combination generation dominates the runtime when many substitutions exist.
What is the best approach for Synonymous Sentences?
Union-Find combined with DFS is the most efficient approach. Union-Find groups all related synonyms into connected components in near O(1) amortized time per union operation. DFS or backtracking then generates every valid sentence combination by replacing words with others from the same synonym group.
Is Synonymous Sentences asked at Google/Amazon/Meta?
Variants of synonym grouping and sentence generation appear in interviews at companies like Google, Amazon, and Meta. The problem tests knowledge of Union-Find, graph connectivity, and recursive backtracking for generating combinations.
What data structure is used in Synonymous Sentences?
Union-Find (Disjoint Set Union) is commonly used to group synonyms efficiently. A hash map stores the mapping from group root to all words in that synonym set, and DFS/backtracking generates the possible sentences. Arrays or lists store the final combinations.
What is the time complexity of Synonymous Sentences?
The Union-Find setup takes roughly O(P α(P)) where P is the number of synonym pairs and α is the inverse Ackermann function. Generating sentences depends on the number of combinations, which can grow exponentially with the number of replaceable words. Sorting synonym groups typically adds O(C log C).

Ready to solve this problem?

Practice Synonymous Sentences with our built-in code editor and test cases.

Practice on FleetCode