Synonymous Sentences - Problem

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.

A synonymous sentence is formed by replacing zero or more words in the original sentence with their synonyms.

Input & Output

Example 1 — Basic Synonyms
$ Input: synonyms = [["happy","joy"],["sad","sorrow"],["joy","cheerful"]], text = "I am happy today"
Output: ["I am cheerful today","I am happy today","I am joy today"]
💡 Note: The word 'happy' can be replaced with 'joy' or 'cheerful' (since happy↔joy↔cheerful are all connected). The other words remain unchanged.
Example 2 — Multiple Words with Synonyms
$ Input: synonyms = [["happy","joy"],["cheerful","content"]], text = "I am happy today"
Output: ["I am happy today","I am joy today"]
💡 Note: Only 'happy' has synonyms in this case. The pairs [happy,joy] and [cheerful,content] are separate groups since they're not connected.
Example 3 — No Synonyms Found
$ Input: synonyms = [["a","b"],["c","d"]], text = "I like coding"
Output: ["I like coding"]
💡 Note: None of the words in the sentence have synonyms in the given list, so only the original sentence is returned.

Constraints

  • 0 ≤ synonyms.length ≤ 10
  • synonyms[i].length == 2
  • 1 ≤ synonyms[i][j].length, text.length ≤ 10
  • synonyms[i][0] ≠ synonyms[i][1]
  • text consists of at most 10 words

Visualization

Tap to expand
Synonymous Sentences INPUT Synonym Pairs (Graph) happy joy cheerful sad sorrow Input Text: "I am happy today" ALGORITHM STEPS 1 Union-Find Setup Group synonyms into sets Set1: {happy, joy, cheerful} Set2: {sad, sorrow} 2 Parse Sentence Split into words I am happy today 3 Find Replacements "happy" has synonyms happy --> cheerful, happy, joy 4 Generate All Cartesian product, sort Use BFS/DFS + Backtracking FINAL RESULT All Synonymous Sentences: "I am cheerful today" "I am happy today" "I am joy today" Output Array: [ "I am cheerful today", "I am happy today", "I am joy today" OK - SORTED 3 sentences generated Key Insight: Use Union-Find to group all synonymous words into equivalence classes. For each word in the sentence, if it belongs to a synonym group, replace it with ALL words in that group. Generate all combinations using backtracking, then sort lexicographically. Time: O(n * k^m) where k=avg synonyms. TutorialsPoint - Synonymous Sentences | Optimal Solution (Union-Find + Backtracking)
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
23.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen