Python 0127.py
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if beginWord == endWord:
return 1
# hit => [ ".it", "h.t", "hi." ]
def dots(w):
for i in range(len(w)):
yield w[:i] + "." + w[i+1:]
offbyone = defaultdict(list)
for w in wordList:
for d in dots(w):
offbyone[d].append(w)
processed = set()
steps = 1
todo = set()
for d in dots(beginWord):
if d in offbyone:
todo.update(offbyone[d])
while todo:
next = set()
steps += 1
for i in todo:
if i == endWord:
return steps
# avoid loops
if i in processed:
continue
processed.add(i)
for d in dots(i):
next.update(offbyone[d])
todo = next
return 0
Difficulty
and has an acceptance rate of about 46% (3+ million submissions).
Typical patterns to solve this problem:
- Breadth First Search
- Hash Table
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the classic word-ladder problem: given a start word, a target word, and a list of allowed intermediate words, it returns the length of the shortest transformation sequence where each step changes exactly one character and the intermediate word must belong to the list. The algorithm follows a breadth-first search (BFS) strategy, but it introduces a preprocessing step that groups words by generic patterns containing a wildcard character. This preprocessing enables rapid neighbor discovery during the BFS traversal.
Early Exit
The function begins by handling the trivial case where the start and target words are identical. In that situation the shortest sequence consists of the single word itself, so the function returns 1 immediately.
if beginWord == endWord:
return 1
Pattern Generation
A helper generator produces all generic patterns for a given word by replacing each character, one at a time, with a dot (.). For a word of length L it yields L patterns. This abstraction allows words that differ by a single character to share at least one common pattern.
def dots(w):
for i in range(len(w)):
yield w[:i] + "." + w[i+1:]
Building the Adjacency Map
The core of the optimization lies in constructing a dictionary that maps each generic pattern to the list of words from wordList that match it. By iterating over every word and every pattern produced by dots, the code populates a defaultdict(list) called offbyone. This structure makes it possible to retrieve all one-letter-away neighbors of any word in constant time per neighbor.
offbyone = defaultdict(list)
for w in wordList:
for d in dots(w):
offbyone[d].append(w)
Initial Frontier
The BFS frontier is initialized with all words that are one transformation away from the beginWord. This is achieved by generating the patterns for beginWord and collecting the corresponding word lists from offbyone. The result is stored in a set named todo, which guarantees uniqueness of entries and provides O(1) membership checks.
todo = set()
for d in dots(beginWord):
if d in offbyone:
todo.update(offbyone[d])
BFS Loop
The algorithm enters a loop that continues as long as there are candidates in the current frontier. At each iteration it increments a step counter, creates a new empty set for the next frontier, and processes each word in the current frontier.
while todo:
next = set()
steps += 1
for i in todo:
if i == endWord:
return steps
if i in processed:
continue
processed.add(i)
for d in dots(i):
next.update(offbyone[d])
todo = next
End Condition
If a word from the frontier matches endWord, the function returns the current step count, which represents the length of the shortest transformation sequence.
Loop Prevention
A processed set records words that have already been expanded. Before expanding a word, the code checks whether it has been processed; if so, it skips further work. This prevents cycles and redundant exploration, ensuring each word contributes to the frontier at most once.
Expanding Neighbors
For each unprocessed word, the code generates its generic patterns and uses the precomputed offbyone map to retrieve all neighboring words. These neighbors are added to the next set, forming the frontier for the subsequent BFS level.
Edge Cases Handled
The implementation gracefully handles several edge conditions without special branching. When the wordList does not contain any words that share a pattern with beginWord, the initial todo set remains empty and the loop is never entered, causing the function to fall through to the final return statement of 0. This return value signals that no transformation sequence exists.
If endWord is absent from wordList, it will never appear in any adjacency list, so the BFS will exhaust all reachable words and ultimately return 0.
The use of sets for both the current and next frontiers automatically eliminates duplicate entries that could arise from multiple patterns leading to the same neighbor, thereby avoiding unnecessary repeated work.
Performance Optimizations
The code’s primary performance gain stems from the pattern-based adjacency map. By converting the problem of “find all words that differ by one character” into a series of dictionary lookups, the algorithm avoids the O(N · L) pairwise comparison that a naïve approach would require, where N is the size of wordList and L is the word length.
Using a generator for pattern creation (dots) reduces memory overhead compared to building a list of patterns for each word.
Storing the BFS frontiers in sets provides constant-time checks for membership and eliminates duplicate entries without extra passes.
The processed set ensures each word is expanded at most once, preventing exponential blow-up in the presence of many interconnecting words.
Collectively, these choices keep the search focused on the minimal necessary subset of the graph at each level, delivering an efficient solution for typical input sizes.
ELI5 - Simplified Explanation
Imagine playing a game where you want to change one word into another word, but you can only change one letter at a time. Every time you change a letter, the new word must be a real word that is on your list.
Think of it like stepping across a pond on lily pads. Each word on the list is a lily pad. You start at the beginning word and try to jump to the next word by changing just one letter, then change another letter to jump again, until you land on the final word.
The code starts by looking at every word and noticing which ones are almost the same. It does this by taking a word and putting a dot where a letter goes, so a word like cat becomes .at, c.t, and ca. to show how it can connect to other words like bat or cot.
It keeps a list of words that could be the next jump. In the beginning, it finds all the words that are only one letter away from the starting word. Then it looks at those words and finds all the words that are one letter away from them. It keeps doing this jump by jump, counting how many steps it takes to get to the end.
If it finds the target word at any point, it stops and says how many steps it took to get there. If it tries every possible jump and still cannot find the target word, it knows that the goal is impossible to reach. It is like mapping out a path through a secret garden to see how quickly one can reach the fountain.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | C# | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | aylei | Rust | |||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JS | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| Garvit244 | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lennylxx | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| wisdompeak | C++ | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, C#, Go, Java, Python, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| aylei | Rust | ||||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JavaScript | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| Garvit244 | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lennylxx | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| wisdompeak | C++ | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 126: Word Ladder II
- problem 433: Minimum Genetic Mutation
- problem 2452: Words Within Two Edits of Dictionary
Solved On The Same Day
- problem 144: Binary Tree Preorder Traversal
- problem 145: Binary Tree Postorder Traversal
- problem 222: Count Complete Tree Nodes
- problem 404: Sum of Left Leaves
- problem 501: Find Mode in Binary Search Tree
- problem 543: Diameter of Binary Tree
- problem 559: Maximum Depth of N-ary Tree
- problem 589: N-ary Tree Preorder Traversal
- problem 590: N-ary Tree Postorder Traversal
- problem 637: Average of Levels in Binary Tree
- problem 700: Search in a Binary Search Tree
- problem 703: Kth Largest Element in a Stream
- problem 79: Word Search
- problem 81: Search in Rotated Sorted Array II
- problem 97: Interleaving String
- problem 99: Recover Binary Search Tree
- problem 173: Binary Search Tree Iterator
- problem 199: Binary Tree Right Side View
- problem 230: Kth Smallest Element in a BST
- problem 235: Lowest Common Ancestor of a Binary Search Tree
- problem 341: Flatten Nested List Iterator
- problem 429: N-ary Tree Level Order Traversal
- problem 508: Most Frequent Subtree Sum
- problem 513: Find Bottom Left Tree Value
- problem 538: Convert BST to Greater Tree
- problem 65: Valid Number
- problem 85: Maximal Rectangle
- problem 87: Scramble String
- problem 126: Word Ladder II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality