Solve LeetCode 127: Word Ladder in Python with a wildcard-neighbor BFS approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.
This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.
| Difficulty | Hard |
|---|---|
| Topic | Graph BFS |
| Reusable pattern | wildcard-neighbor BFS |
| Complexity | O(NL^2) preprocessing and traversal time and O(NL) space |
What the problem is testing
Index words by wildcard patterns, then BFS from the beginning word through words sharing a pattern.
Algorithm
- Index words by wildcard patterns, then BFS from the beginning word through words sharing a pattern.
- Maintain this invariant: The first BFS layer reaching a word uses the shortest transformation sequence.
- Continue until every input item or reachable state has been resolved, then return the accumulated result.
Python solution
from collections import Counter, defaultdict, deque, OrderedDict
import random
class Solution:
def ladderLength(self, beginWord, endWord, wordList):
if endWord not in wordList: return 0
patterns = defaultdict(list)
width = len(beginWord)
for word in wordList:
for i in range(width): patterns[word[:i] + "*" + word[i + 1:]].append(word)
queue, seen = deque([(beginWord, 1)]), {beginWord}
while queue:
word, distance = queue.popleft()
for i in range(width):
pattern = word[:i] + "*" + word[i + 1:]
for neighbor in patterns[pattern]:
if neighbor == endWord: return distance + 1
if neighbor not in seen:
seen.add(neighbor); queue.append((neighbor, distance + 1))
patterns[pattern] = []
return 0Why this is correct
The proof follows the maintained state: The first BFS layer reaching a word uses the shortest transformation sequence. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.
Complexity
O(NL^2) preprocessing and traversal time and O(NL) space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.
Edge cases
The end word must be in the dictionary; each transformation changes exactly one character.
Tested reference code
This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 433. Minimum Genetic Mutation · Next: 208. Implement Trie (Prefix Tree)