HARD NC#92 Graphs - BFS
127. Word Ladder
๐ Problem
A transformation sequence from beginWord to endWord using a wordList. Each step changes exactly one letter. Return the number of words in the shortest transformation sequence (including beginWord). Return 0 if impossible.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
- โขLevel-order traversal
- โขQueue discipline
- โขShortest-step interpretation
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply BFS reasoning pattern
๐ก Approach
- โ Model as graph where edges connect words differing by one letter
- โ Use BFS to find shortest path from beginWord to endWord
- โ For each word, try changing each character to a-z
- โ Use Set for O(1) lookup and to avoid revisiting
- โ Time: O(N * M * 26) where N = wordList.length, M = word length
- โ Space: O(N * M)
๐ ๏ธ Hints & Pitfalls
Hints
- โขModel as graph where edges connect words differing by one letter
- โขUse BFS to find shortest path from beginWord to endWord
- โขFor each word, try changing each character to a-z
Common Pitfalls
- โขUse Set for O(1) lookup and to avoid revisiting
- โขTime: O(N * M * 26) where N = wordList.length, M = word length
- โขSpace: O(N * M)
๐งช Test Cases
Test Case 1
Not run Input:
ladderLength('hit', 'cog', ['hot','dot','dog','lot','log','cog']); Expected:
5 Test Case 2
Not run Input:
ladderLength('hit', 'cog', ['hot','dot','dog','lot','log']); Expected:
0 Test Case 3
Not run Input:
ladderLength(beginWord: string, endWord: string, wordList: string[]); Expected:
Computed from hidden reference ๐ Code Editor
๐ค Output