You are given two words, beginWord and endWord, together with a dictionary wordList.
A transformation sequence starts at beginWord and ends at endWord. At each step you may change exactly one letter, and every word produced after the first step must appear in wordList. Note that beginWord itself does not need to be in wordList.
Return the number of words in the shortest transformation sequence from beginWord to endWord. If no such sequence exists, return 0.
Example 1
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5
One shortest sequence is "hit" -> "hot" -> "dot" -> "dog" -> "cog", which contains 5 words.
Example 2
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
Output: 0
endWord "cog" is not present in wordList, so no valid sequence can end at it.
Constraints
1 <= beginWord.length <= 10endWord.length == beginWord.length1 <= wordList.length <= 5000wordList[i].length == beginWord.lengthbeginWord, endWord, and wordList[i] consist of lowercase English lettersbeginWord != endWordAll the words in wordList are uniqueSee the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI