Overview
Given beginWord, endWord, and a word list, find the shortest transformation sequence length from beginWord to endWord, where:
- Only one letter can be changed at a time.
- Each transformed word must exist in the word list.
Return 0 if no such sequence exists.
Constraints
1 <= beginWord.length <= 10- All words are the same length
1 <= wordList.length <= 5000
Examples
ladderLength("hit", "cog", ["hot","dot","dog","lot","log","cog"]);
// => 5 (hit → hot → dot → dog → cog)
ladderLength("hit", "cog", ["hot","dot","dog","lot","log"]);
// => 0 (no path to "cog")Solution
Reveal solution
function ladderLength(beginWord, endWord, wordList) {
const wordSet = new Set(wordList);
if (!wordSet.has(endWord)) return 0;
const queue = [[beginWord, 1]];
const visited = new Set([beginWord]);
while (queue.length) {
const [word, steps] = queue.shift();
for (let i = 0; i < word.length; i++) {
for (let c = 97; c <= 122; c++) {
const next = word.slice(0, i) + String.fromCharCode(c) + word.slice(i + 1);
if (next === endWord) return steps + 1;
if (wordSet.has(next) && !visited.has(next)) {
visited.add(next);
queue.push([next, steps + 1]);
}
}
}
}
return 0;
}Resources
word-ladder.js
Word Ladder
hardcodingAlgorithmsBFS
Overview
Given beginWord, endWord, and a word list, find the shortest transformation sequence length from beginWord to endWord, where:
- Only one letter can be changed at a time.
- Each transformed word must exist in the word list.
Return 0 if no such sequence exists.
Constraints
1 <= beginWord.length <= 10- All words are the same length
1 <= wordList.length <= 5000
Examples
ladderLength("hit", "cog", ["hot","dot","dog","lot","log","cog"]);
// => 5 (hit → hot → dot → dog → cog)
ladderLength("hit", "cog", ["hot","dot","dog","lot","log"]);
// => 0 (no path to "cog")Solution
Reveal solution
function ladderLength(beginWord, endWord, wordList) {
const wordSet = new Set(wordList);
if (!wordSet.has(endWord)) return 0;
const queue = [[beginWord, 1]];
const visited = new Set([beginWord]);
while (queue.length) {
const [word, steps] = queue.shift();
for (let i = 0; i < word.length; i++) {
for (let c = 97; c <= 122; c++) {
const next = word.slice(0, i) + String.fromCharCode(c) + word.slice(i + 1);
if (next === endWord) return steps + 1;
if (wordSet.has(next) && !visited.has(next)) {
visited.add(next);
queue.push([next, steps + 1]);
}
}
}
}
return 0;
}Resources
NameTopicDifficulty
103 of 103 problems