Word Ladder
Difficulty: Hard · Pattern: Graphs (BFS / DFS) · LeetCode #127
Transform beginWord into endWord by changing one letter at a time, where every intermediate word (and endWord) must be in wordList. Return the number of words in the shortest such sequence, counting both ends, or 0 if it's impossible.
Examples
beginWord = "cold", endWord = "warm",
wordList = ["cord","card","ward","warm","worm","word","wore"]
→ 5 (cold → cord → card → ward → warm)
beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
→ 0 ("cog" not in the list)Hints
- Shortest number of steps in an unweighted graph means BFS.
- Words are nodes; two words are connected if they differ in exactly one position.
- Generate neighbors by trying all 26 letters at each position and checking a set, or bucket words by patterns like
c*ld.
Approach
BFS from beginWord, with the remaining dictionary words in a set. For the current word, generate every one-letter variation (L × 26 candidates); each one present in the set is a neighbor at distance + 1. Remove it from the set when enqueuing so it's never revisited. Return the level count when endWord is reached.
Bidirectional BFS (from both ends, always expanding the smaller frontier) is a strong optimization to mention.
Complexity
Time: O(N · L · 26) for N words of length L (plus O(L) string building). Space: O(N · L).
Python solution
from collections import deque
from string import ascii_lowercase
def ladderLength(beginWord, endWord, wordList):
words = set(wordList)
if endWord not in words:
return 0
q = deque([(beginWord, 1)])
words.discard(beginWord)
while q:
w, d = q.popleft()
if w == endWord:
return d
for i in range(len(w)):
for ch in ascii_lowercase:
nxt = w[:i] + ch + w[i + 1:]
if nxt in words:
words.remove(nxt)
q.append((nxt, d + 1))
return 0JavaScript solution
function ladderLength(beginWord, endWord, wordList) {
const words = new Set(wordList);
if (!words.has(endWord)) return 0;
words.delete(beginWord);
let q = [beginWord], depth = 1;
while (q.length) {
const next = [];
for (const w of q) {
if (w === endWord) return depth;
for (let i = 0; i < w.length; i++) {
for (let c = 97; c <= 122; c++) {
const nxt = w.slice(0, i) + String.fromCharCode(c) + w.slice(i + 1);
if (words.has(nxt)) { words.delete(nxt); next.push(nxt); }
}
}
}
q = next; depth++;
}
return 0;
}