Word Ladder

hard

Given beginWord, endWord, and a wordList, return the length of the shortest transformation sequence from beginWord to endWord such that: each step changes exactly one letter, every intermediate word is in wordList, and the length counts all words in the sequence (including both ends). Return 0 if no such sequence exists. beginWord need not be in wordList, but endWord must be.

Hints

Treat words as nodes; connect two words that differ by exactly one letter.
The shortest sequence is a shortest path — BFS from beginWord.
Find neighbours by trying all 26 letters at each position and checking a hash set.

Common doubts

The sequence lists every word visited, so the length is the number of nodes on the BFS path, including begin and end.
There are only 26·L possible one-letter neighbours of a word, independent of list size, so membership tests beat O(N) comparisons per word.
The sequence is just that word — length 1 (assuming it's a valid endpoint).

Interview follow-ups

Bidirectional BFS from both ends roughly halves the explored frontier.
That's Word Ladder II — track parents during BFS, then reconstruct the paths.

Fun facts

  • LeetCode 127 — Lewis Carroll invented word ladders in 1877.
  • Bidirectional BFS is the standard optimization interviewers look for here.

Asked at

AmazonFacebookGoogle
Frequently Sometimes Occasionally
Example 1
Input: beginWord = "hit", endWord = "cog", wordList = [hot,dot,dog,lot,log,cog]
Output: 5
hit → hot → dot → dog → cog, five words.
Example 2
Input: beginWord = "hit", endWord = "cog", wordList = [hot,dot,dog,lot,log]
Output: 0
endWord 'cog' isn't in the list, so no sequence exists.
Constraints

- 1 <= word length <= 10 - 1 <= wordList.length <= 5000 - all words have the same length - all words are lowercase and distinct

Solve this problem →