Word Transformation
Shortest Path
Algorithm
Computational Linguistics
Word Ladder

Shortest path to transform one word into another

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

The classic "word ladder" problem asks for the shortest sequence of valid words that transforms one word into another by changing one letter at a time. Because every valid one-letter change has equal cost, the correct core algorithm is breadth-first search.

Model the Problem as an Unweighted Graph

Treat each dictionary word as a node. Two words are connected if they differ by exactly one character and have the same length. Then the transformation problem becomes: find the shortest path from the start word to the target word.

For example, using the dictionary hit, hot, dot, dog, and cog, one valid path is:

hit -> hot -> dot -> dog -> cog

Because each step changes exactly one letter, every edge has the same weight. That is why BFS works: it explores all paths of length 1, then all paths of length 2, and so on until it reaches the goal.

A Straightforward BFS Solution

The simplest implementation generates neighbors by trying every letter in every position.

python
1from collections import deque
2from string import ascii_lowercase
3
4def shortest_word_path(start, target, words):
5    words = set(words)
6    if target not in words:
7        return None
8
9    queue = deque([(start, [start])])
10    visited = {start}
11
12    while queue:
13        word, path = queue.popleft()
14
15        if word == target:
16            return path
17
18        for i in range(len(word)):
19            for ch in ascii_lowercase:
20                if ch == word[i]:
21                    continue
22
23                candidate = word[:i] + ch + word[i + 1:]
24                if candidate in words and candidate not in visited:
25                    visited.add(candidate)
26                    queue.append((candidate, path + [candidate]))
27
28    return None
29
30
31dictionary = {"hit", "hot", "dot", "dog", "cog", "lot", "log"}
32print(shortest_word_path("hit", "cog", dictionary))

This version is easy to understand and works well for moderate dictionaries.

Why BFS Guarantees the Shortest Path

In an unweighted graph, BFS discovers nodes in increasing distance from the start. The first time you pop the target from the queue, you have found the fewest number of transformations possible.

Depth-first search does not give that guarantee. It may find a path quickly, but not the shortest one.

Speeding Up Neighbor Lookup

The expensive part is checking many candidate words. A common optimization is to build wildcard patterns such as h*t or *ot and map each pattern to matching words. Then you can find one-letter neighbors without trying all 26 letters in every position.

python
1from collections import defaultdict, deque
2
3def build_pattern_map(words):
4    patterns = defaultdict(list)
5    for word in words:
6        for i in range(len(word)):
7            pattern = word[:i] + "*" + word[i + 1:]
8            patterns[pattern].append(word)
9    return patterns
10
11
12def shortest_word_path_fast(start, target, words):
13    words = set(words)
14    words.add(start)
15    patterns = build_pattern_map(words)
16
17    queue = deque([(start, [start])])
18    visited = {start}
19
20    while queue:
21        word, path = queue.popleft()
22        if word == target:
23            return path
24
25        for i in range(len(word)):
26            pattern = word[:i] + "*" + word[i + 1:]
27            for neighbor in patterns[pattern]:
28                if neighbor not in visited:
29                    visited.add(neighbor)
30                    queue.append((neighbor, path + [neighbor]))
31
32    return None

This is especially useful when the dictionary is large and many repeated neighbor checks would otherwise occur.

Bidirectional BFS for Large Inputs

When the start and target are both known, bidirectional BFS can reduce search dramatically. Instead of exploring outward from only the start word, you explore from both ends and stop when the frontiers meet.

That technique does not change correctness, but it often cuts the number of visited nodes substantially in dense word graphs.

Input Constraints Matter

Only words of the same length can be part of one ladder under the one-letter-change rule. Filter the dictionary accordingly before you search.

You also need to decide whether the start word must already exist in the dictionary. Many formulations allow the start word even if it is not in the word list, while still requiring all intermediate words and the target to be valid dictionary entries.

Common Pitfalls

The most common mistake is using depth-first search and assuming the first solution found is shortest. It is not.

Another mistake is forgetting to mark words as visited when they are enqueued. If you wait until dequeue time, the same word can enter the queue many times and slow the search dramatically.

Developers also sometimes allow words of different lengths into the graph. That quietly breaks the one-letter-change assumption and creates invalid transitions.

Finally, be clear about output requirements. Some callers want only the path length; others need the full sequence of words. That choice affects how you store predecessor information.

Summary

  • Model the dictionary as an unweighted graph where edges connect one-letter variants.
  • Use breadth-first search because it guarantees the shortest transformation path.
  • Generate neighbors directly or precompute wildcard patterns for faster lookups.
  • Consider bidirectional BFS when the dictionary is large.
  • Filter by word length and track visited words carefully to avoid incorrect paths.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.