04. Word Ladder II

Difficulty:HardPattern:BFS Graph Distance + Backtracking DFSTime:O(N * L^2)Space:O(N * L)

Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord.

How It Works & Algorithmic Design

Solves using Bidirectional BFS Level Graph Construction + Backtracking DFS:

  1. BFS Level Mapping: Perform BFS starting from beginWord. Build distance map distMap[word] storing shortest steps from beginWord to every reachable dictionary word.
  2. DFS Path Backtracking: Backtrack from endWord down to beginWord:
    • Only step to neighbor words where distMap[neighbor] === distMap[current] - 1.
  3. Return: All collected minimum length paths.

Why This Approach Works Best

Decoupling minimum distance calculation (BFS) from path generation (DFS) prevents combinatorial path explosion.

Example Walkthrough

Input

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

Target conversion.

Shortest Paths

["hit","hot","dot","dog","cog"], ["hit","hot","lot","log","cog"]

Length 5 paths.

Output

List of both 5-step shortest paths.

All minimum transformations.

Answer: Word Ladder II BFS + DFS implementation

function findLadders(beginWord, endWord, wordList) {
  const wordSet = new Set(wordList);
  if (!wordSet.has(endWord)) return [];
  wordSet.add(beginWord);
  const dist = new Map();
  const queue = [beginWord];
  dist.set(beginWord, 0);
  while (queue.length) {
    const curr = queue.shift();
    const d = dist.get(curr);
    for (let i = 0; i < curr.length; i++) {
      for (let c = 97; c <= 122; c++) {
        const next = curr.substring(0, i) + String.fromCharCode(c) + curr.substring(i + 1);
        if (wordSet.has(next) && !dist.has(next)) {
          dist.set(next, d + 1);
          queue.push(next);
        }
      }
    }
  }
  if (!dist.has(endWord)) return [];
  const res = [];
  function dfs(word, path) {
    if (word === beginWord) {
      res.push([beginWord, ...path]);
      return;
    }
    const d = dist.get(word);
    for (let i = 0; i < word.length; i++) {
      for (let c = 97; c <= 122; c++) {
        const prev = word.substring(0, i) + String.fromCharCode(c) + word.substring(i + 1);
        if (dist.get(prev) === d - 1) {
          dfs(prev, [word, ...path]);
        }
      }
    }
  }
  dfs(endWord, []);
  return res;
}

Build shortest distance level graph using BFS, then generate valid minimum paths using DFS backtracking.

Key Takeaways
  • BFS measures shortest levels; DFS reconstructs exact matching paths.

  • Backtracking backwards from endWord reduces redundant branching.

  • Time complexity $O(N \cdot L^2)$.