Problem Description
Given two words, beginWord and endWord, and a wordList, the goal is to find all the shortest transformation sequences from beginWord to endWord. A transformation sequence is a list of words where every adjacent pair of words differs by one letter and each intermediate word exists in wordList. If no valid sequence exists (for example, if endWord is not in wordList), return an empty list.
Key Insights
- Use Breadth-First Search (BFS) to traverse level-by-level and capture only the shortest paths.
- Build a parent mapping during BFS to record which words lead to each newly discovered word.
- Once the shortest path is found via BFS, use backtracking (or DFS) from endWord to reconstruct all transformation sequences.
- Remove words as they are visited within a level to avoid unnecessary revisits and cycles.
- The solution must handle multiple shortest paths, so maintaining a list of predecessors for each word is crucial.
Space and Time Complexity
Time Complexity: O(N * L * 26) where N is the number of words in the wordList and L is the length of each word. This accounts for checking all possible one-letter transformations. Space Complexity: O(N * L) for storing the parent mapping and maintaining the BFS queue and other auxiliary data structures.
Solution
We solve the problem in two major phases:
- Use BFS to explore from beginWord to endWord. During BFS, record all parents for each word encountered. This ensures we capture all possible predecessors that yield a shortest transformation.
- Once the BFS completes (once endWord is reached), use backtracking (DFS) beginning from the endWord and moving backwards via the parent mapping to reconstruct all transformation sequences in reverse. Finally, reverse each sequence to present it from beginWord to endWord.
This two-phase approach guarantees that only the shortest paths are reconstructed, as BFS ensures level-by-level exploration.