#127

Word Ladder

Hard
Hash TableStringBreadth-First SearchBreadth-First SearchGraph Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m * 26)
Space
O(1)
O(n)
💡

Intuition

Time O(n * m * 26)Space O(n)

The optimal solution uses a breadth-first search (BFS) approach to explore the shortest path from the beginWord to the endWord. This ensures that we find the shortest transformation sequence efficiently.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a queue with the beginWord and a length of 1.
  2. 2Step 2: While the queue is not empty, dequeue the front element.
  3. 3Step 3: For each character in the current word, try replacing it with every letter from 'a' to 'z'.
  4. 4Step 4: If the new word is in the wordList, enqueue it with an incremented length and remove it from the wordList.
  5. 5Step 5: If the new word is the endWord, return the length.
solution.py19 lines
1# Full working Python code
2from collections import deque
3
4def wordLadder(beginWord, endWord, wordList):
5    if endWord not in wordList:
6        return 0
7    wordList = set(wordList)
8    queue = deque([(beginWord, 1)])
9    while queue:
10        current_word, length = queue.popleft()
11        if current_word == endWord:
12            return length
13        for i in range(len(current_word)):
14            for c in 'abcdefghijklmnopqrstuvwxyz':
15                next_word = current_word[:i] + c + current_word[i+1:]
16                if next_word in wordList:
17                    queue.append((next_word, length + 1))
18                    wordList.remove(next_word)
19    return 0

Complexity note: The time complexity is O(n * m * 26) where n is the number of words in the wordList and m is the length of each word. We generate up to 26 new words for each character in each word.

  • 1Using a set for wordList allows for O(1) average time complexity for lookups.
  • 2BFS is optimal for unweighted shortest path problems like this one.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.