A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:
si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.sk == endWordGiven two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk].
Example 1:
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] Output: [["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]] Explanation: There are 2 shortest transformation sequences: "hit" -> "hot" -> "dot" -> "dog" -> "cog" "hit" -> "hot" -> "lot" -> "log" -> "cog"
Example 2:
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"] Output: [] Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.
Constraints:
1 <= beginWord.length <= 5endWord.length == beginWord.length1 <= wordList.length <= 500wordList[i].length == beginWord.lengthbeginWord, endWord, and wordList[i] consist of lowercase English letters.beginWord != endWordwordList are unique.105.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you are trying to transform a starting word into a target word by changing one letter at a time, making sure every intermediate step is also a valid word. The brute force approach tries every possible sequence of word transformations to find all the shortest paths from start to finish.
Here's how the algorithm would work step-by-step:
def find_ladders(begin_word, end_word, word_list):
word_set = set(word_list)
if end_word not in word_set:
return []
current_paths = [[begin_word]]
shortest_paths = []
# We explore paths level by level to ensure we only capture the absolute shortest transformations
while current_paths and not shortest_paths:
next_level_visited = set()
next_paths = []
for path in current_paths:
current_word = path[-1]
if current_word == end_word:
shortest_paths.append(path)
continue
for character_index in range(len(current_word)):
for alphabet_char in 'abcdefghijklmnopqrstuvwxyz':
next_word = current_word[:character_index] + alphabet_char + current_word[character_index + 1:]
if next_word in word_set:
next_level_visited.add(next_word)
next_paths.append(path + [next_word])
# We remove visited words after exploring a full depth level to prevent cycles across paths
for visited_word in next_level_visited:
word_set.discard(visited_word)
current_paths = next_paths
return shortest_pathsTo find all the shortest paths from a starting word to an ending word, we use a two-part strategy. First, we explore the dictionary level by level to map out the shortest distances and connections between words. Second, we trace backward from the target word to the start word, collecting every valid sequence along the way.
Here's how the algorithm would work step-by-step:
from collections import deque, defaultdict
class Solution:
def findLadders(self, begin_word: str, end_word: str, word_list: list[str]) -> list[list[str]]:
word_set = set(word_list)
if end_word not in word_set:
return []
word_set.discard(begin_word)
distance_mapping = {begin_word: 0}
predecessor_map = defaultdict(list)
queue = deque([begin_word])
found_end_word = False
# We perform a breadth-first search to compute the shortest distance to every reachable word.
while queue and not found_end_word:
current_level_visited = set()
level_size = len(queue)
for _ in range(level_size):
current_word = queue.popleft()
current_distance = distance_mapping[current_word]
if current_word == end_word:
found_end_word = True
break
for char_index in range(len(current_word)):
for char_code in range(ord('a'), ord('z') + 1):
next_char = chr(char_code)
if next_char == current_word[char_index]:
continue
next_word = current_word[:char_index] + next_char + current_word[char_index + 1:]
if next_word in word_set:
if next_word not in distance_mapping:
distance_mapping[next_word] = current_distance + 1
queue.append(next_word)
current_level_visited.add(next_word)
if distance_mapping[next_word] == current_distance + 1:
predecessor_map[next_word].append(current_word)
word_set -= current_level_visited
all_shortest_paths = []
# We backtrack from the end word using predecessors to reconstruct all shortest transformation paths.
def backtrack_paths(current_word, current_path):
if current_word == begin_word:
all_shortest_paths.append(list(reversed(current_path)))
return
for previous_word in predecessor_map[current_word]:
current_path.append(previous_word)
backtrack_paths(previous_word, current_path)
current_path.pop()
if found_end_word:
backtrack_paths(end_word, [end_word])
return all_shortest_paths| Case | How to Handle |
|---|---|
| EndWord is not present in the wordList | Return an empty list immediately because the transformation is impossible. |
| BeginWord is already equal to endWord | Return a list containing a single sequence with just the beginWord. |
| No valid transformation sequence exists even though endWord is in wordList | The search will exhaust all possibilities and return an empty list. |
| WordList contains duplicates of words | Using a set for the wordList during initialization eliminates duplicates and prevents redundant processing. |
| Multiple shortest paths exist sharing intermediate nodes | A backtrack step combined with a predecessor map correctly reconstructs all valid paths of identical minimum length. |
| Words in wordList have varying lengths compared to beginWord | Filter out any words that do not match the exact length of beginWord before starting the search. |
| Extremely large wordList with maximum constraints | Bidirectional breadth-first search is required to prune the search space and prevent memory limit or timeout errors. |
| Cyclic paths where a word can lead back to a previously visited ancestor | Level-by-level tracking of visited nodes ensures we only process words on shortest paths without falling into infinite cycles. |