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: Generate All VariationsInput Synonyms[["happy","joy"],["joy","cheerful"]]Original Sentence"I am happy today"Synonym Groupshappy ↔ joy ↔ cheerfulI, am, today (no synonyms)Generate All CombinationsReplace "happy" with: happy, joy, cheerfulKeep other words unchangedOutput: ["I am cheerful today", "I am happy today", "I am joy today"]
Understanding the Visualization
1
Input
Synonym pairs and original sentence
2
Process
Find all words that can be replaced with synonyms
3
Output
All possible sentences sorted lexicographically
Key Takeaway
🎯 Key Insight: Group transitively connected synonyms, then generate all combinations systematically
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