#126
Word Ladder II
HardHash TableStringBacktrackingBreadth-First SearchBreadth-First SearchGraph TraversalBacktracking
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a breadth-first search (BFS) to find the shortest paths from beginWord to endWord. It explores all possible transformations level by level, ensuring that we only consider the shortest paths and avoids revisiting nodes unnecessarily.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a queue with the beginWord and a set to track visited words.
- 2Step 2: Perform BFS to find all possible transformations, storing paths as we go.
- 3Step 3: Once we reach endWord, backtrack to construct all valid paths.
solution.py33 lines
1# Full working Python code
2from collections import defaultdict
3
4class Solution:
5 def findLadders(self, beginWord, endWord, wordList):
6 wordSet = set(wordList)
7 if endWord not in wordSet:
8 return []
9 res = []
10 self.bfs(beginWord, endWord, wordSet, res)
11 return res
12
13 def bfs(self, beginWord, endWord, wordSet, res):
14 queue = [[beginWord]]
15 visited = set([beginWord])
16 found = False
17
18 while queue and not found:
19 next_level = set()
20 for path in queue:
21 last_word = path[-1]
22 for i in range(len(last_word)):
23 for c in 'abcdefghijklmnopqrstuvwxyz':
24 new_word = last_word[:i] + c + last_word[i+1:]
25 if new_word in wordSet:
26 if new_word == endWord:
27 found = True
28 res.append(path + [new_word])
29 if new_word not in visited:
30 next_level.add(new_word)
31 visited.update(next_level)
32 queue = [path + [word] for path in queue for word in next_level]
33ℹ
Complexity note: The time complexity is O(n) because we explore each word once and generate new words at each step. The space complexity is O(n) due to the storage of the queue and visited set.
- 1The problem can be visualized as a graph where each word is a node and edges exist between words that differ by one letter.
- 2Using BFS ensures that we find the shortest path first before exploring longer paths.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.