MediumArrayHash TableStringBacktrackingSortingUnion FindUpdated Sep 2026

1258. Synonymous Sentences

Asked at Rippling

Difficulty

Medium

Time

O(n * m + R log R)

Space

O(n + R * m)

Pattern

Array

Companies

1

Problem

You are given a list of synonym pairs synonyms and a sentence text. Each pair [a, b] means the words a and b can be used in place of each other. This relation is transitive: if a equals b and b equals c, then all three words belong to the same group.

For every word in the sentence, you may keep it or swap it with any other word from its synonym group. Words that appear in no pair have only one choice: themselves.

Return all possible sentences you can build this way, as a list of strings, sorted in lexicographical order. Each sentence keeps the same number of words, separated by single spaces. A word that is not in any synonym pair must stay unchanged.

Words that can be swapped

textIamhappytodaybutwassadyesterday01234567Orange positions are the only ones with alternative words.group of happycheerfulhappyjoyhappy, joy and cheerful are all connected through the pairs, so they form onegroup.group of sadsadsorrowsad and sorrow form a second, separate group.
The sentence has 8 positions, but only "happy" and "sad" have synonyms, so only those two positions can change.

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

Examples

Example 1
Inputsynonyms = [["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
WhyThe pairs link happy, joy and cheerful into one group, and sad with sorrow into another. So the word "happy" has 3 choices and "sad" has 2 choices, giving 3 × 2 = 6 sentences. The other words have no synonyms and never change.
Example 2
Inputsynonyms = [["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"]
WhyHere happy and joy form one group, and cheerful and glad form a separate group. Only "happy" appears in the sentence, so only 2 sentences are possible. "cheerful" and "glad" are never used.

Asked At

1 companies
CompanyDifficulty
RipplingMediumView all Rippling questions →

How to Think About It

1

Build a graph where each synonym pair is an undirected edge between words

2

Use Union-Find or DFS to group all words that are synonyms into connected components

3

For each word in the input sentence, find all words in its synonym group including itself

4

Use backtracking to generate all combinations by picking one word from each group

5

Sort the final result lexicographically before returning

Optimal Approach

Build a graph from synonym pairs and use DFS or Union-Find to find connected components (synonym groups). For each word in the input sentence, look up its group. Use backtracking to generate all sentences by recursively choosing one synonym from each word position. At each position, iterate through all words in the synonym group (including the original word) and recurse to the next position. Collect all generated sentences and sort them lexicographically. The key insight is treating synonyms as an equivalence relation that partitions words into groups.

Union-Find groups, then backtracking

union each paircollect groups by rootsort each groupbacktrack over wordssort all sentencesThe pipeline: build groups first, then generate andsort the sentences.choices at 'happy'cheerfulhappyjoyBacktracking picks one word from this list, then movesto the next position.choices at 'sad'sadsorrowAt the 'sad' position, the algorithm again tries eachword in its group.root = find(word)candidates = groups[root] or [word]recurse on next word, then undo
First merge words into groups, then try every word from each group position by position.
ComplexityTime O(n * m + R log R)Space O(n + R * m)n is the number of words in the sentence, m is the largest synonym group size, and R is the number of resulting sentences; the log R comes from sorting the output.

What Trips People Up in Real Interviews

1

Clarify that synonyms are transitive (if A=B and B=C then A=C)

2

Ask if the output must be sorted (typically yes for this problem)

3

Discuss Union-Find vs DFS for building synonym groups

4

Mention that empty synonyms list means no replacement possible for that word

5

Talk about edge case where a word appears multiple times in the sentence

Solution Code

O(n * m + R log R) time
from collections import defaultdict

class Solution:
    def generateSentences(self, synonyms: list[list[str]], text: str) -> list[str]:
        parent = {}

        def find(x):
            if x not in parent:
                parent[x] = x
            while parent[x] != x:
                parent[x] = parent[parent[x]]
                x = parent[x]
            return x

        def union(a, b):
            ra, rb = find(a), find(b)
            if ra != rb:
                if ra < rb:
                    parent[ra] = rb
                else:
                    parent[rb] = ra

        for a, b in synonyms:
            union(a, b)

        groups = defaultdict(list)
        for word in list(parent.keys()):
            groups[find(word)].append(word)

        for g in groups:
            groups[g].sort()

        words = text.split(' ')
        result = []

        def backtrack(i, current):
            if i == len(words):
                result.append(' '.join(current))
                return
            w = words[i]
            root = find(w) if w in parent else w
            candidates = groups.get(root, [w])
            for syn in candidates:
                current.append(syn)
                backtrack(i + 1, current)
                current.pop()

        backtrack(0, [])
        result.sort()
        return result

Pro at DSA?

Test your skills with a real FAANG-style mock interview.

Start a Mock Interview →

Frequently Asked Questions

What is the Synonymous Sentences problem?

Given a list of synonymous word pairs and a sentence, generate all possible sentences by replacing words with their synonyms. Each synonymous group forms an equivalence class, and you must produce every valid combination by substituting words within the same group. Return the sentences sorted in lexicographical order.

How do you solve Synonymous Sentences?

The optimal approach runs in O(n * m + R log R) time and O(n + R * m) space. Scroll up to "Optimal Approach" for the step-by-step walkthrough, diagrams, and code in Python, C++ and Java.

What companies ask Synonymous Sentences?

Synonymous Sentences is asked at Rippling. It is a medium difficulty problem.

What are common mistakes on Synonymous Sentences?
  • Clarify that synonyms are transitive (if A=B and B=C then A=C)
  • Ask if the output must be sorted (typically yes for this problem)
  • Discuss Union-Find vs DFS for building synonym groups
  • Mention that empty synonyms list means no replacement possible for that word
  • Talk about edge case where a word appears multiple times in the sentence