Word Ladder - Problem
Word Ladder is a classic transformation puzzle where you need to find the shortest path from one word to another by changing exactly one letter at a time.
Given a
Example: Transform "
Path: "
Return
Given a
beginWord, an endWord, and a dictionary wordList, you need to find the minimum number of words in the transformation sequence from beginWord to endWord. Each intermediate word must be in the dictionary, and each step can only change one letter.Example: Transform "
hit" → "cog" using dictionary ["hot","dot","dog","lot","log","cog"]Path: "
hit" → "hot" → "dot" → "dog" → "cog" = 5 wordsReturn
0 if no transformation sequence exists. Input & Output
example_1.py — Basic Transformation
$
Input:
beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
›
Output:
5
💡 Note:
One shortest transformation sequence is "hit" → "hot" → "dot" → "dog" → "cog", which has 5 words.
example_2.py — No Path Exists
$
Input:
beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
›
Output:
0
💡 Note:
The endWord "cog" is not in wordList, so no transformation sequence is possible.
example_3.py — Direct Transformation
$
Input:
beginWord = "a", endWord = "c", wordList = ["a","b","c"]
›
Output:
2
💡 Note:
The shortest transformation sequence is "a" → "c" with 2 words.
Visualization
Tap to expand
Understanding the Visualization
1
Initial Ripple
Start with beginWord as the center point (level 1)
2
First Wave
Explore all words reachable in 1 transformation (level 2)
3
Expanding Waves
Continue expanding to words reachable in 2, 3, 4... transformations
4
Target Reached
The first wave to touch endWord gives us the shortest path
Key Takeaway
🎯 Key Insight: BFS is perfect for shortest path problems in unweighted graphs because it explores nodes level by level, ensuring the first time we reach our destination is via the shortest route.
Time & Space Complexity
Time Complexity
O(M×N×26)
M words in wordList, N length of each word, 26 letters to try for each position
✓ Linear Growth
Space Complexity
O(M)
Queue storage and visited set, both bounded by number of words
✓ Linear Space
Constraints
- 1 ≤ beginWord.length ≤ 10
- endWord.length == beginWord.length
- 1 ≤ wordList.length ≤ 5000
- wordList[i].length == beginWord.length
- All strings contain only lowercase English letters
- All the strings in wordList are unique
- beginWord ≠ endWord
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code