⬅ Previous Topic
Word Ladder - Shortest Transformation using GraphNext Topic ⮕
Number of Distinct Islands using DFS⬅ Previous Topic
Word Ladder - Shortest Transformation using GraphNext Topic ⮕
Number of Distinct Islands using DFSTopic Contents
Given two words, startWord
and targetWord
, and a list of unique words wordList
, find all the shortest transformation sequences from startWord
to targetWord
.
wordList
.Return all such sequences in any order.
startWord
to generate a graph and record the level (distance) of each word from the start.targetWord
is not reachable, return an empty list.targetWord
and move backwards using the levels map to collect all shortest paths.function wordLadderII(beginWord, endWord, wordList) {
const wordSet = new Set(wordList);
if (!wordSet.has(endWord)) return [];
const graph = new Map();
const level = new Map();
const res = [];
const bfs = () => {
const queue = [beginWord];
level.set(beginWord, 0);
while (queue.length) {
const word = queue.shift();
const currLevel = level.get(word);
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 (wordSet.has(next)) {
if (!level.has(next)) {
level.set(next, currLevel + 1);
queue.push(next);
graph.set(next, [word]);
} else if (level.get(next) === currLevel + 1) {
graph.get(next).push(word);
}
}
}
}
}
};
const dfs = (word, path) => {
if (word === beginWord) {
res.push([beginWord, ...path.reverse()]);
return;
}
if (!graph.has(word)) return;
for (const prev of graph.get(word)) {
dfs(prev, [...path, word]);
}
};
bfs();
if (level.has(endWord)) dfs(endWord, []);
return res;
}
console.log(wordLadderII("hit", "cog", ["hot","dot","dog","lot","log","cog"]));
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n * m^2) | Best case occurs when the target word is found early during BFS. Here, n is the number of words in the list, and m is the word length. Checking all possible one-letter transformations involves m changes per word and comparing with up to n words. |
Average Case | O(n * m^2) | On average, we process each word and generate transformations by changing every character (m positions), resulting in n * m comparisons. |
Worst Case | O(n * m^2 + k) | In the worst case, BFS explores all words, and backtracking (DFS) finds all possible shortest sequences (let's say k sequences). So the total complexity is O(n * m^2 + k). |
O(n * m + k)
Explanation: We store the graph (adjacency list), the level map, and the sequences found. Graph and level maps use O(n * m), and storing all k shortest sequences adds O(k).
⬅ Previous Topic
Word Ladder - Shortest Transformation using GraphNext Topic ⮕
Number of Distinct Islands using DFSYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.