Word Ladder
You get a begin word, an end word and a list of words of the same length. A ladder goes from the begin word to the end word, changing one letter at a time, and every word after the first must be in the list. Return how many words the shortest ladder has, counting both ends, or 0 if there is none. Our example: sit → pan with the list [pit, sat, pat, pan] — the answer is 4.
- input
beginWordandendWord: two different words of the same length;wordList: the words a step may make, all different.- returns
- The number of words in the shortest sequence from
beginWordtoendWord, both of them included. A step changes one letter of the word, and the word it makes must be inwordList;beginWordneed not be there.0if there is no such sequence. - constraints
- 1 ≤ beginWord.length ≤ 10
- endWord.length = wordList[i].length = beginWord.length
- 1 ≤ wordList.length ≤ 1000
- beginWord, endWord, wordList[i]: lowercase English letters
- beginWord ≠ endWord
- the words of wordList are all different
- examples
- Open a test in the tests panel: it shows the input and the expected answer.
/**
* @param {string} beginWord
* @param {string} endWord
* @param {string[]} wordList
* @return {number}
*/
function ladderLength(beginWord, endWord, wordList) {
}
Ctrl ↵
format
reset
saved in this browser
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more breadth-first search (bfs) problems
- 637Average of Levels in Binary TreeEasysolve
- 102Binary Tree Level Order TraversalMediumsolve
- 199Binary Tree Right Side ViewMediumsolve
- 994Rotting OrangesMediumsolve
- 1091Shortest Path in Binary MatrixMedium
- 841Keys and RoomsMediumsolve
- 117Populating Next Right Pointers in Each Node IIMediumsolve
- 103Binary Tree Zigzag Level Order TraversalMediumsolve
- 909Snakes and LaddersMediumsolve
- 433Minimum Genetic MutationMediumsolve
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.