Word Ladder

Hard

Topics
GraphBFSHash Table

Given beginWord, endWord, and a wordList, return the number of words in the shortest transformation sequence from begin to end (changing one letter at a time, each intermediate word in the list), or 0 if none. The count includes both endpoints.

Example 1

hithotdotdoglotlogcog
the shortest chain
Two words are neighbours when they differ in exactly one letter, which turns the word list into a graph and the question into a shortest path. The shaded chain is hit → hot → dot → dog → cog, so the answer counts 5 words — words, not steps.
The first chip is beginWord; the rest are wordList.
Input:  beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5

Example 2

hithotdotdoglotlog
cog is not reachable by single-letter edits through the given list (and the end word must itself be in the list), so the answer is 0.
Input:  beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
Output: 0

Constraints

  • 1 <= word length <= 10
  • 1 <= wordList.length <= 5000
  • All words have the same length.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Words are nodes; an edge connects two words differing by one letter. The shortest transformation is a shortest path, so BFS from beginWord finds it in the fewest steps.

Approach

  1. Put wordList in a set; if endWord is absent, return 0.
  2. BFS from beginWord, tracking the level (sequence length).
  3. From each word, try all one-letter changes; enqueue those in the set and not yet visited.

Dry Run

beginWord = hit, endWord = cog, wordList = [hot, dot, dog, lot, log, cog]

pop (hit, 1)   neighbours in the set: hot              queue (hot, 2)
pop (hot, 2)   neighbours: dot, lot                    queue (dot, 3) (lot, 3)
pop (dot, 3)   neighbours: dog                         queue (dog, 4)
pop (lot, 3)   neighbours: log                         queue (log, 4)
pop (dog, 4)   neighbours: cog                         queue (cog, 5)
pop (log, 4)   cog already seen, nothing queued
pop (cog, 5)   equals endWord                          return 5

answer 5   (hit to hot to dot to dog to cog)

Two things the trace shows. The depth is stored with the word rather than
tracked separately, so there is no level bookkeeping. And `seen` is marked when
a word is QUEUED, not when it is popped -- log finds cog already seen and
queues nothing, which is what stops the same word entering the queue twice.

Complexity

  • Time — O(N * L * 26): for each of N words, L positions times 26 letters.
  • Space — O(N * L): the visited set and queue.

Common Pitfalls

  • Mark a word seen when you enqueue it, not when you pop it. Marking on pop lets the same word enter the queue many times before any of them is processed, and the run does not finish -- it times out rather than returning something wrong.
  • Generating all 26 single-character substitutions is O(26 L) per word, which beats comparing against every word in the list when the list is large. That trade is the actual content of this problem.

Full Solution — all languages

class Solution:
    def ladderLength(self, beginWord, endWord, wordList):
        words=set(wordList)
        if endWord not in words: return 0
        from collections import deque
        q=deque([(beginWord,1)]); seen={beginWord}
        while q:
            w,d=q.popleft()
            if w==endWord: return d
            for i in range(len(w)):
                for c in 'abcdefghijklmnopqrstuvwxyz':
                    nxt=w[:i]+c+w[i+1:]
                    if nxt in words and nxt not in seen:
                        seen.add(nxt); q.append((nxt,d+1))
        return 0
SensAI
Beta
Tap the mic to stop voice mode