Compare Sentences Using Transitive Synonym Groups
Read.AiSoftware Engineer · Technical ScreenLast updated
Compare two tokenized sentences using undirected, transitive synonym relationships. Sentence lengths and word positions must match, while a union-find or graph traversal groups chained synonyms and leaves unknown words equivalent only to themselves.
Problem
Given synonym pairs and two tokenized sentences, return whether the sentences are equivalent. They are equivalent only if they have the same number of words and every pair of words at the same position is either identical or connected through one or more synonym pairs. Synonymy is undirected and transitive.
Constraints & Assumptions
- There are at most 100,000 synonym pairs.
- Each sentence contains at most 100,000 lowercase words.
- A word may appear in several pairs and form a larger synonym group.
- Words absent from all pairs are equivalent only to themselves.
Clarifications
- Sentence word order cannot change.
- Synonym pairs are symmetric even if listed once.
- Transitive chains such as
hit -> hits -> hittedbelong to one group.
Examples
pairs = [["flat", "flatting"], ["hit", "hits"], ["hits", "hitted"]]
a = ["flat", "the", "word"]
b = ["flatting", "the", "word"]
output = true
a = ["hit", "the", "click"]
b = ["hitted", "one", "click"]
output = false
Hints
Hints
Hint 1
Build components: Treat words as vertices and synonym pairs as undirected connections.
Hint 2
Compare aligned tokens: After grouping synonyms, sentence equivalence is a position-by-position check.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.