Ctrl K

Every Rewording of a Sentence

Medium
An editor wants to see every way a sentence can be reworded using a synonym dictionary. You are given a list pairs, where each pair [x, y] means the words x and y are interchangeable. Synonymy is transitive: if x can stand in for y and y for z, then x can stand in for z too. You are also given sentence, a sequence of words separated by single spaces. Any word of the sentence that has synonyms may be replaced by any word from its group (or kept as is); all other words stay unchanged. Return every distinct sentence obtainable this way, sorted lexicographically as strings.
Example 1
pairs=[["quick", "fast"], ["fast", "rapid"]], sentence="a quick fix" → ['a fast fix', 'a quick fix', 'a rapid fix']

quick, fast and rapid form one synonym group, so there are three sentences, listed in alphabetical order.

Example 2
pairs=[["big", "huge"], ["old", "ancient"]], sentence="big old house" → ['big ancient house', 'big old house', 'huge ancient house', 'huge old house']

Two independent swaps give 2 × 2 = 4 variants.

Example 3
pairs=[], sentence="nothing to swap" → ['nothing to swap']
Constraints
  • 0 ≤ len(pairs) ≤ 10
  • len(pairs[i]) == 2, and the two words differ
  • 1 ≤ length of a word in a pair ≤ 20
  • No pair appears twice
  • sentence has 1 to 20 words separated by single spaces
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsMerge Contact Cards MediumChains of Synonyms MediumRearrange Through Links MediumAn Unused Bit String MediumEvery Way to Space the Words Hard
loading Python…
Input
pairs=[["quick", "fast"], ["fast", "rapid"]], sentence="a quick fix"
Expected
['a fast fix', 'a quick fix', 'a rapid fix']

Run checks the first 3 tests in your browser. Submit checks all 126 tests on the server, hidden ones included.