Skip to content
GKgkml.dev
← Problem set
#127HardGraphs

Word Ladder

The tell: Fewest transformations between two words — unit edge weights, so BFS is optimal.

How you get there

  1. 1Words are nodes; an edge exists when they differ by one letter.
  2. 2Comparing every pair is O(n²), so generate wildcard patterns instead.
  3. 3BFS from the start gives the shortest chain by construction.

Solution

Python
from collections import deque, defaultdict

def ladder_length(begin: str, end: str, word_list: list[str]) -> int:
    words = set(word_list)
    if end not in words:
        return 0

    buckets: dict[str, list[str]] = defaultdict(list)
    for word in words:
        for i in range(len(word)):
            buckets[word[:i] + "*" + word[i + 1 :]].append(word)

    queue = deque([(begin, 1)])
    seen = {begin}
    while queue:
        word, steps = queue.popleft()
        if word == end:
            return steps
        for i in range(len(word)):
            for nxt in buckets[word[:i] + "*" + word[i + 1 :]]:
                if nxt not in seen:
                    seen.add(nxt)
                    queue.append((nxt, steps + 1))
    return 0
Time
O(n · L²)
Space
O(n · L)

What goes wrong

Comparing every pair of words to build edges is correct but quadratic in the dictionary size.