Sentence Equivalence Under Transitive Synonyms
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
You receive a collection of two-word links synonym_pairs along with two pre-tokenized word lists, sentence_a and sentence_b. Implement are_sentences_equivalent(synonym_pairs, sentence_a, sentence_b) to decide whether the two word lists convey the same meaning.
Two tokenized sentences match when both requirements hold:
- Equal token count and fixed alignment:
sentence_aandsentence_bmust have the exact same length, and comparison happens strictly index by index (sentence_a[i]againstsentence_b[i], with no token reordering permitted). - Token-level equivalence at each index: For every index
i,sentence_a[i]andsentence_b[i]must either be the exact same string or belong to a shared synonym cluster built fromsynonym_pairs.
Synonym relationships obey three rules:
- Bidirectional: Listing
[u, v]once makesumatchvandvmatchu. - Chained (transitive): Whenever
ulinks tovandvlinks tow,uandwbelong to one merged cluster, even if[u, w]never appears directly. A single word can participate in multiple pairs, joining all reachable words into a single cluster. - Self-matching default: Any token that never appears in
synonym_pairsmatches itself and no other distinct token.
Return True if the sentences match at every position, or False otherwise.
Examples
Example 1
synonym_pairs = [["fast", "quick"], ["quick", "rapid"], ["calm", "quiet"]]
sentence_a = ["fast", "river", "calm"]
sentence_b = ["rapid", "river", "quiet"]
Output: True
Explanation: Both lists have length 3. At index 0, "fast" connects to "quick" and "quick" connects to "rapid", placing "fast" and "rapid" in the same cluster. At index 1, "river" equals "river" directly without needing any pair entry. At index 2, "calm" and "quiet" are directly paired.
Example 2
synonym_pairs = [["fast", "quick"], ["quick", "rapid"], ["calm", "quiet"]]
sentence_a = ["rapid", "stream", "quiet"]
sentence_b = ["fast", "brook", "quiet"]
Output: False
Explanation: Index 0 ("rapid" vs. "fast") and index 2 ("quiet" vs. "quiet") both match, but at index 1, "stream" and "brook" are different tokens absent from synonym_pairs, so they do not match.
Constraints
0 <= len(synonym_pairs) <= 100,000, where every element has the form[word_1, word_2].0 <= len(sentence_a), len(sentence_b) <= 100,000.- Every token in
synonym_pairs,sentence_a, andsentence_bis a lowercase string.
Step-by-step walkthrough
Understand the rules and aligned positions
We are given a list of
synonym_pairsand two tokenized word listssentence_aandsentence_b. Two word lists match only when both conditions hold:- Both contain the exact same number of tokens (alignment is fixed—index
ionly ever compares against indexi). - At every index
i,sentence_a[i]andsentence_b[i]are either the exact same token or linked through one or more pairs insynonym_pairs.
Each pair is bidirectional (
["calm", "quiet"]works in both directions) and chained (["fast", "quick"]plus["quick", "rapid"]joins"fast"and"rapid"into one shared cluster). Any token missing from all pairs matches only itself.Synonym pairs: ["fast", "quick"], ["quick", "rapid"], ["calm", "quiet"] Clusters formed: Cluster 1: fast <---> quick <---> rapid Cluster 2: calm <---> quiet Unlisted tokens ("river", "stream", "brook"): each stands alone Aligned check on Example 1: index: 0 1 2 sentence_a: "fast" "river" "calm" sentence_b: "rapid" "river" "quiet" | | | Cluster 1 equal Cluster 2 --> True- Both contain the exact same number of tokens (alignment is fixed—index
Why searching the graph per word position is too slow
If we treat every word as a graph node and every pair as an undirected edge, two words are synonyms whenever a path connects them. A straightforward brute-force approach builds an adjacency list and runs a fresh graph search from
sentence_a[i]looking forsentence_b[i]at every indexi.That logic gives the right answer, but it repeats massive work. With up to
P = 100,000pairs andn = 100,000words per sentence, one traversal across a large cluster can visit100,000words. Repeating that search across100,000positions can reach100,000 * 100,000 = 10^10steps—far too slow.Notice why that work is redundant: which words share a cluster depends strictly on
synonym_pairs, never on the sentences. Precomputing all clusters once turns each aligned token check into a tiny lookup.Key idea: precompute synonym clubs with Union-Find
In graph terminology, each isolated cluster of mutually reachable words is a connected component. We can maintain these components dynamically with a Union-Find (also called disjoint-set) data structure:
- Every known word in
parentpoints to a parent word in its cluster. - Following parent links eventually reaches a root (the cluster's representative), which points to itself (
parent[root] == root). - Two words belong to the same cluster if and only if both climb to the exact same root.
- When a pair
[first_word, second_word]bridges two separate clusters, we merge them in one step by pointing one root at the other.
Before pair ["quick", "rapid"]: fast (root, parent["fast"] = "fast") rapid (root, parent["rapid"] = "rapid") ^ | quick After merging "rapid" under "fast": fast (single shared root) / \ quick rapid- Every known word in
Helper 1: find a word's group leader iteratively
To find the leader of
word, we followparent[word]upward untilparent[word] == word. Writing an iterativewhileloop instead of recursion guarantees we can never hit Python's ~1,000-call recursion limit, even on100,000-link chains.While climbing, we add a one-line speedup called path halving: before stepping upward from
word, we re-pointworddirectly to its grandparentparent[parent[word]]. This stays safe even near the root, because a root's parent is itself (parent[root] == root).Before find_root("rapid"): During find_root("rapid"): fast (root) fast (root) ^ / \ quick quick rapid ^ ("rapid" skips straight to grandparent "fast") rapiddef find_root(parent: Dict[str, str], word: str) -> str: """Return the representative (root) word of `word`'s synonym group.""" # Follow parent links upward until we reach a root word that points to itself. while parent[word] != word: # Path halving: point `word` directly to its grandparent to flatten the tree, # making future lookups along this chain nearly constant time. grandparent = parent[parent[word]] parent[word] = grandparent word = grandparent return wordHelper 2: merge synonym pairs with union by size
Next we iterate through
synonym_pairsone pair at a time:- Register any previously unseen word as its own root with
group_size[word] = 1. - Look up
root_aandroot_b. Ifroot_a == root_b(which handles self-pairs like["x", "x"], duplicate pairs, and words already joined earlier), they already share a cluster, socontinue. - Otherwise, merge via union by size: attach the root of the smaller cluster under the root of the larger cluster, and add their sizes. Because a word's depth increases only when its cluster at least doubles in size, tree height never exceeds
log2(W)levels.
def build_synonym_groups(synonym_pairs: List[List[str]]) -> Dict[str, str]: """Group connected words with union-find and return the `parent` map.""" # parent: maps each known word -> its parent word in the forest (roots map to themselves), # e.g. {"fast": "fast", "quick": "fast", "rapid": "fast"}. parent: Dict[str, str] = {} # group_size: maps each root word -> number of words in that group, e.g. {"fast": 3}. group_size: Dict[str, int] = {} for first_word, second_word in synonym_pairs: # Phase 1: Register any newly seen word as its own group of size 1. for word in (first_word, second_word): if word not in parent: parent[word] = word group_size[word] = 1 # Phase 2: Find the current group leaders of both words. root_a = find_root(parent, first_word) root_b = find_root(parent, second_word) # Self-pairs (["x", "x"]) or pairs already in the same group need no merge. if root_a == root_b: continue # Union by size: attach the smaller group under the larger group's root # so tree height stays at most O(log W) even before path halving helps. if group_size[root_a] < group_size[root_b]: root_a, root_b = root_b, root_a parent[root_b] = root_a group_size[root_a] += group_size[root_b] return parent- Register any previously unseen word as its own root with
Compare the sentences position by position and trace Example 2
Once
parentis ready,are_sentences_equivalentevaluates four checks in exact order:- Length mismatch (
len(sentence_a) != len(sentence_b)): returnFalseimmediately before touching any pairs. Never rely onzipalone, becausezipsilently stops at the shorter list. - Exact string match (
word_a == word_b):continue. Checking string equality before touchingparentis vital: tokens like"river"or"quiet"match themselves even when absent fromparent. - Unlisted word (
word_a not in parent or word_b not in parent): sinceword_a != word_b, if either word never appeared insynonym_pairs, they cannot match—returnFalse(this also avoids aKeyErrorinfind_root). - Different cluster leaders (
find_root(parent, word_a) != find_root(parent, word_b)): returnFalse.
If every index passes, return
True.def are_sentences_equivalent(synonym_pairs: List[List[str]], sentence_a: List[str], sentence_b: List[str]) -> bool: # Sentences with different word counts can never match position by position. if len(sentence_a) != len(sentence_b): return False parent = build_synonym_groups(synonym_pairs) # Compare aligned words at index 0, 1, ..., len(sentence_a) - 1. for word_a, word_b in zip(sentence_a, sentence_b): # Check exact equality BEFORE looking up `parent`: every word matches itself, # even if it never appeared in `synonym_pairs` (and would raise KeyError in `parent`). if word_a == word_b: continue # Different words where either is absent from all pairs cannot match, # because an unknown word is equivalent only to itself. if word_a not in parent or word_b not in parent: return False # Both words are known; they are synonyms iff they share the same group root. if find_root(parent, word_a) != find_root(parent, word_b): return False return TrueLet's trace Example 2 (
synonym_pairs = [["fast", "quick"], ["quick", "rapid"], ["calm", "quiet"]]):Clusters built: "fast", "quick", "rapid" -> root "fast" "calm", "quiet" -> root "calm" Aligned trace for sentence_a = ["rapid", "stream", "quiet"], sentence_b = ["fast", "brook", "quiet"]: idx word_a word_b Rule triggered Outcome --- -------- ------- -------------------------------------------- ----------------- 0 "rapid" "fast" both in parent; root("rapid") == root("fast") keep going 1 "stream" "brook" not equal, and "stream" not in parent return False! 2 "quiet" "quiet" (never reached because idx 1 returned False)- Length mismatch (
Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def find_root(parent: Dict[str, str], word: str) -> str: """Return the representative (root) word of `word`'s synonym group.""" # Follow parent links upward until we reach a root word that points to itself. while parent[word] != word: # Path halving: point `word` directly to its grandparent to flatten the tree, # making future lookups along this chain nearly constant time. grandparent = parent[parent[word]] parent[word] = grandparent word = grandparent return word def build_synonym_groups(synonym_pairs: List[List[str]]) -> Dict[str, str]: """Group connected words with union-find and return the `parent` map.""" # parent: maps each known word -> its parent word in the forest (roots map to themselves), # e.g. {"fast": "fast", "quick": "fast", "rapid": "fast"}. parent: Dict[str, str] = {} # group_size: maps each root word -> number of words in that group, e.g. {"fast": 3}. group_size: Dict[str, int] = {} for first_word, second_word in synonym_pairs: # Phase 1: Register any newly seen word as its own group of size 1. for word in (first_word, second_word): if word not in parent: parent[word] = word group_size[word] = 1 # Phase 2: Find the current group leaders of both words. root_a = find_root(parent, first_word) root_b = find_root(parent, second_word) # Self-pairs (["x", "x"]) or pairs already in the same group need no merge. if root_a == root_b: continue # Union by size: attach the smaller group under the larger group's root # so tree height stays at most O(log W) even before path halving helps. if group_size[root_a] < group_size[root_b]: root_a, root_b = root_b, root_a parent[root_b] = root_a group_size[root_a] += group_size[root_b] return parent def are_sentences_equivalent(synonym_pairs: List[List[str]], sentence_a: List[str], sentence_b: List[str]) -> bool: # Sentences with different word counts can never match position by position. if len(sentence_a) != len(sentence_b): return False parent = build_synonym_groups(synonym_pairs) # Compare aligned words at index 0, 1, ..., len(sentence_a) - 1. for word_a, word_b in zip(sentence_a, sentence_b): # Check exact equality BEFORE looking up `parent`: every word matches itself, # even if it never appeared in `synonym_pairs` (and would raise KeyError in `parent`). if word_a == word_b: continue # Different words where either is absent from all pairs cannot match, # because an unknown word is equivalent only to itself. if word_a not in parent or word_b not in parent: return False # Both words are known; they are synonyms iff they share the same group root. if find_root(parent, word_a) != find_root(parent, word_b): return False return True✅ Submit now — all tests should pass.
Intuition & how it works
Think of synonym clusters like clubs where every club elects one official "club leader" word. Whenever a pair tells us two words share a meaning, we merge their two clubs under a single leader. Once all clubs are formed from the pair list, comparing two sentences is just walking across both word lists finger-by-finger and checking that each aligned pair of words is either identical or wears the same club leader badge.
A naive solution either stores only direct pairs in a hash set or runs a fresh graph search from sentence_a[i] to sentence_b[i] at every index. Checking direct pairs alone breaks on multi-hop chains like fast -> quick -> rapid, because "fast" and "rapid" never appear together in a single pair. Running a fresh search at each of 100,000 positions handles chains, but it can re-traverse 100,000 pairs again and again—up to 10 billion operations in the worst case.
We get both speed and transitivity with a Union-Find (also called a disjoint-set) data structure, which maintains non-overlapping clusters where each item points toward a cluster leader called its root. Trace Example 1 with synonym_pairs = [["fast", "quick"], ["quick", "rapid"], ["calm", "quiet"]], sentence_a = ["fast", "river", "calm"], and sentence_b = ["rapid", "river", "quiet"]:
- Pair
["fast", "quick"]places both words under leader"fast". - Pair
["quick", "rapid"]finds"quick"'s leader ("fast") and attaches"rapid"under"fast"as well; pair["calm", "quiet"]puts"quiet"under"calm". - At index
0,"fast"and"rapid"both resolve to leader"fast"(match!). - At index
1,"river"equals"river"directly even though"river"never appeared insynonym_pairs; at index2,"calm"and"quiet"both resolve to"calm"—returningTrue.
Complexity
Let P be the number of entries in synonym_pairs, W (at most 2 * P) be the number of distinct words across those pairs, and n be the length of each sentence (treating dictionary hashing of short lowercase strings as O(1)).
- Time:
O((P + n) * α(W)), which behaves likeO(P + n)in practice. Hereα(W)is the inverse Ackermann function, a mathematical function that grows so slowly it never exceeds5for any realistic input size. Building the clusters processesPpairs (doing two root lookups and at most one merge per pair), and comparing the sentences scansnpositions (doing at most two root lookups per position). Combining union by size (always hanging the smaller tree under the larger tree's root) with path halving (pointing each visited node straight to its grandparent) makes each lookup nearly constant amortized time—meaning the average cost per operation across the whole run is tiny even if an individual lookup climbs a few links. When sentence lengths differ, the function returnsFalseinO(1)time before touching any pairs. - Space:
O(W)to store one entry per distinct paired word inparentandgroup_size. Tokens appearing only inside the sentences are compared in place without allocating extra dictionary entries.
Edge cases
- Different sentence lengths: returns
Falseimmediately, even when one sentence is a prefix of the other or empty. - Both sentences empty (
[]and[]): returnsTrue, since their lengths match and zero indices disagree. - Identical tokens absent from all pairs: returns
Trueat that index because every word matches itself. - Distinct tokens where either is absent from all pairs: returns
False, because unlisted words never match any other word. - Bidirectional and chained pairs:
[["a", "b"], ["c", "b"]]links"a"and"c"regardless of pair ordering. - Self-pairs and duplicate pairs: entries like
["x", "x"]or repeated["x", "y"]findroot_a == root_band skip merging without inflatinggroup_size. - Deep chains of
100,000pairs: handled safely by an iterativewhileloop without hitting Python's recursion limit. - Same words in swapped positions:
["quick", "fox"]vs.["fox", "fast"]returnsFalse, since matching is strictly index-aligned.
Common mistakes
- Treating pairs as one-way edges: recording only
synonyms[a].add(b)missesb -> awhen[a, b]was listed once. - Checking only direct pairs: fails on multi-step chains like
fast -> quick -> rapidwhere two synonyms are connected via intermediate words. - Looking up
parent[word]before checkingword_a == word_b: tokens absent fromsynonym_pairsare missing fromparent, so callingfind_rooton"river"vs."river"crashes with aKeyError(or falsely rejects identical unlisted tokens). - Skipping the length check before
zip: Python'szip(sentence_a, sentence_b)stops at the shorter list, falsely accepting["hi"]against["hi", "there"]. - Using recursive
find_rootwithout balancing: a chain of100,000pairs can overflow Python's call stack withRecursionError.
Alternative approaches
- Connected components via BFS or DFS: Breadth-first search (BFS) explores a graph layer by layer with a queue, whereas depth-first search (DFS) explores along one branch as deep as possible with a stack. You can build an undirected adjacency list from
synonym_pairs, run one iterative BFS/DFS from each unvisited word to assign an integercomponent_idto every word in that component, and comparecomponent_ids at each sentence index. That takesO(W + P + n)time andO(W + P)space; Union-Find uses slightly less memory (O(W)with no adjacency lists) and naturally accepts incremental pair insertions later. - Canonical sentence transformation: define the canonical form of a word (its single standardized cluster representative) as
find_root(parent, w)ifw in parentelsew, transform both sentences into canonical word lists, and checkcanon_a == canon_b. It performs the same asymptotic work, though checking index by index in a loop exits early on the first mismatch without allocating twon-word lists.
Follow-up questions
- How would the algorithm simplify if only direct synonym pairs matched and chains did not? Drop Union-Find altogether and insert each pair
[u, v]into a hash set as(u, v)and(v, u)(or normalized sorted tuples(min(u, v), max(u, v))). At each indexi, two tokens match ifword_a == word_bor(word_a, word_b)belongs to the set, running inO(P + n)time andO(P)space. - How would you support a live stream of new synonym pairs interleaved with millions of sentence checks? Persist
parentandgroup_sizeon a service object across calls: each incoming pair performs a singleO(α(W))union without rebuilding prior clusters, and each sentence comparison runs inO(n * α(W))time. Standard Union-Find supports additions only; if pair deletions were also required, you would maintain an explicit edge multiset and recompute affected components upon edge removal. - How would you partition a batch of 50,000 sentences into equivalence classes? Build the Union-Find structure once from
synonym_pairs, convert every sentence into its canonical tupletuple(find_root(parent, w) if w in parent else w for w in sentence), and group sentences in a dictionary keyed by that tuple. Equivalent sentences map to the exact same canonical tuple, clustering the entire batch in time linear in the total token count rather than comparing all pairs of sentences.
Follow-up questions
- How would the algorithm simplify if only direct synonym pairs matched and chains did not?
- How would you support a live stream of new synonym pairs interleaved with millions of sentence checks?
- How would you partition a batch of 50,000 sentences into equivalence classes?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array