Cluster Interchangeable Words by Surrounding Context
Trees & GraphsAuto-graded · 26 test casesLast updated
Tests context hashing, union-find for transitive closure, and precise output formatting to group words that are mutually substitutable in identical four-word windows.
Problem
You have a collection of sentences. A word's frame is the pair of words immediately to its left and the pair of words immediately to its right — a 4-tuple (left2, left1, right1, right2). A word only has a frame if there are at least two words on each side within the same sentence.
Two distinct words are interchangeable when at least one occurrence of each appears in the same frame. Interchangeability is transitive: if X is interchangeable with Y, and Y is interchangeable with Z, then X and Z belong to the same cluster, even if they never share a frame directly.
Return every cluster of interchangeable words. Words with no interchangeable partner are not reported.
Rules
- Split each sentence on single spaces and number the words
0, 1, 2, …within that sentence. - Word at position
ihas a frame only wheni >= 2andi <= len(words) - 3. - A word is identified by its exact character sequence; every occurrence of the same string is the same word.
- Occurrences in different sentences are compared against each other using the same global frame table.
- Within each cluster, sort the words in ascending lexicographic order.
- Sort the list of clusters by each cluster's first (lexicographically smallest) word.
- Return an empty list when no clusters exist.
Constraints
1 <= len(sentences) <= 10^4- Each sentence contains between 1 and 100 words; all sentences together contain at most
2 * 10^5words. - Every word is 1–20 lowercase English letters with no punctuation.
- Sentences have no leading or trailing spaces and words are separated by exactly one space.
Examples
Example 1
Input: find_interchangeable_clusters(['i really like the movie a lot', 'i really love the movie a lot', 'we really love the show very much', 'we really enjoy the show very much'])
Output: [['enjoy', 'like', 'love']]
Example 2
Input: find_interchangeable_clusters(['p q red r s', 'p q blue r s', 'm n big o t', 'm n large o t', 'm n huge o u'])
Output: [['big', 'large'], ['blue', 'red']]
Example 3
Input: find_interchangeable_clusters(['the cat sat'])
Output: []
Hints
Hint 1
For each valid position, build a 4-tuple of the surrounding words and think of it as a bucket — all words that land in the same bucket are directly interchangeable. How can you avoid comparing every pair inside a large bucket?
Hint 2
You only need one representative per bucket: record the first word seen for each frame. Every later word in that same frame gets linked to that representative, keeping the work per position O(1) amortized.
Hint 3
Once you have edges between words, the clusters are just connected components. Union-Find with path compression handles the transitive closure efficiently and lets you collect components at the end by grouping every registered word with its root.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core insight
Every valid position in a sentence produces a 4-tuple frame (left2, left1, right1, right2). Think of each unique frame as a bucket. Any two distinct words that land in the same bucket are directly interchangeable. Transitivity means we need the connected components of the graph where each direct-interchangeable pair is an edge — a classic Union-Find job.
Avoiding quadratic blowup
A naive approach would store all words per bucket and union every pair, which is O(k²) for a bucket of size k. Instead, keep only the first word seen for each frame. Every subsequent word in that frame gets unioned directly with that anchor. The bucket becomes a star graph, which has the same connectivity as the complete graph but only k−1 edges.
Algorithm
- Split each sentence on spaces and iterate over positions
iin[2, len(words) − 3](inclusive), which guarantees two neighbors on each side. - Build the frame tuple for position
i. - If the frame is new, store
anchor[frame] = words[i]. - If the frame was seen before and the stored anchor differs from the current word, add both to Union-Find (via
setdefault) and union their roots. - After scanning all sentences, group every registered word by its root. Discard groups of size 1 (defensive; all registered words already have at least one partner). Sort words within each group, then sort groups by their first element.
Why it is correct
- No false edges. A union only fires when two different words share an identical frame. Every edge is a genuine direct-interchangeable relationship.
- All true edges are captured. If words A and B share frame f, and F is the anchor for f, then both A and B are either equal to F or were unioned with F on arrival. So A and B end up in the same component.
- Transitivity is free. Union-Find's components are exactly the transitive closure of the unioned pairs.
- Singletons are excluded. A word only enters
parentwhen it is unioned with a different word, so isolated words are never registered.
Complexity
Let N ≤ 2·10⁵ be the total word count and L ≤ 20 the maximum word length.
- Time: Hashing each frame tuple costs O(L), so the full scan is O(N·L). Union-Find with path halving costs amortized O(log N) per operation, effectively constant. Final sorting is O(K log K · L) where K ≤ N is the number of grouped words.
- Space: O(N·L) for the
anchormap and the Union-Find dictionary.
Edge cases
- Short sentences. A sentence with fewer than 5 words has no valid position, so
range(2, len(words) − 2)is empty and nothing is registered. - Same word repeated in a frame. The
other != wordguard blocks a self-union, so the word is not reported unless it shares that frame with a genuinely different word. - A word bridging two frames. If word Y appears in frame f1 alongside X, and in frame f2 alongside Z, Union-Find naturally merges X, Y, and Z into one cluster.
- No interchangeable pairs at all.
parentstays empty and the function returns[].
Reference solution
from typing import List
def find_interchangeable_clusters(sentences: List[str]) -> List[List[str]]:
parent = {}
def find(x):
# Iterative find with path halving to avoid recursion-limit issues.
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
# Maps each frame 4-tuple to the first word encountered in that frame.
anchor = {}
for sentence in sentences:
words = sentence.split(' ')
for i in range(2, len(words) - 2):
frame = (words[i - 2], words[i - 1], words[i + 1], words[i + 2])
word = words[i]
if frame in anchor:
other = anchor[frame]
if other != word:
# Register both words in union-find if not already present.
parent.setdefault(word, word)
parent.setdefault(other, other)
root_w, root_o = find(word), find(other)
if root_w != root_o:
parent[root_w] = root_o
else:
anchor[frame] = word
# Collect words into clusters by their root.
clusters = {}
for x in parent:
clusters.setdefault(find(x), []).append(x)
result = [sorted(g) for g in clusters.values() if len(g) > 1]
result.sort(key=lambda g: g[0])
return result