sagelearnai

Word Ladder II

Difficulty: Hard · Pattern: Graphs (BFS / DFS) · LeetCode #126

Return all shortest transformation sequences from beginWord to endWord. Each step changes exactly one letter, and every intermediate word must be in wordList. Return [] if there is none. The sequences can be in any order.

Example

text
beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
→ [["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]]

Hints

  1. Start with Word Ladder I's BFS to get shortest distances.
  2. Don't store whole paths in the queue, because memory blows up. Store, for each word, its parents in the previous layer.
  3. Remove a whole layer of words from the dictionary only after the layer is done, so two parents in the same layer can both point to one child.

Approach

  1. Layered BFS from beginWord: for each word in the current layer, try all 26 × L one-letter changes. Any candidate still in the unvisited set becomes part of the next layer, and we record parents[next].add(word). Only after the whole layer is processed do we remove the next layer's words from the unvisited set. That's what allows multiple shortest parents.
  2. Stop after the layer that reaches endWord.
  3. Backtrack from endWord through parents to beginWord, building every path, then reverse each one.

Storing parents instead of paths keeps memory at O(edges in the shortest-path DAG).

Complexity

Time: O(N · L · 26) for the BFS, plus the output size. Space: O(N · L).

Python solution
from collections import defaultdict

def findLadders(beginWord, endWord, wordList):
    words = set(wordList)
    if endWord not in words:
        return []
    parents = defaultdict(set)
    layer, found = {beginWord}, False
    words.discard(beginWord)
    while layer and not found:
        nxt = defaultdict(set)
        for w in layer:
            for i in range(len(w)):
                for ch in 'abcdefghijklmnopqrstuvwxyz':
                    cand = w[:i] + ch + w[i + 1:]
                    if cand in words:
                        nxt[cand].add(w)
                        if cand == endWord:
                            found = True
        words -= set(nxt)
        for k, ps in nxt.items():
            parents[k] |= ps
        layer = set(nxt)
    if not found:
        return []
    res = []
    def build(w, path):
        if w == beginWord:
            res.append(path[::-1])
            return
        for p in parents[w]:
            path.append(p)
            build(p, path)
            path.pop()
    build(endWord, [endWord])
    return res
JavaScript solution
function findLadders(beginWord, endWord, wordList) {
  const words = new Set(wordList);
  if (!words.has(endWord)) return [];
  words.delete(beginWord);
  const parents = new Map();
  let layer = [beginWord], found = false;
  while (layer.length && !found) {
    const next = new Map();
    for (const w of layer) {
      for (let i = 0; i < w.length; i++) for (let c = 97; c < 123; c++) {
        const cand = w.slice(0, i) + String.fromCharCode(c) + w.slice(i + 1);
        if (!words.has(cand)) continue;
        if (!next.has(cand)) next.set(cand, new Set());
        next.get(cand).add(w);
        if (cand === endWord) found = true;
      }
    }
    for (const [k, ps] of next) { words.delete(k); parents.set(k, ps); }
    layer = [...next.keys()];
  }
  if (!found) return [];
  const res = [], path = [endWord];
  const build = (w) => {
    if (w === beginWord) { res.push([...path].reverse()); return; }
    for (const p of parents.get(w)) { path.push(p); build(p); path.pop(); }
  };
  build(endWord);
  return res;
}