Word Ladder II - Problem
Imagine you're a linguist working with word transformations! You need to find all the shortest possible paths to transform one word into another by changing exactly one letter at a time.
Given a beginWord, an endWord, and a dictionary of valid words (wordList), your task is to return all the shortest transformation sequences from beginWord to endWord.
Rules for transformation:
- Each step changes exactly one letter
- Every intermediate word must exist in the
wordList - The
beginWorddoesn't need to be inwordList - All words have the same length and contain only lowercase letters
Example: Transform "hit" → "cog"
Possible path: ["hit", "hot", "dot", "dog", "cog"]
Another path: ["hit", "hot", "lot", "log", "cog"]
Return an empty list if no transformation sequence exists. If multiple shortest paths exist, return all of them!
Input & Output
example_1.py — Basic Transformation
$
Input:
beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
›
Output:
[["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]]
💡 Note:
There are 2 shortest transformation sequences of length 5. Both start with 'hit'→'hot', then diverge: one goes through 'dot'→'dog' and the other through 'lot'→'log', both ending at 'cog'.
example_2.py — No Valid Path
$
Input:
beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
›
Output:
[]
💡 Note:
The endWord 'cog' is not in the wordList, so no transformation sequence is possible. We cannot transform to a word that doesn't exist in our dictionary.
example_3.py — Single Step
$
Input:
beginWord = "a", endWord = "c", wordList = ["a","b","c"]
›
Output:
[["a","c"]]
💡 Note:
Direct transformation from 'a' to 'c' in one step (changing one letter). This is the shortest possible path with length 2.
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
Visualization
Tap to expand
Understanding the Visualization
1
Build Word Graph
Create connections between words that differ by exactly one letter
2
BFS for Distances
Use BFS to find shortest distance from start word to all reachable words
3
Backtrack Paths
From end word, follow only edges leading to words closer to start
4
Collect Results
All valid backtracking paths give us the shortest transformation sequences
Key Takeaway
🎯 Key Insight: Use BFS to find shortest distances first, then backtrack following only edges that decrease distance by 1. This ensures we find ALL shortest paths efficiently without exploring suboptimal routes.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code