#127
Hard
BFS / DFS

Word Ladder

Find the shortest transformation sequence from beginWord to endWord.

BFS

Pattern fit

Every valid transformation is an edge in an implicit unweighted graph, so shortest steps means BFS almost immediately.

Key observation

The hard part is not BFS itself but generating neighbors efficiently without trying every word naively.

Target complexity

O(N * L * alphabet) / O(N)

How to break down the solution cleanly

1

Every valid transformation is an edge in an implicit unweighted graph, so shortest steps means BFS almost immediately.

2

The hard part is not BFS itself but generating neighbors efficiently without trying every word naively.

3

Identify the graph model and how neighbors are generated.

4

Choose BFS for shortest unweighted distance or DFS for structure exploration.

Reference implementation

Python
# Generic pattern template
from collections import deque

def bfs(start):
    queue = deque([start])
    visited = {start}
    while queue:
        node = queue.popleft()
        for nxt in graph[node]:
            if nxt not in visited:
                visited.add(nxt)
                queue.append(nxt)

def dfs(node):
    visited.add(node)
    for nxt in graph[node]:
        if nxt not in visited:
            dfs(nxt)

Common pitfalls

warning

Generating neighbors too expensively and timing out.

warning

Marking visited too late and revisiting the same word many times.

Common follow-ups

How does bidirectional BFS improve this?

What exactly is the graph node in this problem?

Continue with related problems

Build repeatable depth inside the BFS / DFS cluster before moving on.

view_weekBack to the pattern page
LeetCode 127. Word Ladder Guide | Interview AiBox