CodingNodes / Graphs / Word Ladder System design Space play · ←→ step · R restart

Problem

You start with beginWord and want to turn it into endWord by changing one letter at a time. Every word you produce along the way must be in wordList. The begin word itself does not have to be in the list.

Return the number of words in the shortest such sequence, counting both beginWord and endWord, or 0 if no sequence exists. All words have the same length and use lowercase letters.

Constraints

  • 1 ≤ word length ≤ 10
  • 1 ≤ wordList.length ≤ 5000; all words are different, lowercase letters only
  • beginWord ≠ endWord, and all words have the same length

Examples: pick one to animate

Solutions

TimeO(26 · N · L²) SpaceO(N · L)

Time: Each of the N words is queued at most once, and for each we build L × 26 candidate strings of length L, hashing each one in O(L), so the total is O(26 · N · L²).

Space: The word set, the seen set and the queue each hold at most N + 1 words of length L.

Every word is a node, and words one letter apart are joined. The shortest ladder is the shortest path from the begin word, so we run BFS one level at a time: the queue holds exactly the words that are `length` words away. Process all of them, queueing every new word that is in the list, then add one to `length`. The first time the end word is taken from the queue, `length` is the answer. If the queue empties first, there is no ladder.