Word Ladder - Problem
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words:
beginWord → s₁ → s₂ → ... → sₖ
Such that:
- Every adjacent pair of words differs by a single letter
- Every
sᵢfor1 ≤ i ≤ kis inwordList - Note that
beginWorddoes not need to be inwordList sₖ == endWord
Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.
Input & Output
Example 1 — 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 is 5 words long.
Example 2 — No Valid Path
$
Input:
beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
›
Output:
0
💡 Note:
The endWord "cog" is not in wordList, therefore no transformation sequence exists.
Example 3 — Direct Transformation
$
Input:
beginWord = "a", endWord = "c", wordList = ["a","b","c"]
›
Output:
2
💡 Note:
The shortest transformation is a → c, which is 2 words long.
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
Input
Start word 'hit', target 'cog', dictionary of valid words
2
Process
Find shortest path by changing one letter at a time
3
Output
Return length of shortest transformation sequence
Key Takeaway
🎯 Key Insight: Model as shortest path in unweighted graph - BFS finds optimal solution
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code