graph
breadth-first-search
shortest-path
strings
A transformation sequence changes exactly one letter at a time, and every intermediate word must exist in wordList. Return the number of words in the shortest valid sequence from beginWord to endWord, including both endpoints. If no sequence exists, return 0.
All words have the same length.
Input / output
- Input:
beginWord: string,endWord: string,wordList: string[] - Output: integer shortest ladder length, or
0if impossible
Examples
beginWord = "hit",endWord = "cog",wordList = ["hot","dot","dog","lot","log","cog"]returns5forhit -> hot -> dot -> dog -> cog.beginWord = "hit",endWord = "cog",wordList = ["hot","dot","dog","lot","log"]returns0.beginWord = "lost",endWord = "cost",wordList = ["most","fist","lost","cost","fish"]returns2.
Constraints
1 <= beginWord.length <= 10beginWord.length == endWord.length1 <= wordList.length <= 5000wordList[i].length == beginWord.length- Words contain only lowercase English letters
Target complexity
- Aim for breadth-first search over implicit graph neighbors, because the first time BFS reaches
endWord, that path is guaranteed shortest.
Hints
- Treat each word as a graph node, where edges connect words differing by exactly one letter.
- You do not need to build every edge ahead of time; generate neighbors by changing one position at a time during BFS.
Follow-up What would a bidirectional BFS buy you here, and when is it worth the extra implementation complexity?
Examples
Example 1
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5
Example 2
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
Output: 0
Example 3
Input: beginWord = "lost", endWord = "cost", wordList = ["most","fist","lost","cost","fish"]
Output: 2
🔒 6 hidden
Running will execute all 9 cases, including 6 hidden ones.