> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Word Ladder II Python Solution with Tests

> Tested Python solution for LeetCode 126 with 23 pytest cases. Generate a practice environment with lcpy.

LeetCode 126, [Hard](/catalog/hard). Topics: [Hash Table](/catalog/topics/hash-table), [String](/catalog/topics/string), [Backtracking](/catalog/topics/backtracking), [Breadth-First Search](/catalog/topics/breadth-first-search), Bidirectional Search. [View on LeetCode](https://leetcode.com/problems/word-ladder-ii/description/).

Generate this problem as a practice environment: tested reference solution, 23 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 126   # by problem number
lcpy gen -s word_ladder_ii   # by problem name
```

## Problem

A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:

* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`.
* `sk == endWord`

Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return *all the **shortest transformation sequences** from* `beginWord` *to* `endWord`*, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words* `[beginWord, s1, s2, ..., sk]`.

### Examples

```
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 2 shortest transformation sequences: "hit" -> "hot" -> "dot" -> "dog" -> "cog" and "hit" -> "hot" -> "lot" -> "log" -> "cog".

```
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
Output: []
```

**Explanation:** The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.

### Constraints

* 1 \<= beginWord.length \<= 5
* endWord.length == beginWord.length
* 1 \<= wordList.length \<= 500
* wordList\[i].length == beginWord.length
* beginWord, endWord, and wordList\[i] consist of lowercase English letters.
* beginWord != endWord
* All the words in wordList are unique.
* The sum of all shortest transformation sequences does not exceed 10^5.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/word_ladder_ii/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/word_ladder_ii/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from string import ascii_lowercase


class Solution:
    # Time: O(N * L^2) BFS over N words of length L, plus backtracking over the
    # shortest-path DAG bounded by the total output size.
    # Space: O(N * L) for the parent graph and recursion stack.
    def find_ladders(self, begin_word: str, end_word: str, word_list: list[str]) -> list[list[str]]:
        words = set(word_list)
        if end_word not in words:
            return []
        words.discard(begin_word)

        parents: dict[str, list[str]] = {}
        level = [begin_word]
        reached = False
        while level and not reached:
            discovered: dict[str, list[str]] = {}
            for word in level:
                for i in range(len(word)):
                    prefix, suffix = word[:i], word[i + 1 :]
                    for ch in ascii_lowercase:
                        candidate = prefix + ch + suffix
                        if candidate in words and candidate not in parents:
                            discovered.setdefault(candidate, []).append(word)
            reached = end_word in discovered
            for candidate, defs in discovered.items():
                parents[candidate] = defs
                words.discard(candidate)
            level = list(discovered)

        paths: list[list[str]] = []
        if not reached:
            return paths
        self._backtrack(end_word, begin_word, parents, [end_word], paths)
        return paths

    def _backtrack(
        self,
        word: str,
        begin_word: str,
        parents: dict[str, list[str]],
        path: list[str],
        paths: list[list[str]],
    ) -> None:
        if word == begin_word:
            paths.append(path[::-1])
            return
        for parent in parents[word]:
            path.append(parent)
            self._backtrack(parent, begin_word, parents, path, paths)
            path.pop()
```

## Complexity

| Time | Space |
| - | - |
| O(N \* L^2) BFS over N words of length L, plus backtracking over the | O(N \* L) for the parent graph and recursion stack. |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.