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:

  1. Equal token count and fixed alignment: sentence_a and sentence_b must have the exact same length, and comparison happens strictly index by index (sentence_a[i] against sentence_b[i], with no token reordering permitted).
  2. Token-level equivalence at each index: For every index i, sentence_a[i] and sentence_b[i] must either be the exact same string or belong to a shared synonym cluster built from synonym_pairs.

Synonym relationships obey three rules:

  • Bidirectional: Listing [u, v] once makes u match v and v match u.
  • Chained (transitive): Whenever u links to v and v links to w, u and w belong 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_pairs matches 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, and sentence_b is a lowercase string.

Step-by-step walkthrough

  1. Understand the rules and aligned positions

    We are given a list of synonym_pairs and two tokenized word lists sentence_a and sentence_b. Two word lists match only when both conditions hold:

    1. Both contain the exact same number of tokens (alignment is fixed—index i only ever compares against index i).
    2. At every index i, sentence_a[i] and sentence_b[i] are either the exact same token or linked through one or more pairs in synonym_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
    
  2. 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 for sentence_b[i] at every index i.

    That logic gives the right answer, but it repeats massive work. With up to P = 100,000 pairs and n = 100,000 words per sentence, one traversal across a large cluster can visit 100,000 words. Repeating that search across 100,000 positions can reach 100,000 * 100,000 = 10^10 steps—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.

  3. 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 parent points 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
    
  4. Helper 1: find a word's group leader iteratively

    To find the leader of word, we follow parent[word] upward until parent[word] == word. Writing an iterative while loop instead of recursion guarantees we can never hit Python's ~1,000-call recursion limit, even on 100,000-link chains.

    While climbing, we add a one-line speedup called path halving: before stepping upward from word, we re-point word directly to its grandparent parent[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")
      rapid
    
    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
    
  5. Helper 2: merge synonym pairs with union by size

    Next we iterate through synonym_pairs one pair at a time:

    1. Register any previously unseen word as its own root with group_size[word] = 1.
    2. Look up root_a and root_b. If root_a == root_b (which handles self-pairs like ["x", "x"], duplicate pairs, and words already joined earlier), they already share a cluster, so continue.
    3. 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
    
  6. Compare the sentences position by position and trace Example 2

    Once parent is ready, are_sentences_equivalent evaluates four checks in exact order:

    1. Length mismatch (len(sentence_a) != len(sentence_b)): return False immediately before touching any pairs. Never rely on zip alone, because zip silently stops at the shorter list.
    2. Exact string match (word_a == word_b): continue. Checking string equality before touching parent is vital: tokens like "river" or "quiet" match themselves even when absent from parent.
    3. Unlisted word (word_a not in parent or word_b not in parent): since word_a != word_b, if either word never appeared in synonym_pairs, they cannot match—return False (this also avoids a KeyError in find_root).
    4. Different cluster leaders (find_root(parent, word_a) != find_root(parent, word_b)): return False.

    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 True
    

    Let'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)
    
  7. 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"]:

  1. Pair ["fast", "quick"] places both words under leader "fast".
  2. Pair ["quick", "rapid"] finds "quick"'s leader ("fast") and attaches "rapid" under "fast" as well; pair ["calm", "quiet"] puts "quiet" under "calm".
  3. At index 0, "fast" and "rapid" both resolve to leader "fast" (match!).
  4. At index 1, "river" equals "river" directly even though "river" never appeared in synonym_pairs; at index 2, "calm" and "quiet" both resolve to "calm"—returning True.

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 like O(P + n) in practice. Here α(W) is the inverse Ackermann function, a mathematical function that grows so slowly it never exceeds 5 for any realistic input size. Building the clusters processes P pairs (doing two root lookups and at most one merge per pair), and comparing the sentences scans n positions (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 returns False in O(1) time before touching any pairs.
  • Space: O(W) to store one entry per distinct paired word in parent and group_size. Tokens appearing only inside the sentences are compared in place without allocating extra dictionary entries.

Edge cases

  • Different sentence lengths: returns False immediately, even when one sentence is a prefix of the other or empty.
  • Both sentences empty ([] and []): returns True, since their lengths match and zero indices disagree.
  • Identical tokens absent from all pairs: returns True at 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"] find root_a == root_b and skip merging without inflating group_size.
  • Deep chains of 100,000 pairs: handled safely by an iterative while loop without hitting Python's recursion limit.
  • Same words in swapped positions: ["quick", "fox"] vs. ["fox", "fast"] returns False, since matching is strictly index-aligned.

Common mistakes

  • Treating pairs as one-way edges: recording only synonyms[a].add(b) misses b -> a when [a, b] was listed once.
  • Checking only direct pairs: fails on multi-step chains like fast -> quick -> rapid where two synonyms are connected via intermediate words.
  • Looking up parent[word] before checking word_a == word_b: tokens absent from synonym_pairs are missing from parent, so calling find_root on "river" vs. "river" crashes with a KeyError (or falsely rejects identical unlisted tokens).
  • Skipping the length check before zip: Python's zip(sentence_a, sentence_b) stops at the shorter list, falsely accepting ["hi"] against ["hi", "there"].
  • Using recursive find_root without balancing: a chain of 100,000 pairs can overflow Python's call stack with RecursionError.

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 integer component_id to every word in that component, and compare component_ids at each sentence index. That takes O(W + P + n) time and O(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) if w in parent else w, transform both sentences into canonical word lists, and check canon_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 two n-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 index i, two tokens match if word_a == word_b or (word_a, word_b) belongs to the set, running in O(P + n) time and O(P) space.
  • How would you support a live stream of new synonym pairs interleaved with millions of sentence checks? Persist parent and group_size on a service object across calls: each incoming pair performs a single O(α(W)) union without rebuilding prior clusters, and each sentence comparison runs in O(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 tuple tuple(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

Similar questions

More Read.Ai interview questions

All 1 Read.Ai questions →