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 the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.
Example 1:
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] Output: 5 Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long.
Example 2:
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"] Output: 0 Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.
Constraints:
1 <= beginWord.length <= 10endWord.length == beginWord.length1 <= wordList.length <= 5000wordList[i].length == beginWord.lengthbeginWord, endWord, and wordList[i] consist of lowercase English letters.beginWord != endWordwordList are unique.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 need to transform a starting word into a target word by changing only one letter at a time, using only words from a given dictionary. The brute force approach exhaustively explores every single possible sequence of word transformations until it successfully reaches the target.
Here's how the algorithm would work step-by-step:
def ladder_length_brute_force(begin_word, end_word, word_list):
word_set = set(word_list)
if end_word not in word_set:
return 0
# We use a recursive helper to explore all paths exhaustively to find the shortest one
def explore_paths(current_word, visited_words):
if current_word == end_word:
return len(visited_words)
shortest_path = float('inf')
for next_word in word_set:
if next_word not in visited_words:
difference_count = sum(1 for first_char, second_char in zip(current_word, next_word) if first_char != second_char)
if difference_count == 1:
visited_words.add(next_word)
path_length = explore_paths(next_word, visited_words)
shortest_path = min(shortest_path, path_length)
visited_words.remove(next_word)
# Returning the minimum length found among all branching paths from this current position
return shortest_path
initial_visited = {begin_word}
minimum_steps = explore_paths(begin_word, initial_visited)
# If the minimum steps remain infinity, it means no valid transformation sequence was found
return minimum_steps if minimum_steps != float('inf') else 0To find the shortest path from a starting word to a target word, we treat the puzzle like a maze where each step allows us to change only one letter at a time. The most efficient way to solve this is to explore the maze level by level, starting from the beginning and moving outward until we reach our destination.
Here's how the algorithm would work step-by-step:
from collections import deque
def ladder_length(begin_word, end_word, word_list):
word_set = set(word_list)
# The target must exist in the dictionary to form a valid transformation path.
if end_word not in word_set:
return 0
queue = deque([(begin_word, 1)])
visited_words = {begin_word}
while queue:
current_word, current_level = queue.popleft()
# Generating all single-letter mutations explores every possible adjacent node in the graph.
for character_index in range(len(current_word)):
for ascii_value in range(97, 123):
next_character = chr(ascii_value)
next_word = current_word[:character_index] + next_character + current_word[character_index + 1:]
if next_word == end_word:
return current_level + 1
# Restricting exploration to unvisited valid words prevents infinite loops in cycles.
if next_word in word_set and next_word not in visited_words:
visited_words.add(next_word)
queue.append((next_word, current_level + 1))
# If the queue empties without finding the target, no valid transformation sequence exists.
return 0| Case | How to Handle |
|---|---|
| EndWord is not present in the wordList | The algorithm should return zero immediately since the target is unreachable. |
| BeginWord is already equal to endWord | Return one as the length of the transformation sequence since no steps are needed. |
| WordList contains duplicate strings | Using a set for the word list automatically de-duplicates entries and ensures O(1) average time lookups. |
| No valid transformation path exists between beginWord and endWord | The BFS queue will empty without finding the target, causing the function to return zero. |
| BeginWord is not in the wordList | This is completely valid as long as beginWord can transform into a word that is in the wordList. |
| Very large word lists with long strings | Using a bidirectional breadth-first search scales efficiently by meeting in the middle and cutting down the branching factor. |
| Graph cycles where words can transform back to previously visited words | Marking words as visited or removing them from the word set prevents infinite loops and redundant processing. |
| Words of varying lengths | The problem constraints guarantee all words are of equal length, so length checks are unnecessary. |