0:00 / 0:00

Change one letter at a time to reach the end word. Treat words as a graph and search breadth first, so the first hit is the shortest.

▼

The problem

LeetCode 127 (Hard). Given beginWord, endWord and a wordList, find the shortest transformation sequence from beginWord to endWord that changes one letter at a time, where every word after beginWord is in wordList. Return the number of words in it, or 0 if there is none.

Example (the original's): hit → cog with [hot, dot, dog, lot, log, cog] → 5 (hit → hot → dot → dog → cog).

TRY IT ON LEETCODE ▶

The solution

def ladder_length(begin, end, word_list):
    words = set(word_list)
    if end not in words:
        return 0
    queue = deque([(begin, 1)])
    seen = {begin}
    while queue:
        word, steps = queue.popleft()
        if word == end:
            return steps
        for i in range(len(word)):
            for c in 'abcdefghijklmnopqrstuvwxyz':
                nxt = word[:i] + c + word[i+1:]
                if nxt in words and nxt not in seen:
                    seen.add(nxt)
                    queue.append((nxt, steps + 1))
    return 0

Transcript

Word Ladder. Change one word into another, one letter at a time, where every word along the way must be in a word list. Return the number of words in the shortest ladder, or zero if there isn't one.

Take hit to cog, with hot, dot, dog, lot, log and cog. Hit, hot, dot, dog, cog: five words. Take cog off the list, and the ladder can't finish: zero.

The naive way tries every sequence with depth-first search, and keeps the shortest. This tiny list already has eight ways up, and with more words the count explodes.

The key idea: each word is a node, linked to every word one letter away. The shortest ladder is the shortest path, so use breadth-first search. It explores level by level, so the first time it reaches the end word, that ladder is the shortest.

To find neighbors, try all twenty-six letters at each position. For hot, the first position gives dot and lot. A seen set makes sure no word is queued twice.

In code: put the list in a set, and return zero if the end word is missing. Queue the begin word at step one. Pop a word; if it's the end, return its steps. Otherwise, try every letter at every position, and queue each unseen word with one more step.

Let's climb. Hit is floor one. Change the middle letter: hot, floor two. From hot, dot and lot, floor three. Then dog and log, floor four. Dog changes d to c: cog, floor five. Log reaches cog too, but it's already seen. Cog comes off the queue, and it's the end: the answer is five.

Each of n words is queued at most once. For each of its L positions we try twenty-six letters, and building each new word costs L: n times L squared, times twenty-six. The queue and the set hold up to n words: n times L space.

One letter per step, one floor per level, first arrival wins. That's Word Ladder.