Skip to content

Instantly share code, notes, and snippets.

@mikegwhit
Created May 7, 2025 20:59
Show Gist options
  • Save mikegwhit/da3de86c56981576f66aacd03bc6a682 to your computer and use it in GitHub Desktop.
Save mikegwhit/da3de86c56981576f66aacd03bc6a682 to your computer and use it in GitHub Desktop.
/**
* Problem: Word Ladder
*
* Given a `beginWord`, an `endWord`, and a list of `wordList`:
* Transform `beginWord` into `endWord` by changing **only one letter at a time**,
* and each intermediate word must exist in the `wordList`.
*
* Return the **minimum number of transformations** required.
* If no such sequence exists, return 0.
*
* Note: You may assume beginWord and endWord are lowercase and of the same length.
*
* Example:
* Input:
* beginWord = "hit"
* endWord = "cog"
* wordList = ["hot","dot","dog","lot","log","cog"]
* Output: 5
* Explanation: "hit" → "hot" → "dot" → "dog" → "cog"
*
* Why BFS?
* Because you're looking for the **shortest transformation** → use BFS to explore word levels.
*/
function wordLadder(beginWord, endWord, wordList) {
// 1. Convert wordList to a Set for O(1) lookups
// 2. Use a queue to store current word and step count
// 3. While queue is not empty:
// a. For each word in the queue:
// i. If word is endWord, return step count
// ii. Generate all valid one-letter transformations
// iii. If transformation is in wordSet, enqueue it and remove from wordSet
// 4. If queue empties with no result, return 0
}
function testWordLadder() {
const begin = "hit";
const end = "cog";
const wordList = ["hot","dot","dog","lot","log","cog"];
const expected = 5;
const actual = wordLadder(begin, end, wordList);
console.log(actual === expected ? "✅ PASS" : `❌ FAIL (got ${actual}, expected ${expected})`);
}
testWordLadder();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment