> ## 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 Python Solution with Tests

> Tested Python solution for LeetCode 127 with 15 pytest cases. Generate a practice environment with lcpy.

LeetCode 127, Hard. Topics: Hash Table, String, Breadth-First Search. [View on LeetCode](https://leetcode.com/problems/word-ladder/description/).

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

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 127   # by problem number
lcpy gen -s word_ladder   # 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 the **number of words** in the **shortest transformation sequence** from `beginWord` to `endWord`, or `0` if no such sequence exists.

### Examples

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

**Explanation:** One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> "cog", which is 5 words long.

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

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

### Constraints

* 1 \<= beginWord.length \<= 10
* endWord.length == beginWord.length
* 1 \<= wordList.length \<= 5000
* wordList\[i].length == beginWord.length
* beginWord, endWord, and wordList\[i] consist of lowercase English letters.
* beginWord != endWord
* All the words in wordList are unique.

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(M^2 * N) where M is length of each word, N is total number of words
    # Space: O(M * N) for the visited sets
    def ladder_length(self, begin_word: str, end_word: str, word_list: list[str]) -> int:
        if end_word not in word_list:
            return 0

        if begin_word == end_word:
            return 1

        word_set = set(word_list)
        begin_set = {begin_word}
        end_set = {end_word}
        length = 1

        while begin_set and end_set:
            if len(begin_set) > len(end_set):
                begin_set, end_set = end_set, begin_set

            next_set = set()
            for word in begin_set:
                for i in range(len(word)):
                    for c in "abcdefghijklmnopqrstuvwxyz":
                        new_word = word[:i] + c + word[i + 1 :]

                        if new_word in end_set:
                            return length + 1

                        if new_word in word_set:
                            next_set.add(new_word)
                            word_set.remove(new_word)

            begin_set = next_set
            length += 1

        return 0
```

## Complexity

| Time                                                                   | Space                          |
| ---------------------------------------------------------------------- | ------------------------------ |
| O(M^2 \* N) where M is length of each word, N is total number of words | O(M \* N) for the visited sets |

## Tags

[Grind 75](/catalog/grind-75), [Grind](/catalog/grind), [NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode), [AlgoMaster 75](/catalog/algo-master-75).
