Word Ladder
Master this topic with zero to advance depth.
Word Ladder
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words such that:
- Every adjacent pair of words differs by a single letter.
- Every
s_ifor1 <= i <= kis inwordList. s_k == endWord.
Return the number of words in the shortest transformation sequence, or 0 if no such sequence exists.
Visual Representation
Begin: "hit", End: "cog", List: ["hot","dot","dog","lot","log","cog"]
"hit" -> "hot" -> "dot" -> "dog" -> "cog"
Path length: 5Examples
hit -> hot -> dot -> dog -> cog (5 words).
Level I: Brute Force (BFS with Word Comparison)
Intuition
The simplest BFS approach is to compare the current word with every word in the dictionary to find neighbors (words with only 1 character difference).
Thought Process
- Use a Queue for BFS, starting with
(beginWord, 1). - In each step:
- Pop
word, dist. - Iterate through every
winwordList:- If
wis not visited andisNeighbor(word, w):- If
w == endWord, returndist + 1. - Mark
was visited and add to queue.
- If
- If
- Pop
Why it's Level I
If is the number of words, this involves comparisons for every word we visit, leading to total work.
Detailed Dry Run
"hit" -> "cog", ["hot", "dot", "dog", "cog"]
- "hit": neighbors? Scan list. Found "hot".
- "hot": neighbors? Scan list. Found "dot", "lot".
- "dot": neighbors? Scan list. Found "dog".
- "dog": neighbors? Scan list. Found "cog". DONE.
Level III: Optimal (BFS with Char Change)
Intuition
Instead of comparing with every word, we can generate all 26 possible neighbors for each character position. This is much faster when the alphabet size is small.
Thought Process
- Store all words in a set for lookups.
- Use a Queue for BFS, starting with
(beginWord, 1). - While the queue is not empty:
- Pop
word, dist. - For each character position in
word:- Replace
word[i]with every letter from 'a' to 'z'. - If the new string exists in the set:
- If it's the
endWord, returndist + 1. - Add to queue and remove from set (marking it visited).
- If it's the
- Replace
- Pop
Pattern: BFS State Generation
Detailed Dry Run
hit -> hot -> dot -> dog -> cog
- hit: change h to i,j,k... change i to a,b,c... change t to a,b,c,s,o (hot!)
- Add hot to queue, remove from set.
- Process 'hot' similarly.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.