-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0127-word-ladder.js
More file actions
61 lines (52 loc) · 1.61 KB
/
0127-word-ladder.js
File metadata and controls
61 lines (52 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* Word Ladder
* Time Complexity: O(L^2 * N)
* Space Complexity: O(N * L)
*/
var ladderLength = function (beginWord, endWord, wordList) {
const dictionaryWords = new Set(wordList);
const hasEndWordInList = dictionaryWords.has(endWord);
if (!hasEndWordInList) {
return 0;
}
let bfsQueue = [beginWord];
let pathCounter = 1;
while (bfsQueue.length > 0) {
const currentLevelProcessingSize = bfsQueue.length;
const nextLevelQueueCollector = [];
for (
let wordIndexInLevel = 0;
wordIndexInLevel < currentLevelProcessingSize;
wordIndexInLevel++
) {
const currentWordBeingProcessed = bfsQueue[wordIndexInLevel];
if (currentWordBeingProcessed === endWord) {
return pathCounter;
}
for (
let charPositionInWord = 0;
charPositionInWord < currentWordBeingProcessed.length;
charPositionInWord++
) {
for (
let alphabetIterator = 0;
alphabetIterator < 26;
alphabetIterator++
) {
const charToSubstitute = String.fromCharCode(97 + alphabetIterator); // 'a' through 'z'
const generatedNeighborWord =
currentWordBeingProcessed.substring(0, charPositionInWord) +
charToSubstitute +
currentWordBeingProcessed.substring(charPositionInWord + 1);
if (dictionaryWords.has(generatedNeighborWord)) {
nextLevelQueueCollector.push(generatedNeighborWord);
dictionaryWords.delete(generatedNeighborWord);
}
}
}
}
bfsQueue = nextLevelQueueCollector;
pathCounter++;
}
return 0;
};