Taro Logo

Word Ladder

Hard
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+25
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.4K views
Topics:
GraphsStrings

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 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 <= 10
  • endWord.length == beginWord.length
  • 1 <= wordList.length <= 5000
  • wordList[i].length == beginWord.length
  • beginWord, endWord, and wordList[i] consist of lowercase English letters.
  • beginWord != endWord
  • All the words in wordList are unique.

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. Is the `endWord` guaranteed to be present in the provided `wordList`?
  2. Are all the strings in `wordList`, `beginWord`, and `endWord` guaranteed to be of the exact same length?
  3. Can `wordList` contain duplicate strings, and should we handle them in any special way?
  4. What should be returned if `beginWord` and `endWord` are already identical?
  5. Are the words restricted to lowercase English letters, or could they contain uppercase letters, numbers, or special characters?

Brute Force Solution

Approach

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:

  1. Begin with your starting word and look at all the words in your dictionary that differ by exactly one letter.
  2. Pick one of those valid next words and treat it as your current position.
  3. From this new position, look again at all the dictionary words that differ by one letter, continuing to forge a path forward.
  4. Keep branching out and trying every possible combination of word sequences, making sure not to reuse words you have already visited in the current path.
  5. If a path hits a dead end where no more valid single-letter changes are possible, step back and try a different branch of word choices.
  6. Repeat this trial-and-error exploration for every conceivable path until you finally land on your target word.
  7. Count the number of steps in the paths that successfully reach the goal, and identify the one with the fewest number of steps.

Code Implementation

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 0

Big(O) Analysis

Time Complexity
O(M^2 * N) – Let N be the number of words in the dictionary and M be the length of each word. For each of the N words, we generate all possible single-letter mutations, which takes M operations per word. Since we check each mutation against the dictionary taking M time per lookup, processing a single word takes M^2 operations. Multiplying this by all N words results in approximately N * M^2 operations, which simplifies to O(M^2 * N).
Space Complexity
O(N * M^2) – To track the shortest transformation sequence, the algorithm uses a queue for breadth-first search, a hash set for the dictionary for quick lookups, and another hash set to store visited words, where N is the total number of words in the dictionary and M is the maximum length of a word. The queue and visited set can hold at most all N words, while string slicing operations generate intermediate state strings of length M during neighbor generation. Therefore, the total auxiliary memory scales linearly with the number of words N and quadratically with the word length M due to string creation.

Optimal Solution

Approach

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

  1. Begin at the starting word and consider it our current location in the maze.
  2. Look at all the possible valid words we can reach by changing just one single letter of our current word.
  3. Check if any of these newly reachable words happen to be our target destination.
  4. If the target is among them, we have found our answer and can stop immediately.
  5. If the target is not reached, take all those newly discovered words and treat them as the next layer of our journey, making sure we never revisit any word we have already seen.
  6. Repeat this expanding search layer by layer, moving further away from the start, until the target word finally appears.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(M² * N) – Let N be the number of words in the word list and M be the length of each word. In the worst-case scenario, the breadth-first search visits every word in the list once. For each visited word, we generate all possible single-letter variations, which takes M operations per position, resulting in M squared string transformations. Combining these factors yields approximately N * M² operations, which simplifies to O(M² * N).
Space Complexity
O(N * M) – The auxiliary space is driven by the data structures used for the level-by-level breadth-first search, where N is the total number of words in the word list and M is the maximum length of a word. Specifically, we maintain a queue for exploring layers, a set of visited words, and intermediate string transformations that together can store up to every word and its possible single-letter mutations in memory. As the total number of words N increases, the hash set and queue scale linearly to hold these elements, resulting in a space complexity proportional to N times M.

Edge Cases

EndWord is not present in the wordList
How to Handle:
The algorithm should return zero immediately since the target is unreachable.
BeginWord is already equal to endWord
How to Handle:
Return one as the length of the transformation sequence since no steps are needed.
WordList contains duplicate strings
How to Handle:
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
How to Handle:
The BFS queue will empty without finding the target, causing the function to return zero.
BeginWord is not in the wordList
How to Handle:
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
How to Handle:
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
How to Handle:
Marking words as visited or removing them from the word set prevents infinite loops and redundant processing.
Words of varying lengths
How to Handle:
The problem constraints guarantee all words are of equal length, so length checks are unnecessary.
0/75 completed