LeetCode 1258, Medium. Topics: Sort, Union Find, Array, Hash Table, String, Backtracking. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 20 parametrized pytest cases, and a playground notebook:
Problem
You are given a list of equivalent string pairs synonyms where synonyms[i] = [s<sub>i</sub>, t<sub>i</sub>] indicates that s<sub>i</sub> and t<sub>i</sub> are equivalent strings. You are also given a sentence text.
Return all possible synonymous sentences sorted lexicographically.
Examples
Constraints
0 <= synonyms.length <= 10
synonyms[i].length == 2
1 <= s<sub>i</sub>.length, t<sub>i</sub>.length <= 10
s<sub>i</sub> != t<sub>i</sub>
text consists of at most 10 words.
- All the pairs of
synonyms are unique.
- The words of
text are separated by single spaces.
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
NeetCode All. Last modified on September 7, 2026