Word Ladder
HardP2Coding
A transformation sequence from beginWord to endWord is a list of words in which each consecutive pair differs in exactly one letter and every word after the first is in wordList. beginWord itself does not need to be in the list.
Return the number of words in the shortest such sequence, counting both ends, or 0 if no sequence exists. If endWord is not in wordList, the answer is 0.
Example 1
- Input
- beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
- Output
- 5
- Why
- hit -> hot -> dot -> dog -> cog.
Example 2
- Input
- beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
- Output
- 0
- Why
- cog is not in the list.
Constraints
- 1 <= word length <= 10, all words have the same length
- 1 <= wordList.length <= 5000
- Words consist of lower-case letters
- beginWord != endWord; words in wordList are unique
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 9. ⌘Enter runs, ⌘⇧Enter submits.