Skip to problem
←

Word Ladder

Hard 0 attempts

You're given beginWord, endWord, and a list wordList. Each step lets you change exactly one letter of the current word, and whatever word results must appear in wordList. Find how many words long the shortest such chain from beginWord to endWord is, counting both endpoints; if no such chain exists, the answer is 0.

All words have the same length and contain lowercase English letters. You may only replace one letter per step; inserting, deleting, or leaving the word unchanged is not a move.

beginWord does not have to be in wordList, but endWord and every word after the starting word must be. The endpoints are different.

For the first example, hit → hot → dot → dog → cog contains 5 words and 4 changes, so return 5. Return only the length, not the chain itself.

Function contract

Implement ladderLength(beginWord, endWord, wordList).

Output: Return the number of words in the shortest valid chain, including both endpoints, or 0 if no chain exists.

Example 1

Input
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
Output
5

Example 2

Input
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
Output
0
Constraints
  • 1 <= beginWord.length <= 10
  • endWord.length == beginWord.length
  • 1 <= wordList.length <= 5000
  • beginWord and endWord are different.
  • All words contain only lowercase English letters and have the same length as beginWord.
  • All words in wordList are unique.

Breadth-first search

Treat words as vertices and one-letter changes as edges. BFS explores all chains of a given length before longer chains, so the first discovery of the end word gives the shortest length. Start at length 1 to count the beginning word.

Generate neighbors by replacing each position with each other lowercase letter. Only dictionary members can be enqueued. Mark words visited when enqueuing them to avoid cycles and repeated work. If the end word is absent from the dictionary, no chain can reach it.

javascript
function ladderLength(beginWord, endWord, wordList) {
  const wordSet = new Set(wordList);
  if (!wordSet.has(endWord)) return 0;
  const q = [[beginWord, 1]];
  const visited = new Set([beginWord]);
  let head = 0;
  while (head < q.length) {
    const [word, len] = q[head++];
    for (let i = 0; i < word.length; i++) {
      for (let c = 97; c <= 122; c++) {
        if (c === word.charCodeAt(i)) continue;
        const next = word.slice(0,i) + String.fromCharCode(c) + word.slice(i+1);
        if (next === endWord) return len + 1;
        if (wordSet.has(next) && !visited.has(next)) {
          visited.add(next); q.push([next, len + 1]);
        }
      }
    }
  }
  return 0;
}

Time: O(M² × N) where M=word length, N=word list size | Space: O(M × N)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript