Word Ladder II
Problem link: https://leetcode.com/problems/word-ladder-ii/
Problem Statement
Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord. Each adjacent word must differ by exactly one letter.
Input
Two strings (beginWord, endWord) and a list of strings (wordList).
Output
A list of lists containing all shortest paths.
Example
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] Output: [["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]]
Explanation
There are two paths of length 5 that lead from 'hit' to 'cog'. Any other paths are either longer or do not exist.
Brute Force
Intuition
Use simple backtracking (DFS) to explore every possible path from beginWord to endWord.
Approach
- From current word, try changing every character (a-z).
- If the new word is in the dictionary, recurse.
- Keep track of the current path length and only store paths matching the global minimum found so far.
Complexity Analysis
Exponential time complexity due to exploring all possible paths, most of which are not the shortest.
Optimal Solution
Intuition
A two-step approach:
- BFS to find the shortest distance from
beginWordto all reachable words and map the 'parent-child' relationships. - Backtracking (DFS) to traverse the map from
endWordback tobeginWord(or vice versa) to build only the shortest paths.
Approach
- Use a
SetforwordListfor O(1) lookups. - BFS Phase: Store the level/distance of each word from
beginWordin aHashMap<String, Integer>. This ensures we only move 'forward' in levels during reconstruction. - DFS Phase: Start from
endWord. For the current word, look at all neighbors (1-char diff). If a neighbor's level is exactlycurrentLevel - 1, it is part of a shortest path. Recurse untilbeginWordis reached. - Reverse the paths found if you backtracked from end to start.
Dry Run
begin: 'hit', end: 'cog'. BFS: hit(0) -> hot(1) -> {dot, lot}(2) -> {dog, log}(3) -> cog(4). DFS from 'cog': Finds neighbors at level 3 ('dog', 'log'), then their neighbors at level 2, etc.
Code (Java)
Complexity Analysis
N is words in list, L is word length, K is number of shortest paths. BFS takes O(N * 26 * L). DFS time depends on the number of paths.
Quick Revision (Brute Force)
- Simple DFS
- Inefficient: visits non-shortest paths
Quick Revision (Optimal)
- BFS + Backtracking
- BFS stores min steps to each word
- DFS reconstructs paths using level check: (level[neighbor] == level[current] - 1)
- O(N * 26 * L) time