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ᵢ for 1 ≤ i ≤ k is in wordList
  • Note that beginWord does not need to be in wordList
  • 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
Word Ladder: Transform 'hit' → 'cog'Start:hithotdotdogTarget:cogi→oh→dt→gd→cWord Dictionary (wordList)hotdotdoglotlogcogAll intermediate words must be in this dictionaryResult: 5Transformation sequence length: hit → hot → dot → dog → cog
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
Asked in
Amazon 65 Facebook 45 Google 38 Microsoft 32 Apple 25
287.3K Views
High Frequency
~25 min Avg. Time
8.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen