Shortest Word Chain Allowing One or Two Letter Swaps
Trees & GraphsAuto-graded · 24 test casesLast updated
Find a shortest word chain where each step swaps one or two letters, with a fixed tie-break, using BFS on an implicit graph and wildcard bucketing for fast neighbor lookup.
You are given a starting word, a target word, and a list of allowed words. All words are lowercase. Build a chain of words that begins at the starting word and ends at the target word, moving one word at a time.
Move rule. Going from one word to the next replaces the letters at exactly 1 or 2 positions. The two words must have the same length and differ in exactly 1 or 2 positions. Letters cannot be inserted or removed.
Allowed words.
- Every word in the chain other than the starting word must come from the allowed list, with one exception: the target word is always allowed as the final word, even if the list does not contain it.
- The starting word does not need to appear in the list.
- Words in the list whose length differs from the starting word's length are ignored. The list may contain duplicates, which have no effect.
Goal. Return a chain with the fewest possible moves, as a list of words from the starting word to the target word, both included.
Special cases.
- If the starting word equals the target word, return a list containing just that word, whatever the list holds.
- If the starting and target words have different lengths, or no chain exists, return an empty list.
Which chain to return. Several shortest chains may exist, and the answer is the one produced by this exact procedure:
- Run a breadth-first search from the starting word with a FIFO queue.
- When a word is taken from the queue, look at all not-yet-discovered words that can be reached from it in one move. Handle them in ascending alphabetical (lexicographic) order.
- Each newly discovered word records the word it was discovered from as its predecessor. A word is never re-assigned a predecessor.
- The returned chain is the one obtained by following predecessors back from the target word.
Following these rules gives a single well-defined answer for every input.
Function. Return the chain as List[str].
Constraints
- Words contain only lowercase English letters
a-z. - Word lengths are small (about 1 to 10 characters).
- The list can hold up to roughly 10^4 words.
- The starting word may or may not be in the list.
- The target word may or may not be in the list.
- The list may be empty.
Examples
Example 1
Input: find_shortest_word_chain('hit', 'cog', ['hot', 'dot', 'dog', 'lot', 'log', 'cog'])
Output: ['hit', 'dot', 'cog']
Example 2
Input: find_shortest_word_chain('hit', 'cog', ['hot', 'dot', 'dog', 'lot', 'log'])
Output: ['hit', 'dot', 'cog']
Example 3
Input: find_shortest_word_chain('aaa', 'bbb', ['aab', 'abb', 'aba', 'bbb'])
Output: ['aaa', 'aab', 'bbb']
Example 4
Input: find_shortest_word_chain('same', 'same', [])
Output: ['same']
Hints
Hint 1
Treat each word as a node in an unweighted graph, with an edge between two words of equal length that differ in exactly 1 or 2 positions. A shortest path in an unweighted graph is a BFS job.
Hint 2
Comparing every pair of words is too slow. Replace two positions of a word with a wildcard to make patterns. Two distinct words share such a pattern exactly when they differ in at most 2 positions. Index words by these patterns, and use a single wildcard when the word length is 1.
Hint 3
To get the required tie-break, collect all neighbors of the dequeued word, sort them, and only then assign predecessors to the undiscovered ones. Rebuild the chain by walking predecessors back from the target and reversing. Handle equal start and target, and length mismatch, before the search.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat every word as a node in an unweighted graph. Two words are joined by an edge when they have the same length and differ in exactly 1 or 2 positions. The task is then a shortest-path search, so BFS is the natural tool. DFS could return a path that is not the shortest.
Finding neighbors quickly
Comparing every pair of words costs O(N^2 * L). Instead, build wildcard buckets:
- For every pair of positions (i, j), replace those two letters with
*to make a pattern. - Put each word into the bucket of each of its patterns.
- Two distinct words share a pattern exactly when they agree on all other positions. That means they differ in at most 2 positions, which is the same as having a Hamming distance of 1 or 2. This catches every edge and adds no false ones.
- For words of length 1, use a single
*pattern. Any two distinct one-letter words differ in exactly one position, so they are always neighbors.
The target word is added to the pool even if the list lacks it. Words of other lengths are dropped.
Tie-break
The statement fixes the answer by requiring that, for each dequeued word, its neighbors are sorted alphabetically before predecessors are assigned. Collect the neighbors into a set, remove the word itself, and sort. Then walk through them in order and skip any already discovered. Because the queue is FIFO and every predecessor is set on first discovery, the output is deterministic.
Reconstruction
When the target is first discovered, its level is its minimum distance. Follow the predecessor pointers back to the start and reverse the result. If the queue empties first, return []. Handle start_word == target_word (return [start_word]) and a length mismatch (return []) before the search.
Why it is correct
BFS discovers words in non-decreasing order of distance, so a word's predecessor always lies one level closer to the start, and the reconstructed path has the minimum length. The bucket equivalence guarantees the neighbor sets are exact.
Complexity
Let N be the number of words and L the word length. There are O(L^2) patterns per word, each of length L.
- Building the index: O(N * L^3).
- BFS: each word is dequeued once, and its neighbor set is the union of its buckets. Buckets can be large, so the worst case is higher than the index build, but it is far below pairwise comparison for sparse data. Sorting adds a logarithmic factor.
- Space: O(N * L^3) characters for the index, plus O(N * L) for the predecessor map and queue.
Reference solution
from collections import defaultdict, deque
from typing import List
def find_shortest_word_chain(start_word: str, target_word: str, allowed_words: List[str]) -> List[str]:
if start_word == target_word:
return [start_word]
if len(start_word) != len(target_word):
return []
length = len(start_word)
pool = set(allowed_words)
pool.add(target_word)
pool = [w for w in pool if len(w) == length]
def patterns(word):
if length <= 1:
yield ('*',)
return
chars = list(word)
for i in range(length):
for j in range(i + 1, length):
p = chars[:]
p[i] = '*'
p[j] = '*'
yield tuple(p)
buckets = defaultdict(list)
for w in pool:
for p in patterns(w):
buckets[p].append(w)
def neighbors(word):
found = set()
for p in patterns(word):
found.update(buckets.get(p, ()))
found.discard(word)
return sorted(found)
parent = {start_word: None}
queue = deque([start_word])
while queue:
current = queue.popleft()
for cand in neighbors(current):
if cand in parent:
continue
parent[cand] = current
if cand == target_word:
path = []
node = cand
while node is not None:
path.append(node)
node = parent[node]
return path[::-1]
queue.append(cand)
return []