Skip to content

Instantly share code, notes, and snippets.

@OFRBG
Last active August 24, 2024 18:57
Show Gist options
  • Save OFRBG/2a4dd6f93176407269106c47357fa9a7 to your computer and use it in GitHub Desktop.
Save OFRBG/2a4dd6f93176407269106c47357fa9a7 to your computer and use it in GitHub Desktop.
Leetcode 127, "Word Ladder" with Promises as a queue
/* https://leetcode.com/problems/word-ladder/ */
const checkAdjacency = (a, b) => {
if (a.length !== b.length) {
return false;
}
let first = true;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
if (first) first = false;
else return false;
}
}
return true;
};
function ladderLength(beginWord, endWord, wordList) {
wordList.push(beginWord);
const adjacency = [];
for (let i = 0; i < wordList.length; i++) {
adjacency[i] ||= Array(i).fill(0);
for (let j = 0; j < i; j++) {
adjacency[i][j] = checkAdjacency(wordList[i], wordList[j]);
}
}
let min = Infinity;
const visited = Array(wordList.length).fill(false);
const findAdjacent = (i, s) => {
if (wordList[i] === endWord) min = Math.min(min, s);
for (let j = 0; j < wordList.length; j++) {
const isAdj = j < i ? adjacency[i][j] : adjacency[j][i];
if (isAdj && !visited[j]) {
visited[j] = true;
// Sync promise execution is just a queue
new Promise((res) => res(findAdjacent(j, s + 1)));
}
}
};
findAdjacent(wordList.length - 1, 0);
return new Promise((res) => res(min === Infinity ? 0 : min));
}
console.log(
await ladderLength("hit", "cog", ["hot", "dot", "dog", "lot", "log", "cog"])
);
// 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment