Word Ladder II
List every shortest chain of words from one word to another, changing one letter per step.
Given two words, beginWordendWordwordListbeginWordendWordwordList
Example 1
Output: [["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]]
Example 2
Output: []
Explanation: "cog" is not in the list, so no sequence can end with it.
The Idea
This is the old word ladder puzzle: get from one word to another by changing one letter at a time, where every word on the way must be a real word. A word counts as real only if wordList
In Example 1, hit becomes hot by changing i to o. From hot, changing h to d gives dot, then dog, then cog. That is four steps. Changing h to l instead gives lot, log and cog, also four steps. Both ladders are in the answer. So two questions come up: how can we be sure no ladder with three steps exists, and how do we collect every four-step ladder without missing one?
Start from hit and ask which list words are one change away. Only hot is. From hot, dot and lot are one change away. From those, dog and log, and from those, cog. Grouping the words by how many steps they are from hit gives layers. Look at the picture below.
hit sits alone on layer 0, hot on layer 1, dot and lot on layer 2, dog and log on layer 3, and cog on layer 4. Each word appears on the first layer that reaches it. cog is on layer 4, so the shortest ladder has four steps, and no shorter one can exist.
The words and the "one letter apart" links between them form a graph: the words are its points, and each link joins two words that differ in one letter. Visiting a graph one layer at a time, nearest words first, is called breadth-first search.
Now look at cog. Two arrows lead into it, one from dog above it and one from log below it. Call the words on the previous layer that lead to a word its parents: cog has two parents, dog and log. dog has one parent, dot, and dot has one, hot. If every word remembers all its parents, each shortest ladder can be read backwards: start at cog, pick a parent, then a parent of that parent, until you reach hit.
Look at the dashed lines too, labelled "same-layer links are not used". dot and lot are one letter apart, but both are on layer 2, so stepping from one to the other never makes a ladder shorter. Only arrows from one layer to the next count.
Solution Approach
Turning that idea into code means seeing first why trying every ladder is slow, then settling four things: how to find the words one letter away, how to build the layers and when to stop, when to cross a word off, and how to read the ladders back.
Trying every ladder
Why not start at beginWordendWord
Finding the words one letter away
How do we find the words one change away from hot? One way is to compare hot with every word in the list, letter by letter. A quicker way for short words is to try every change: put each of the 26 letters at each position, and check whether the new word is in a HashSet
Building the layers and when to stop
Which words go on the next layer? Every word one change away from a word on the current layer, as long as it has not appeared on an earlier layer. While a layer is built, each new word also records the word it came from as a parent.
When should the search stop? As soon as a layer contains endWordendWord
When to cross a word off
How do we keep words from earlier layers out? Keep a set of words not yet used, and remove the words of a layer from it. The timing matters. If a word is removed the moment it is first found, a second word on the same layer that also reaches it finds it gone. In Example 1, cog would be removed when the first of its two parents finds it, and the other parent would never be recorded.
So the words of a new layer are removed only after the whole layer is built. Words of earlier layers are still excluded, which keeps every recorded ladder shortest.
Reading the ladders back
How do we turn the parents into ladders? Start a path holding only endWordbeginWord
Java Solution
The method findLadders
- First, copy
into awordList namedHashSet , the words not on any layer yet, and create an empty listunused . Ifresult is not inendWord , return the emptyunused . Otherwise removeresult frombeginWord , in case the list contains it.unused - Create a map named
, from a word to the list of its parents, a set namedparents holding the current layer, which starts as justlevel , and a flag namedbeginWord . Afound loop builds one layer per round, as long aswhile is not empty andlevel has not been found.endWord - Inside, create an empty set
. For each word innextLevel , two loops, one inside the other, try every positionlevel and every letteri from a to z, building the changed wordch .next - If
is innext , add it tounused and add the current word to its list innextLevel . Ifparents isnext , setendWord to true.found - When the layer is finished, remove all of
fromnextLevel withunused , and makeunused.removeAll(nextLevel) the newnextLevel .level - After the loop, if
is true, start afound namedLinkedList holdingpath and callendWord . It puts each parent at the front withbacktrack , calls itself from that parent, and takes the parent off again withaddFirst . When it reachesremoveFirst , it adds a copy ofbeginWord topath .result - Finally, return
.result
The mainbeginWordendWord
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class WordLadderII {
public static List<List<String>> findLadders(String beginWord, String endWord,
List<String> wordList) {
Set<String> unused = new HashSet<>(wordList);
List<List<String>> result = new ArrayList<>();
if (!unused.contains(endWord)) {
return result; // endWord can never be reached
}
unused.remove(beginWord);
// 1. Visit the words layer by layer, remembering every parent of each word.
Map<String, List<String>> parents = new HashMap<>();
Set<String> level = new HashSet<>(List.of(beginWord));
boolean found = false;
while (!level.isEmpty() && !found) {
Set<String> nextLevel = new HashSet<>();
for (String word : level) {
char[] chars = word.toCharArray();
for (int i = 0; i < chars.length; i++) {
char original = chars[i];
for (char ch = 'a'; ch <= 'z'; ch++) {
chars[i] = ch;
String next = new String(chars);
if (!unused.contains(next)) {
continue; // not in the list, or on an earlier layer
}
nextLevel.add(next);
parents.computeIfAbsent(next, k -> new ArrayList<>()).add(word);
if (next.equals(endWord)) {
found = true;
}
}
chars[i] = original;
}
}
unused.removeAll(nextLevel); // only now, so a word keeps all its parents
level = nextLevel;
}
// 2. Walk the parent links back from endWord to beginWord.
if (found) {
LinkedList<String> path = new LinkedList<>(List.of(endWord));
backtrack(endWord, beginWord, parents, path, result);
}
return result;
}
private static void backtrack(String word, String beginWord,
Map<String, List<String>> parents,
LinkedList<String> path, List<List<String>> result) {
if (word.equals(beginWord)) {
result.add(new ArrayList<>(path));
return;
}
for (String p : parents.getOrDefault(word, List.of())) {
path.addFirst(p); // put the parent in front
backtrack(p, beginWord, parents, path, result);
path.removeFirst(); // take it off again for the next parent
}
}
public static void main(String[] args) {
System.out.println(findLadders("hit", "cog",
List.of("hot", "dot", "dog", "lot", "log", "cog")));
System.out.println(findLadders("hit", "cog",
List.of("hot", "dot", "dog", "lot", "log")));
System.out.println(findLadders("red", "tax",
List.of("ted", "tex", "red", "tax", "tad", "den", "rex", "pee")));
System.out.println(findLadders("hot", "dot", List.of("dot")));
System.out.println(findLadders("hit", "cog", List.of("hot", "cog")));
}
}
Running it prints:
[[hit, hot, lot, log, cog], [hit, hot, dot, dog, cog]]
[]
[[red, ted, tad, tax], [red, ted, tex, tax], [red, rex, tex, tax]]
[[hot, dot]]
[]
Look at the first line: both ladders of Example 1, but with the lot ladder first. The layers are hash sets, which hand out their words in an order of their own, and the problem accepts the ladders in any order.
The third line turns red into tax in three steps, three different ways. tex appears in two of them because it has two parents, ted and rex. red is also in that list, but it was removed from unused
The last line is empty even though cog is in the list. From hit the only word one change away is hot, and nothing in the list is one change away from hot, so the next layer is empty and the loop ends with found
The timing of removeAllunusednextLevel[[hit, hot, lot, log, cog]][[red, ted, tad, tax]]
Complexity
The work is building the layers, where each word is expanded once, plus writing out the ladders. N stands for the number of words in wordList
- Time: O(N × 26 × L2) for the layers, because each word is expanded once, trying 26 letters at L positions, and each try builds and hashes an L-letter string. Writing out the ladders adds their total length, which can grow very fast when many words have several parents.
- Space: O(N × 26 × L) besides the answer, because the sets hold each word of L letters at most once, and a word's parent list can hold one entry for each of its 26 × L possible changes.
When only the number of steps of the shortest ladder is needed, words can be crossed off as soon as they are found: see