Word Ladder II (LeetCode 126): Solution and Explanation

Hard
Hash Table
String
Backtracking
Breadth First Search

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Put the dictionary in a set and return an empty list if endWord is missing.
  2. Start with layer = {beginWord: [[beginWord]]} and remove beginWord from the set.
  3. While the layer is non-empty, check each word; if it equals endWord, return layer[endWord].
  4. 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].
  5. After the whole layer, remove every key of newLayer from the set so later layers cannot revisit them.
  6. Replace layer with newLayer and continue. If the loop ends, return an empty list.

Step-by-step example

beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
  1. Layer 0 is {hit: [[hit]]}. Changing one letter reaches only hot, so layer 1 is {hot: [[hit, hot]]} and hot is removed from the set.
  2. From hot, the neighbors dot and lot form layer 2, and both are removed.
  3. dot reaches dog and lot reaches log, forming layer 3. dot and lot cannot reach each other anymore because they were removed.
  4. Both dog and log reach cog in the same layer, so newLayer[cog] collects two paths. This is exactly why removal waits until the layer finishes.
  5. On the next iteration cog is 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 []

Time and space complexity

Time

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.

Space

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 newLayer while still in the middle of a layer, before all of that layer's parents have added their paths.
  • Forgetting the early check that endWord is 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.