Word Ladder

Hard#127states

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
beginWord and endWord: 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 beginWord to endWord, both of them included. A step changes one letter of the word, and the word it makes must be in wordList; beginWord need not be there. 0 if 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
our 13 tests keep to them
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

13 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more breadth-first search (bfs) problems

Pattern “Breadth-first search (BFS)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.