Taro Logo

Word Ladder II

Hard
Asked by:
Google
Amazon
Meta
Apple
213 views
Topics:
ArraysGraphs

A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:

  • Every adjacent pair of words differs by a single letter.
  • Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.
  • sk == endWord

Given 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 <= 5
  • endWord.length == beginWord.length
  • 1 <= wordList.length <= 500
  • wordList[i].length == beginWord.length
  • beginWord, endWord, and wordList[i] consist of lowercase English letters.
  • beginWord != endWord
  • All the words in wordList are unique.
  • The sum of all shortest transformation sequences does not exceed 105.

Solution


Clarifying Questions

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:

  1. What should we return if no valid transformation sequence exists between the beginWord and the endWord?
  2. Are all the words in the wordList guaranteed to be of the exact same length as beginWord and endWord?
  3. Can we assume that all characters in the words are lowercase English letters?
  4. Does the wordList contain any duplicate strings, and if so, how should they be handled?
  5. If there are multiple shortest transformation sequences, in what order should the final list of paths be returned?

Brute Force Solution

Approach

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:

  1. Start by looking at the initial word and finding every single possible valid word you can make by changing just one letter.
  2. From each of those newly found words, take another step and find every valid word you can make by changing one more letter.
  3. Continue branching out this way, keeping track of every complete path of words you build along the way.
  4. Keep exploring paths of increasing length until you successfully reach the target word.
  5. If you reach a dead end where you cannot change any more letters without repeating a word or hitting a block, stop following that particular path.
  6. Once you have explored all possibilities and found at least one way to reach the target word, collect all the paths that reached the target in the fewest number of steps and throw away any paths that took longer than necessary.

Code Implementation

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_paths

Big(O) Analysis

Time Complexity
O(L * 26^L + V) – Let N be the number of words in the dictionary, L be the length of each word, and V be the total number of valid shortest paths generated. Generating neighbors for each word takes L times 26 operations because we can replace each of the L characters with 26 possible letters. Breadth-first search traverses the word graph in proportional time to the dictionary size and the branching factor, leading to O(L * 26^L + N) for the graph traversal. Finally, backtracking to construct all shortest paths requires time proportional to the output size V, dominating the worst-case scenario when paths proliferate exponentially.
Space Complexity
O(N * 26^L + V) – To find all shortest paths, we use a hash map to track word distances, a queue for breadth-first traversal storing up to N words, and nested lists to assemble paths, where N is the number of words in the dictionary and L is the length of each word. The output list of shortest paths can store up to V valid sequences, directly multiplying the memory footprint based on the branching paths generated during letter transformations.

Optimal Solution

Approach

To 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:

  1. Begin at the starting word and look at all possible dictionary words that differ by only a single letter.
  2. Keep track of how many steps it takes to reach each new word from the starting word, making sure not to revisit words we have already seen.
  3. Continue this process level by level until we finally reach the target ending word, stopping our exploration once the target is found so we only focus on the shortest paths.
  4. Once the mapping of connections and distances is complete, start at the target word and work backward toward the starting word.
  5. At each step backward, look for neighbor words that are exactly one step closer to the beginning than the current word.
  6. Build every possible path by moving in reverse, combining the pieces until you successfully trace all the way back to the start.
  7. Gather all the successfully built paths and present them together as the final result.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(L * N^2 + P) – The time complexity is driven by two main phases where N is the number of words in the dictionary, L is the maximum length of each word, and P is the total number of valid shortest paths generated. First, building the distance map requires generating single-letter mutations for N words, taking O(L * N^2) operations in the worst case. Second, backtracking from the end word to reconstruct all shortest paths takes time proportional to the number of output paths P. Combining these phases and accounting for the path tracing gives a total cost approximated by O(L * N^2 + P) operations, which simplifies to O(L * N^2 + P).
Space Complexity
O(N * L^2 + V) – To analyze the auxiliary space complexity, let N be the number of words in the dictionary and L be the length of each word. The hash maps and queues used during the level-by-level dictionary exploration store at most N words, with each word requiring O(L^2) space to generate and store its single-letter mutations. Additionally, tracing backward builds a collection of all shortest paths, which in the worst-case scenario can exponentially grow with V representing the total number of valid transformation paths. Summing these structures up, the overall extra memory simplifies to O(N * L^2 + V) Big O notation.

Edge Cases

EndWord is not present in the wordList
How to Handle:
Return an empty list immediately because the transformation is impossible.
BeginWord is already equal to endWord
How to Handle:
Return a list containing a single sequence with just the beginWord.
No valid transformation sequence exists even though endWord is in wordList
How to Handle:
The search will exhaust all possibilities and return an empty list.
WordList contains duplicates of words
How to Handle:
Using a set for the wordList during initialization eliminates duplicates and prevents redundant processing.
Multiple shortest paths exist sharing intermediate nodes
How to Handle:
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
How to Handle:
Filter out any words that do not match the exact length of beginWord before starting the search.
Extremely large wordList with maximum constraints
How to Handle:
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
How to Handle:
Level-by-level tracking of visited nodes ensures we only process words on shortest paths without falling into infinite cycles.