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 Problem - BFS Approach INPUT beginWord: "hit" endWord: "cog" wordList: "hot" "dot" "dog" "lot" "log" "cog" Graph Structure: hit hot dot lot ALGORITHM STEPS 1 Initialize BFS Queue: [(hit, 1)] Visited: {hit} 2 Process Level 1 hit --> hot (h->h,i->o,t->t) Queue: [(hot, 2)] 3 Process Level 2 hot --> dot, lot Queue: [(dot,3),(lot,3)] 4 Process Level 3 dot --> dog, lot --> log Queue: [(dog,4),(log,4)] BFS Tree: L1 L2 L3 L4 L5 hit hot dot lot dog log cog FINAL RESULT Shortest Path Found: "hit" 1 "hot" 2 "dot" 3 "dog" 4 "cog" 5 Output: 5 5 words in shortest path OK - Path exists! Key Insight: BFS guarantees the shortest path in an unweighted graph. Each word is a node, and edges connect words differing by exactly one letter. BFS explores level by level, so the first time we reach endWord, we've found the shortest transformation sequence. Time: O(N * M^2), Space: O(N * M). TutorialsPoint - Word Ladder | BFS Approach
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