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.
Input: beginWord = "hit", endWord = "cog", wordList = [hot,dot,dog,lot,log,cog] Output: 5 hit → hot → dot → dog → cog, five words.
Input: beginWord = "hit", endWord = "cog", wordList = [hot,dot,dog,lot,log] Output: 0 endWord 'cog' isn't in the list, so no sequence exists.
- 1 <= word length <= 10 - 1 <= wordList.length <= 5000 - all words have the same length - all words are lowercase and distinct
Hidden inside the word list is a graph: each word is a node, and two words are connected if they differ by exactly one letter. The shortest transformation sequence is then the shortest path from beginWord to endWord — and since every step costs 1, BFS finds it. The sequence length is the BFS depth at which endWord is reached.
The only real choice is how to find a word's neighbours:
O(N²·L) to explore.O(N·L·26), usually far faster.Both do the same BFS and return the same length.
“Does the length include both ends?”
Yes — it counts every word in the sequence.
“Must endWord be in the list?”
Yes, or the answer is 0.
Words are nodes; one-letter changes are edges. I BFS from beginWord and return the depth at which I reach endWord.
I find neighbours by trying all 26 letters at each position and checking a hash set — much faster than comparing every pair.
Worked example — begin = "hit", end = "cog", wordList = [hot, dot, dog, lot, log, cog]
hit -> hot -> dot -> dog -> cog (or via lot/log) length = 5
The word list is a graph.
Unit-step shortest path.
26·L candidates vs comparing all N words.
| Pairwise BFS | Variation BFS | |
|---|---|---|
| Neighbours | compare with every word | try 26 letters per position |
| Time | O(N²·L) | O(N·L·26) |
| Result | same length | same length |
Both run the same BFS; generating variations is faster when the list is large. Full code is in the Approaches selector below.
Key takeaway
Words are nodes, one-letter changes are edges; BFS from beginWord gives the shortest length at endWord. Find neighbours by trying all 26 letters per position against a hash set.
BFS from begin; neighbour = one-letter change that's in the set return depth at endWord, else 0