Word Ladder
Picture
cat → cot → cog → dog is a route through words. Each word is a node; a legal single-letter change is an edge. All edges count equally, even though the input never says “graph.”
Predict
Should the example’s answer be three or four?
Walk through the small example
Four. The problem asks for words in the sequence, not edges. Starting the initial word at distance one handles the difference.
Mental model and complete Python solution
Generate neighbors lazily by changing one character to each possible lowercase letter. A set checks whether the candidate is allowed and still undiscovered. Remove it when enqueuing. BFS ensures the first discovered route to a word is shortest. A closer-looking word is not necessarily on a legal route to the target.
What the function promises: Words have the same length and use lowercase English letters. Return shortest sequence length in words, or zero if impossible. The target must be in the dictionary. The helper also handles equal begin/end when the target is present.
from collections import deque
from string import ascii_lowercase
def ladder_length(begin, end, words):
available = set(words)
if end not in available:
return 0
available.discard(begin)
queue = deque([(begin, 1)])
while queue:
word, length = queue.popleft()
if word == end:
return length
for i in range(len(word)):
for letter in ascii_lowercase:
candidate = word[:i] + letter + word[i+1:]
if candidate in available:
available.remove(candidate)
queue.append((candidate, length + 1))
return 0
assert ladder_length("cat", "dog", ["cot", "cog", "dog"]) == 4
assert ladder_length("cat", "dog", ["cot", "cog"]) == 0
assert ladder_length("a", "c", ["a", "b", "c"]) == 2
Work and storage: For N dictionary words of length L and alphabet size A=26, O(N A L²) worst-case time for this Python implementation, including slicing and hashing candidate strings, and O(NL) string storage. A bidirectional search can reduce explored states but requires careful frontier handling.
When to recognize it: Each word is a state. One legal letter change is an equal-cost edge, even though no graph is supplied.
Check before applying it: Matching the most target letters is not a safe greedy rule. The dictionary may require a detour.
Change one rule
Now return all shortest sequences, not just their length.
See what changes
Record every predecessor giving the same minimum distance, including different parents from the same BFS layer. After reaching the target layer, backtrack through this predecessor DAG. Keeping only one parent would lose valid shortest sequences; enumerating output remains output-sensitive.
Connect
bfs: The same distance-layer idea works without a drawn graph.
Word Break: Words can instead create jumps between string boundaries.
Problem reference: Word Ladder (Hard). The walkthrough and Python solution above are original course material.