Word Ladder II solution explained
Word Ladder II asks for every shortest chain of one-letter changes between two words, so the solution has two phases: a breadth-first search that expands the dictionary one layer at a time and remembers, for each new word, which words in the previous layer reached it, and then a backtracking walk from the target that follows those parent links back to the start. The BFS fixes the length; the walk lists the ladders.
By Evin JohnPublished 9 min read
The problem in plain words
You get a start word, a target word and a list of allowed words. All words have the same length and use lowercase letters. A single move swaps exactly one letter for another letter. After the start, every word you step on must come from the list. Return every sequence of words from the start to the target that uses the fewest moves. If the target cannot be reached, return an empty list. The start word itself does not have to appear in the list.
| Start | Target | Word list | Answer |
|---|---|---|---|
| bed | cat | bad, bat, bet, cat, cad | [bed, bad, bat, cat], [bed, bet, bat, cat], [bed, bad, cad, cat] |
| lot | lid | lit, let, lid, led | [lot, lit, lid] only; the route through let and led takes one move more |
| ink | ant | ick, inn, ant | [] because no word bridges ink and ant |
| sea | sky | sex, set, sat | [] because the target is not in the list |
Before coding, ask whether the list can hold duplicates, whether start can equal target, and whether the ladders must come back in a fixed order. Most versions accept any order, which helps, because a set-based BFS does not produce a stable one.
Why it is harder than Word Ladder I
The first version only wants the length of the shortest chain, so a plain BFS with a visited set is enough: the first time you reach the target, you stop. This version wants every shortest chain. That breaks the usual visited-set habit. If two words in layer 2 both lead to the same word in layer 3, a normal BFS marks that word as visited after the first one and silently drops the second route. You need to keep every edge that goes from one layer to the next, and only those edges.
There is also a size trap. Storing a full path inside every queue entry copies the same prefixes again and again, which is why the naive answer runs out of memory on big inputs.
Slow approach: depth-first search over all paths
The direct idea is a DFS from the start that tries every unused neighbor, records each path that reaches the target, and keeps only the shortest ones. It is correct and makes a good test oracle, but it explores every simple path in the word graph, which is exponential on a dense dictionary even when the shortest ladder is short. Name it as the baseline, then say that BFS hands you the shortest length and lets you prune everything longer.
Main approach: layered BFS, then backtrack
- Build the dictionary as a setPut the word list in a set called remaining. If the target is missing, return an empty list at once. Remove the start word so nothing can loop back to it.
- Expand one full layer at a timeFor each word in the current layer, try every position and every letter from a to z. Any candidate that is still in remaining becomes part of the next layer, and the current word is added to its list of parents.
- Remove the layer only after it is finishedDelete the current layer's words from remaining before you expand it, never in the middle. Two words of the same layer may both point at the same next word, and both parent links must survive.
- Stop after the target's layerOnce the target shows up in a next layer, finish that layer and stop. Anything deeper is longer than the shortest ladder.
- Backtrack from the targetWalk from the target through parent lists until you reach the start. Each complete walk, reversed, is one shortest ladder. Going backward only touches words that lie on a shortest route.
from collections import defaultdict
def all_shortest_ladders(start, goal, words):
remaining = set(words)
if goal not in remaining:
return []
remaining.discard(start)
parents = defaultdict(list) # word -> words one step closer to start
layer = {start}
found = False
while layer and not found:
remaining -= layer
next_layer = set()
for word in layer:
for i in range(len(word)):
for ch in "abcdefghijklmnopqrstuvwxyz":
if ch == word[i]:
continue
cand = word[:i] + ch + word[i + 1:]
if cand in remaining:
parents[cand].append(word)
next_layer.add(cand)
if cand == goal:
found = True
layer = next_layer
if not found:
return []
results, path = [], [goal]
def walk_back(word):
if word == start:
results.append(path[::-1])
return
for prev in parents[word]:
path.append(prev)
walk_back(prev)
path.pop()
walk_back(goal)
return resultsfunction allShortestLadders(start, goal, words) {
const remaining = new Set(words);
if (!remaining.has(goal)) return [];
remaining.delete(start);
const parents = new Map(); // word -> words one step closer to start
let layer = [start];
let found = false;
while (layer.length && !found) {
for (const w of layer) remaining.delete(w);
const next = new Set();
for (const word of layer) {
for (let i = 0; i < word.length; i++) {
for (let k = 0; k < 26; k++) {
const ch = String.fromCharCode(97 + k);
if (ch === word[i]) continue;
const cand = word.slice(0, i) + ch + word.slice(i + 1);
if (!remaining.has(cand)) continue;
if (!parents.has(cand)) parents.set(cand, []);
parents.get(cand).push(word);
next.add(cand);
if (cand === goal) found = true;
}
}
}
layer = [...next];
}
if (!found) return [];
const results = [];
const path = [goal];
const walkBack = (word) => {
if (word === start) {
results.push([...path].reverse());
return;
}
for (const prev of parents.get(word)) {
path.push(prev);
walkBack(prev);
path.pop();
}
};
walkBack(goal);
return results;
}Trace the first example. Layer 0 is {bed}. Expanding it finds bad and bet, each with parent bed. Layer 1 is removed from the set, then expanded: bad reaches bat and cad, and bet also reaches bat, so bat ends up with two parents. Layer 2 is {bat, cad}, and both reach cat, which sets the found flag. Backtracking from cat gives three routes, matching the table.
Complexity
| Phase | Time | Space | Note |
|---|---|---|---|
| Neighbor generation in BFS | O(N · L · 26 · L) | O(N · L) | Each candidate string costs O(L) to build and hash |
| Parent map | Part of the BFS | O(E) | E is the number of layer-to-layer edges kept |
| Backtracking | O(P · K) | O(K) stack | P ladders of K words each; output size dominates |
| DFS over all paths | Exponential | O(N) | Only for tiny inputs or as a test oracle |
An honest complexity answer mentions the output: when there are many shortest ladders, no method can print them faster than their total length. The BFS is the part you control.
Speed-ups interviewers like to hear
- Bidirectional BFS. Grow layers from both ends and always expand the smaller side. It shrinks the explored area a lot on wide dictionaries, but you must keep parent links pointing the same way on both sides, which is fiddly. Mention it, and only code it if asked.
- Wildcard buckets. Precompute patterns like b*d and *ed that map to all words matching them. Neighbor lookup becomes a few dictionary reads instead of 26 · L string builds, at the cost of extra memory.
- Store parents, not paths. Keeping full paths in the queue is the classic memory blow-up. Parent lists share prefixes for free.
Edge cases to test
- The target is not in the list: return an empty list before any search.
- The start word also appears in the list: it must not be reused as a middle step.
- Words of length 1, where every word is a neighbor of every other word.
- Several parents on the same layer, like bat in the first example. A missing route here is the most common bug.
- No route at all: the BFS runs out of layers without setting the found flag.
Common mistakes
- Marking a word visited the moment it is first reached. That drops the second parent from the same layer and loses ladders.
- Removing words from the dictionary too late, after the next layer, which lets longer routes add parents and creates non-shortest ladders.
- Continuing the BFS past the layer that contains the target.
- Pushing whole paths into the queue. It passes small tests and runs out of memory on large ones.
- Comparing results in a fixed order when the problem accepts any order. Sort both sides when you test.
Explaining it in an interview
Fictional example
- Candidate
- The words form a graph where an edge joins two words that differ in one letter. I need every shortest path, so BFS gives me the distance, and I need to keep all the edges that move from one layer to the next.
- Candidate
- I will not use a normal visited set, because a word in layer three can be reached from two words in layer two. Instead I remove a full layer from the dictionary right before I expand it.
- Candidate
- When the target appears I stop after that layer, then backtrack from the target through the parent lists. That avoids storing full paths in the queue, which is where the memory would go.
Related problems in this set
Treating a whole configuration as a graph node comes back in Sliding Puzzle, where each board state is a node and BFS counts the moves. Adding extra information to the node, here the layer, there a set of visited vertices, is the core of Shortest Path Visiting All Nodes. For the theory behind both, see the algorithm interview questions page.
Practicing with Natively
When you rehearse a hard graph problem like this, Natively can read the statement from a screenshot and suggest an approach, which is most useful after you have committed to your own plan and want to compare. It can also transcribe a mock round on your computer, so you can check afterwards whether you explained the layer-removal rule before you started typing. See how an AI interview assistant fits into practice on Mac and Windows.
Questions people ask
How do you solve Word Ladder II?
Run a breadth-first search one layer at a time and record, for every newly reached word, which words in the previous layer led to it. Stop after the layer that contains the target, then backtrack from the target through those parent links to build every shortest ladder.
Why does a normal visited set break Word Ladder II?
It marks a word as done the first time it is reached, so a second word on the same layer cannot add itself as a parent. Removing a whole layer from the dictionary only after it is complete keeps every shortest route.
What is the time complexity of Word Ladder II?
The BFS costs about O(N · L² · 26) for N words of length L, because each candidate string takes O(L) to build. Listing the answers adds time proportional to the number of ladders times their length, which no method can avoid.
Should I use bidirectional BFS for Word Ladder II?
It can cut the search a lot on large dictionaries, so it is worth mentioning. It is harder to get right because parent links must point the same way from both sides, so most candidates code the one-directional version first.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
