Word Ladder
Pattern: Shortest paths
Words are vertices, joined when they differ in exactly one letter. BFS from the begin word, trying every one-letter change and keeping only words in the list, gives the shortest sequence; its length counts the begin and end words.
The problem
Given beginWord, endWord and a word list, return the number of words in the shortest sequence from begin to end where
each step changes one letter and every word after the first is in the list, or 0 if there is none.
Think first
- What graph is hidden here?
- How do you find a word's neighbours quickly?
- Does the answer count steps or words?
Hints
Brute force, and why it fails
Compare every pair of words to build the graph: O(N² × L).
The key insight
Generating one-letter variants and BFS over them finds the shortest sequence without building the whole graph.
Dry run
| level | 1 |
|---|
begin hit, end cog, list hot dot dog lot log cog. Level 1: hit.
The plan
set = words; if end not in set: 0
BFS from begin: for each variant in the set: remove it from the set, push it
Complexity
- Time
O(N × L × 26)- Space
O(N × L)
Each word is reached once, and makes L × 26 variants.
Edge cases
- end not in the list: 0.
- begin equals end: depends on the list.
- One-letter words.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int ladderLength(String beginWord, String endWord, String[] wordList) {
Set<String> words = new HashSet<>(Arrays.asList(wordList));
if (!words.contains(endWord)) return 0;
Queue<String> q = new ArrayDeque<>();
q.add(beginWord);
words.remove(beginWord);
for (int length = 1; !q.isEmpty(); length++) { // BFS: each level is one more word in the sequence
for (int size = q.size(); size > 0; size--) {
char[] w = q.poll().toCharArray();
if (new String(w).equals(endWord)) return length;
for (int i = 0; i < w.length; i++) {
char old = w[i];
for (char c = 'a'; c <= 'z'; c++) { // every word one letter away
w[i] = c;
String next = new String(w);
if (words.remove(next)) q.add(next); // remove = mark visited
}
w[i] = old;
}
}
}
return 0;
}
}C++
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> words(wordList.begin(), wordList.end());
if (!words.count(endWord)) return 0;
queue<string> q;
q.push(beginWord);
words.erase(beginWord);
for (int length = 1; !q.empty(); length++) { // BFS: each level is one more word in the sequence
for (int size = static_cast<int>(q.size()); size > 0; size--) {
string w = q.front();
q.pop();
if (w == endWord) return length;
for (size_t i = 0; i < w.size(); i++) {
char old = w[i];
for (char c = 'a'; c <= 'z'; c++) { // every word one letter away
w[i] = c;
if (words.erase(w)) q.push(w); // erase = mark visited
}
w[i] = old;
}
}
}
return 0;
}
};Python
from collections import deque
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: list[str]) -> int:
words = set(wordList)
if endWord not in words:
return 0
words.discard(beginWord)
q, length = deque([beginWord]), 1
while q: # BFS: each level is one more word in the sequence
for _ in range(len(q)):
w = q.popleft()
if w == endWord:
return length
for i in range(len(w)):
for c in "abcdefghijklmnopqrstuvwxyz": # every word one letter away
nxt = w[:i] + c + w[i + 1:]
if nxt in words:
words.remove(nxt) # remove = mark visited
q.append(nxt)
length += 1
return 0Common mistakes
- Counting steps instead of words.
- Not removing words when they are visited.