Word Ladder (LeetCode 127): Solution and Explanation

Hard
Hash Table
String
Breadth First Search

You are given a start word, a target word and a dictionary. Each step changes exactly one letter, and every intermediate word must be in the dictionary. Return the number of words in the shortest transformation sequence from start to target, counting both ends, or 0 if no such sequence exists.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Picture every word as a node and connect two words when they differ in exactly one position. The question is then the length of the shortest path between two nodes in an unweighted graph, and the standard tool for that is breadth-first search. BFS visits nodes in order of distance from the start, so the first time it reaches the target, that distance is the minimum.

The remaining design question is how to find a word's neighbors. Comparing a word against every other dictionary word costs O(N × L) per node and O(N² × L) overall, which is slow with 5,000 words. Since words are short and the alphabet only has 26 letters, it is cheaper to generate candidates: for each position, try all 26 letters and check whether the result is in a hash set of dictionary words. That is 26 × L lookups per word.

Two details make the search correct and efficient. Mark a word visited the moment you enqueue it, not when you pop it, so the same word is never queued twice. And check whether a generated word equals the target before anything else, so you can return the answer as soon as you see it rather than one level later. If the target is not in the dictionary at all, no sequence can exist, which you can check before searching.

Approach: Breadth-first search with letter substitution

  1. Put the dictionary into wordSet. If endWord is not in it, return 0.
  2. Start the queue with (beginWord, 1) and mark beginWord visited.
  3. Pop the front word and its level, which is the number of words in the path so far.
  4. For each position i and each letter from 'a' to 'z', build newWord by replacing the letter at i.
  5. If newWord equals endWord, return level + 1.
  6. Otherwise, if it is in wordSet and not yet visited, mark it visited and enqueue it with level + 1.
  7. If the queue empties without reaching the target, return 0.

Step-by-step example

beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
  1. The queue starts as [(hit, 1)]. Changing the middle letter of 'hit' to 'o' gives 'hot', which is in the set, so (hot, 2) is queued.
  2. From 'hot', changing the first letter gives 'dot' and 'lot', so (dot, 3) and (lot, 3) are queued.
  3. From 'dot', changing the last letter gives 'dog', queued as (dog, 4). 'lot' is already visited.
  4. From 'lot', changing the last letter gives 'log', queued as (log, 4).
  5. From 'dog', changing the first letter to 'c' produces 'cog', which is the target, so the function returns 4 + 1 = 5: hit, hot, dot, dog, cog.

Code: Python, Java, C++

1class Solution:
2    def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
3        wordSet = set(wordList)
4        if endWord not in wordSet:
5            return 0
6
7        queue = [(beginWord, 1)]
8        visited = {beginWord}
9
10        while queue:
11            word, level = queue.pop(0)
12
13            for i in range(len(word)):
14                for c in 'abcdefghijklmnopqrstuvwxyz':
15                    newWord = word[:i] + c + word[i+1:]
16                    if newWord == endWord:
17                        return level + 1
18                    if newWord in wordSet and newWord not in visited:
19                        visited.add(newWord)
20                        queue.append((newWord, level + 1))
21
22        return 0

Time and space complexity

Time

O(N × 26 × L²)

Each of the N dictionary words is dequeued at most once. For it, the code builds 26 × L candidates, and each candidate costs O(L) to build and hash. Strictly speaking, queue.pop(0) on a Python list shifts the remaining items, which can add up to O(N²) in the worst case; a deque removes that cost.

Space

O(N × L)

The word set, the visited set and the queue each hold at most N words of length L.

Other approaches

Bidirectional BFS (time O(N × 26 × L²), space O(N × L))

Search from both the start and the target at once, always expanding the smaller frontier, and stop when they meet. On large dictionaries it explores far fewer words because each side only goes half as deep.

Wildcard pattern buckets (time O(N × L²), space O(N × L²))

Precompute buckets keyed by patterns such as 'h*t', mapping each to the words that fit it, then use the buckets as adjacency lists. This avoids trying letters that cannot form dictionary words and helps when the alphabet is large.

Common mistakes

  • Returning the number of transformations instead of the number of words. The answer counts words, so a path hit, hot has length 2.
  • Marking words visited only when they are popped. The same word can then be queued many times from different parents, which blows up the run time.
  • Using DFS. It finds a path, but not necessarily the shortest one, and exploring every path to compare lengths is exponential.
  • Using list.pop(0) on large inputs. It is O(n) per pop; collections.deque with popleft keeps the queue operations constant time.

Frequently asked questions

Why is BFS used for Word Ladder?

Every transformation costs one step, so the graph is unweighted, and BFS finds shortest paths in unweighted graphs. The level at which the target first appears is the minimum sequence length.

Why does Word Ladder return 0 when endWord is not in the list?

Every word in the sequence after the start, including the last one, must come from the dictionary. If the target is missing, no valid sequence can end there.

What is the time complexity of Word Ladder?

With N words of length L, each word generates 26 × L neighbors at O(L) cost each, giving O(N × 26 × L²). Using a deque keeps the queue overhead linear.

How is Word Ladder II different?

The second version asks for every shortest sequence, not just the length. You run BFS to record parent links by level, then backtrack from the target to reconstruct all paths, which is considerably more involved.