Magicsheet logo

Word Ladder II

Hard
37.1%
Updated 6/1/2025

Word Ladder II

What is this problem about?

"Word Ladder II" is a more complex version of the first problem. Instead of just finding the length of the shortest transformation sequence, you must return all the shortest paths from beginWord to endWord.

Why is this asked in interviews?

This is a "Hard" difficulty problem because it requires combining two different algorithmic techniques: BFS to find the shortest distance and DFS/Backtracking to reconstruct all paths. Companies like Uber and Citadel ask this to see if you can manage complex data structures and avoid redundant computation during path reconstruction.

Algorithmic pattern used

The pattern is BFS followed by Backtracking.

  1. Run a BFS to build an adjacency list (a graph) where each word points to its predecessors that are exactly one step closer to the beginWord.
  2. During the BFS, record the minimum distance from the start to each word.
  3. Once the target is found, use Backtracking (DFS) starting from the endWord to trace back all paths to the beginWord using the recorded distances or the adjacency list.

Example explanation

Start: red, End: tax, List: ["ted", "tex", "tax", "tad"].

  1. BFS identifies red -> ted -> tex -> tax (length 4) and red -> tad -> tax? No, tad to tax is two changes.
  2. BFS also finds red -> ted -> tex -> tax and potentially another path like red -> tad -> ted -> tex -> tax.
  3. The shortest paths are identified as [["red", "ted", "tex", "tax"]]. (Note: in more complex lists, multiple paths of the same minimum length exist).

Common mistakes candidates make

  • Memory Limit Exceeded: Storing full paths inside the BFS queue. Instead, store only the word and its distance, and rebuild paths later.
  • Revisiting Nodes: Not correctly managing word "layers" in BFS, which is necessary to ensure you find all shortest paths without getting stuck in loops.
  • DFS without BFS: Trying to find all shortest paths using only DFS will result in an exhaustive search that is too slow.

Interview preparation tip

This problem is a great way to practice Layered BFS. Remember that when building the graph for multiple shortest paths, a word in layer i can have multiple parents in layer i-1.

Similar Questions