Word Ladder
1 approach, code in every language
Problem description
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 unique
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Dial Code Rewrite is our own problem on the technique behind Word Ladder: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free