Word Ladder

Find the shortest transformation sequence from beginWord to endWord.

Pattern

BFS Shortest Path

This problem follows the BFS Shortest Path pattern, commonly found in the Graphs category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

BFS where each level changes one character. Use wildcard patterns for O(1) neighbor lookup.

Key Insight

BFS guarantees shortest path. Removing words from the set instead of using a visited set is cleaner and prevents re-processing.

Step-by-step

  1. 1Start BFS from beginWord
  2. 2At each level, try changing each character to a-z
  3. 3If the new word is in the word list, add it to the queue
  4. 4Remove used words from the list to avoid revisiting
  5. 5When endWord is found, return the current depth

Pseudocode

wordSet = set(wordList)
if endWord not in wordSet: return 0
queue = deque([(beginWord, 1)])
while queue:
    word, depth = queue.popleft()
    for i in range(len(word)):
        for c in 'abcdefghijklmnopqrstuvwxyz':
            newWord = word[:i] + c + word[i+1:]
            if newWord == endWord: return depth + 1
            if newWord in wordSet:
                wordSet.remove(newWord)
                queue.append((newWord, depth + 1))
return 0
Complexity Analysis

Time Complexity

O(m² * n)

Space Complexity

O(m² * n)
More Graphs Problems

Master this pattern with YeetCode

Practice Word Ladder and similar Graphs problems with flashcards. Build pattern recognition through active recall.

Practice this problem