Word Ladder
Difficulty: Hard
You're given a beginWord, an endWord, and a dictionary wordList. A transformation sequence is a chain of words from beginWord to endWord where:
- Each step changes exactly one letter.
- Every word except
beginWordis inwordList.
Return the number of words in the shortest sequence, counting both beginWord and endWord. If none exists, return 0.
Examples
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5
One shortest chain is hit -> hot -> dot -> dog -> cog, which has 5 words in it.
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
Output: 0
cog never appears in the word list, so there's no way to end the sequence on it.
Input: beginWord = "a", endWord = "c", wordList = ["a","b","c"]
Output: 3
a -> b -> c: two one-letter changes, three words total.
Constraints
1 <= beginWord.length <= 10
endWord.length == beginWord.length
All words consist of lowercase English letters and are the same length.
wordList contains no duplicates, and beginWord != endWord.
Approach
Make every word a node, with an edge between words that differ by one letter. The shortest chain is then the shortest path between two nodes, and in an unweighted graph that's what BFS finds.
Run BFS from beginWord, one layer (one letter change) at a time, and stop when you reach endWord. The steps taken, plus one for the starting word, is the answer. Mark each word visited when it's discovered, not when it's popped, so it's never queued twice.
The main choice is how to find a word's neighbors:
- Brute force: compare the word against every remaining word, checking for exactly one differing position.
- Optimal: replace each position with every other letter and look the result up in a
Setbuilt fromwordList. Each lookup is O(1), however many words are left.
Solutions
Brute Force - Compare Against Remaining Words
Run a standard BFS. To find a word's neighbors, scan every word left in the dictionary for one that differs in exactly one position.
function ladderLength(beginWord, endWord, wordList) {
const remaining = new Set(wordList);
if (!remaining.has(endWord)) return 0;
function differsByOne(a, b) {
let diffCount = 0;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) diffCount++;
if (diffCount > 1) return false;
}
return diffCount === 1;
}
const queue = [[beginWord, 1]];
while (queue.length > 0) {
const [word, steps] = queue.shift();
if (word === endWord) return steps;
for (const candidate of Array.from(remaining)) {
if (differsByOne(word, candidate)) {
remaining.delete(candidate);
queue.push([candidate, steps + 1]);
}
}
}
return 0;
}Time: O(N² × L) - each of N words may be compared against N others, each comparison scanning L letters · Space: O(N × L)
Optimal - BFS with Generated Neighbors
Put the word list in a Set for O(1) lookups. For each word popped from the queue, generate every one-letter change (26 letters × word length) and check it against the Set. Any hit is a neighbor.
function ladderLength(beginWord, endWord, wordList) {
const remaining = new Set(wordList);
if (!remaining.has(endWord)) return 0;
const queue = [[beginWord, 1]];
const alphabet = "abcdefghijklmnopqrstuvwxyz";
while (queue.length > 0) {
const [word, steps] = queue.shift();
if (word === endWord) return steps;
for (let i = 0; i < word.length; i++) {
for (const letter of alphabet) {
if (letter === word[i]) continue;
const candidate = word.slice(0, i) + letter + word.slice(i + 1);
if (remaining.has(candidate)) {
remaining.delete(candidate); // mark visited so it's never queued twice
queue.push([candidate, steps + 1]);
}
}
}
}
return 0;
}Time: O(N × L × 26) - for each of N words, try 26 letters at each of L positions · Space: O(N × L)