Word Ladder II (LeetCode 126): Solution and Explanation
Given a start word, an end word and a dictionary, find every shortest sequence of words from start to end where each step changes exactly one letter and every word after the first is in the dictionary. Return all such sequences, or an empty list if none exists.
Watch it run step by step
Try your own input and write the code →Intuition
The single-answer version is a straightforward BFS, because BFS reaches the end word at the shortest distance first. Here you need all shortest paths, which changes two things: you must keep track of how you got to each word, and you cannot throw away a word the moment it is first reached, since several words in the same layer may lead to it along equally short paths.
The reference code keeps, for each word in the current BFS layer, the list of all shortest paths that end at it. To expand a layer, it tries every one-letter change of every word. Any result still in the dictionary gets every path of its parent extended by itself. Words reached in this layer are then removed from the dictionary all at once, after the whole layer is processed. Removing them at the end of the layer, rather than on first sight, is what allows two parents in the same layer to share a child.
As soon as the end word appears in a layer, every path stored for it is a shortest path, so the search returns those immediately. If a layer comes up empty, the end word is unreachable. Generating neighbors by changing letters costs 26 × L candidates per word and avoids comparing every pair of dictionary words.
Approach: Layered BFS carrying full paths
- Put the dictionary in a set and return an empty list if
endWordis missing. - Start with
layer = {beginWord: [[beginWord]]}and removebeginWordfrom the set. - While the layer is non-empty, check each word; if it equals
endWord, returnlayer[endWord]. - For each word, try every position and every letter from a to z. If the new word is in the set, extend each path of the current word by it and add those paths to
newLayer[newWord]. - After the whole layer, remove every key of
newLayerfrom the set so later layers cannot revisit them. - Replace
layerwithnewLayerand continue. If the loop ends, return an empty list.
Step-by-step example
beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
- Layer 0 is
{hit: [[hit]]}. Changing one letter reaches onlyhot, so layer 1 is{hot: [[hit, hot]]}andhotis removed from the set. - From
hot, the neighborsdotandlotform layer 2, and both are removed. dotreachesdogandlotreacheslog, forming layer 3.dotandlotcannot reach each other anymore because they were removed.- Both
dogandlogreachcogin the same layer, sonewLayer[cog]collects two paths. This is exactly why removal waits until the layer finishes. - On the next iteration
cogis found in the layer, and the function returns[[hit, hot, dot, dog, cog], [hit, hot, lot, log, cog]].
Code: Python, Java, C++
1class Solution:
2 def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
3 wordSet = set(wordList)
4 if endWord not in wordSet:
5 return []
6
7 # BFS to find shortest path length and build graph
8 layer = {beginWord: [[beginWord]]}
9 wordSet.discard(beginWord)
10
11 while layer:
12 newLayer = defaultdict(list)
13 for word in layer:
14 if word == endWord:
15 return layer[endWord]
16 for i in range(len(word)):
17 for c in 'abcdefghijklmnopqrstuvwxyz':
18 newWord = word[:i] + c + word[i+1:]
19 if newWord in wordSet:
20 for path in layer[word]:
21 newLayer[newWord].append(path + [newWord])
22 wordSet -= set(newLayer.keys())
23 layer = newLayer
24
25 return []1class Solution {
2 public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
3 Set<String> wordSet = new HashSet<>(wordList);
4 if (!wordSet.contains(endWord)) return new ArrayList<>();
5
6 Map<String, List<List<String>>> layer = new HashMap<>();
7 layer.put(beginWord, new ArrayList<>());
8 layer.get(beginWord).add(Arrays.asList(beginWord));
9 wordSet.remove(beginWord);
10
11 while (!layer.isEmpty()) {
12 Map<String, List<List<String>>> newLayer = new HashMap<>();
13 for (String word : layer.keySet()) {
14 if (word.equals(endWord)) return layer.get(endWord);
15 char[] chars = word.toCharArray();
16 for (int i = 0; i < chars.length; i++) {
17 char orig = chars[i];
18 for (char c = 'a'; c <= 'z'; c++) {
19 chars[i] = c;
20 String newWord = new String(chars);
21 if (wordSet.contains(newWord)) {
22 newLayer.putIfAbsent(newWord, new ArrayList<>());
23 for (List<String> path : layer.get(word)) {
24 List<String> newPath = new ArrayList<>(path);
25 newPath.add(newWord);
26 newLayer.get(newWord).add(newPath);
27 }
28 }
29 }
30 chars[i] = orig;
31 }
32 }
33 wordSet.removeAll(newLayer.keySet());
34 layer = newLayer;
35 }
36
37 return new ArrayList<>();
38 }
39}1class Solution {
2public:
3 vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
4 unordered_set<string> wordSet(wordList.begin(), wordList.end());
5 if (wordSet.find(endWord) == wordSet.end()) return {};
6
7 unordered_map<string, vector<vector<string>>> layer;
8 layer[beginWord] = {{beginWord}};
9 wordSet.erase(beginWord);
10
11 while (!layer.empty()) {
12 unordered_map<string, vector<vector<string>>> newLayer;
13 for (auto& [word, paths] : layer) {
14 if (word == endWord) return paths;
15 string newWord = word;
16 for (int i = 0; i < word.size(); i++) {
17 char orig = newWord[i];
18 for (char c = 'a'; c <= 'z'; c++) {
19 newWord[i] = c;
20 if (wordSet.count(newWord)) {
21 for (auto& path : paths) {
22 vector<string> newPath = path;
23 newPath.push_back(newWord);
24 newLayer[newWord].push_back(newPath);
25 }
26 }
27 }
28 newWord[i] = orig;
29 }
30 }
31 for (auto& [word, _] : newLayer) {
32 wordSet.erase(word);
33 }
34 layer = newLayer;
35 }
36
37 return {};
38 }
39};Time and space complexity
O(N × L² × 26 + P × K)
Each of the N dictionary words is expanded at most once, generating 26 × L candidates that each cost O(L) to build and hash. On top of that, copying paths costs time proportional to the total length of all stored paths, P paths of length up to K, which can grow exponentially when many shortest paths exist.
O(N × L + P × K)
The word set holds the dictionary, and each layer stores every partial shortest path ending at its words.
Other approaches
BFS for parents, then DFS backtracking (time O(N × L² × 26 + output), space O(N × L + output))
Run BFS once, recording for each word the set of parents one layer above. Then backtrack from endWord to beginWord through those parent links to build only the complete shortest paths. This avoids storing every partial path and is the most memory-friendly solution.
Bidirectional BFS (time O(N × L² × 26 + output) worst case, space O(N × L + output))
Grow layers from both ends, always expanding the smaller frontier, and record parent links until the frontiers meet. It explores far fewer words on large dictionaries, at the cost of more complex bookkeeping.
Common mistakes
- Removing a word from the set as soon as it is reached. A second parent in the same layer could no longer reach it, and valid shortest paths are lost.
- Never removing visited words. Later layers can then revisit earlier words, producing longer paths and possible cycles.
- Returning after finding the end word in
newLayerwhile still in the middle of a layer, before all of that layer's parents have added their paths. - Forgetting the early check that
endWordis in the dictionary, which wastes a full search that can never succeed.
Frequently asked questions
How is Word Ladder II different from Word Ladder?
Word Ladder asks only for the length of the shortest sequence, so a plain BFS suffices. Word Ladder II needs every shortest sequence, which requires tracking multiple parents per word.
Why remove visited words only after finishing a layer?
Several words in one layer can lead to the same next word through equally short paths. Removing it immediately would keep only the first parent and drop valid answers.
Why does Word Ladder II get time limit exceeded?
Storing and copying every partial path can blow up when there are many shortest paths. Recording parent links during BFS and building paths only at the end with DFS is the usual fix.
What is the time complexity of Word Ladder II?
The search part is O(N × L² × 26), but the total cost also depends on the number and length of shortest paths, which can be exponential in the worst case.