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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit