Word Ladder II
Pattern: Shortest paths
Find all shortest sequences. First BFS from the begin word, recording each word's level, and stop once the end word's level is known. Then backtrack from the end word, stepping only to neighbours exactly one level closer to the start, which builds every shortest sequence and nothing else.
The problem
Return every shortest transformation sequence from beginWord to endWord (each step changes one letter and uses a word
from the list). The tests sort the sequences.
Think first
- Why not store every path during BFS?
- What does each word's BFS level tell you?
- Which neighbours are allowed when walking back?
Hints
Brute force, and why it fails
DFS every sequence up to the shortest length: exponential and slow.
The key insight
Levels from BFS form a layered graph where every backward step towards level 0 is part of some shortest sequence.
Dry run
begin hit, end cog. BFS levels: hit 0, hot 1, dot and lot 2, dog and log 3, cog 4.
The plan
BFS levels until end is reached
walkBack(word, path): if word == begin: record path reversed
for prev one letter away with level[prev] == level[word] - 1: walkBack(prev)
Complexity
- Time
O(N × L × 26 + output)- Space
O(N × L)
BFS plus the size of the answer.
Edge cases
- end not in the list: [].
- Exactly one shortest sequence.
- Many equal sequences.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<List<String>> findLadders(String beginWord, String endWord, String[] wordList) {
Set<String> words = new HashSet<>(Arrays.asList(wordList));
List<List<String>> out = new ArrayList<>();
if (!words.contains(endWord)) return out;
Map<String, Integer> depth = new HashMap<>(); // BFS level of every word reached
depth.put(beginWord, 0);
Queue<String> q = new ArrayDeque<>();
q.add(beginWord);
while (!q.isEmpty() && !depth.containsKey(endWord)) {
for (int size = q.size(); size > 0; size--) {
String w = q.poll();
for (String next : neighbours(w, words)) if (!depth.containsKey(next)) { depth.put(next, depth.get(w) + 1); q.add(next); }
}
}
if (!depth.containsKey(endWord)) return out;
LinkedList<String> path = new LinkedList<>();
path.add(endWord);
walkBack(endWord, beginWord, depth, words, path, out); // from the end, step only to the level just above
return out;
}
private void walkBack(String w, String begin, Map<String, Integer> depth, Set<String> words, LinkedList<String> path, List<List<String>> out) {
if (w.equals(begin)) { out.add(new ArrayList<>(path)); return; }
Set<String> pool = new HashSet<>(words);
pool.add(begin);
for (String prev : neighbours(w, pool)) {
Integer d = depth.get(prev);
if (d != null && d == depth.get(w) - 1) {
path.addFirst(prev);
walkBack(prev, begin, depth, words, path, out);
path.removeFirst();
}
}
}
private List<String> neighbours(String w, Set<String> pool) {
List<String> out = new ArrayList<>();
char[] c = w.toCharArray();
for (int i = 0; i < c.length; i++) {
char old = c[i];
for (char x = 'a'; x <= 'z'; x++) {
if (x == old) continue;
c[i] = x;
String s = new String(c);
if (pool.contains(s)) out.add(s);
}
c[i] = old;
}
return out;
}
}C++
class Solution {
public:
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> words(wordList.begin(), wordList.end());
vector<vector<string>> out;
if (!words.count(endWord)) return out;
unordered_map<string, int> depth; // BFS level of every word reached
depth[beginWord] = 0;
queue<string> q;
q.push(beginWord);
while (!q.empty() && !depth.count(endWord)) {
for (int size = static_cast<int>(q.size()); size > 0; size--) {
string w = q.front();
q.pop();
for (const string& next : neighbours(w, words)) if (!depth.count(next)) { depth[next] = depth[w] + 1; q.push(next); }
}
}
if (!depth.count(endWord)) return out;
unordered_set<string> pool(words);
pool.insert(beginWord);
vector<string> path(1, endWord);
walkBack(endWord, beginWord, depth, pool, path, out); // from the end, step only to the level just above
return out;
}
void walkBack(const string& w, const string& begin, unordered_map<string, int>& depth, unordered_set<string>& pool,
vector<string>& path, vector<vector<string>>& out) {
if (w == begin) { out.push_back(vector<string>(path.rbegin(), path.rend())); return; }
for (const string& prev : neighbours(w, pool)) {
if (depth.count(prev) && depth[prev] == depth[w] - 1) {
path.push_back(prev);
walkBack(prev, begin, depth, pool, path, out);
path.pop_back();
}
}
}
vector<string> neighbours(const string& w, const unordered_set<string>& pool) {
vector<string> out;
string c = w;
for (size_t i = 0; i < c.size(); i++) {
char old = c[i];
for (char x = 'a'; x <= 'z'; x++) {
if (x == old) continue;
c[i] = x;
if (pool.count(c)) out.push_back(c);
}
c[i] = old;
}
return out;
}
};Python
from collections import deque
class Solution:
def findLadders(self, beginWord: str, endWord: str, wordList: list[str]) -> list[list[str]]:
words = set(wordList)
if endWord not in words:
return []
def neighbours(w, pool):
return [w[:i] + x + w[i + 1:] for i in range(len(w)) for x in "abcdefghijklmnopqrstuvwxyz"
if x != w[i] and w[:i] + x + w[i + 1:] in pool]
depth, q = {beginWord: 0}, deque([beginWord]) # BFS level of every word reached
while q and endWord not in depth:
for _ in range(len(q)):
w = q.popleft()
for nxt in neighbours(w, words):
if nxt not in depth:
depth[nxt] = depth[w] + 1
q.append(nxt)
if endWord not in depth:
return []
pool, out = words | {beginWord}, []
def walk_back(w, path): # from the end, step only to the level just above
if w == beginWord:
out.append(path[::-1])
return
for prev in neighbours(w, pool):
if depth.get(prev) == depth[w] - 1:
walk_back(prev, path + [prev])
walk_back(endWord, [endWord])
return outCommon mistakes
- Walking back to words at the same level.
- Continuing BFS past the end word's level.