Fewest Single-Letter Edits Through a Word List
Trees & GraphsAuto-graded · 19 test casesLast updated
Tests modeling word edits as an implicit graph and running BFS with wildcard buckets to find the minimum number of one-letter changes, with careful edge cases.
Word Morphing Distance
You have a starting string start, a target string target of the same length, and a collection dictionary of distinct strings, all of the same length as well.
In one move you may change exactly one character of the current string to a different letter. The string you get after every move must be an entry of dictionary. You are done as soon as the current string equals target.
The starting string itself does not need to appear in dictionary.
Task
Return the smallest number of moves needed to turn start into target. Each single-character change counts as one move. If no sequence of valid moves exists, return -1.
Note that you are counting moves (edges in the path), not the number of strings in the path. For instance, hit -> hot -> dot -> dog -> cog is 4 moves.
Rules and edge cases
- If
start == target, the answer is0, even iftargetis not indictionary. - Otherwise, since the last move produces
target, it must be indictionary; if it is not, the answer is-1. - Two strings are one move apart exactly when they differ in exactly one position.
Input
start: the starting string.target: the goal string.dictionary: a list of distinct strings that intermediate and final strings must come from.
Output
An integer: the minimum number of moves, or -1 if the target cannot be reached.
Constraints
1 <= len(start) = len(target) <= 201 <= len(dictionary) <= 50000- All strings consist of lowercase English letters only.
- All dictionary entries have the same length as
start.
Examples
Example 1
Input: min_word_morph_moves('hit', 'cog', ['hot', 'dot', 'dog', 'lot', 'log', 'cog'])
Output: 4
Hints
Hint 1
Think of every string as a node, with an edge between two strings that differ in exactly one position. What algorithm gives shortest paths in an unweighted graph?
Hint 2
Comparing all pairs of dictionary words is too slow for 50,000 words. Group words by a pattern with one position replaced by a wildcard (for example `h*t`); words sharing a pattern are neighbors.
Hint 3
Mark strings as visited when you enqueue them, and remember that you count moves, not words on the path. Handle `start == target` and a missing `target` before running the search.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat the problem as a shortest path in an unweighted graph. The nodes are start plus every dictionary word; two nodes are connected when they differ in exactly one position. Breadth-first search (BFS) from start finds the fewest edges to target.
The main challenge is finding neighbors quickly. Comparing all pairs of words costs O(N^2 * L), which is far too slow for N = 50,000.
Instead, build wildcard buckets: for every word and every position i, replace the character at i with * to get a pattern (hot gives *ot, h*t, ho*). Two words are one move apart exactly when they share a pattern. Store each pattern mapped to the list of words that produce it.
During BFS, for the current word, form its L patterns and look up each bucket. Every word in a bucket is a neighbor. After a bucket has been expanded once, we remove it: all its words have already been discovered at distance at most d + 1, so scanning it again could never help. This keeps each bucket scanned only once, even when thousands of words share a pattern.
Handle special cases first:
start == targetreturns0.- If
targetis not in the dictionary, return-1, since the last move must produce it. startdoes not need to be in the dictionary.
Mark words visited when they are enqueued so each is queued at most once. The distance counts moves, so the answer is the distance of the current word plus one when target is discovered. If the queue empties, return -1.
Why it is correct
- Every neighbor comes from buckets built from the dictionary, so every intermediate string is valid.
- BFS explores nodes in nondecreasing distance, so the first time
targetis found is at minimum distance. - Removing a bucket is safe because every word in it is already queued with a distance no larger than any later node could give it.
Complexity
Let N be the number of dictionary words and L the word length.
- Time: O(N * L^2). Building patterns costs N * L patterns of length L, and BFS does L pattern constructions per dequeued word.
- Space: O(N * L^2) for the pattern keys, plus O(N) for the queue and visited set.
Reference solution
from collections import deque
from typing import List
def min_word_morph_moves(start: str, target: str, dictionary: List[str]) -> int:
if start == target:
return 0
word_set = set(dictionary)
if target not in word_set:
return -1
length = len(start)
buckets = {}
for w in word_set:
if len(w) != length:
continue
for i in range(length):
buckets.setdefault(w[:i] + "*" + w[i + 1:], []).append(w)
visited = {start}
queue = deque([(start, 0)])
while queue:
word, dist = queue.popleft()
for i in range(length):
pattern = word[:i] + "*" + word[i + 1:]
neighbors = buckets.pop(pattern, None)
if not neighbors:
continue
for nxt in neighbors:
if nxt == target:
return dist + 1
if nxt not in visited:
visited.add(nxt)
queue.append((nxt, dist + 1))
return -1