Start learning free

LESSON 582 OF 673 · GRAPHS

Word Ladder II - Python Solution and Time Complexity Analysis

Practice O(N * L2 * Σ) Read the full explanation

You get a start word beginWord and a target word endWord. You also get a list words of allowed words.

Return the number of words in the shortest ladder from beginWord to endWord. Count both the start and the target. Return 0 if no ladder reaches the target.

A ladder follows two rules:

  1. Each word differs from the word before it in exactly one letter.
  2. Every word after the start is in words. The start word doesn't have to be.

Example 1:

Input:
beginWord = "cold",
endWord = "warm",
words = ["cord","card","ward","warm","worm","word","corm"]

Output: 5

Explanation: One letter changes at each step of this ladder:
"cold" -> "cord" -> "card" -> "ward" -> "warm"
This one is just as short:
"cold" -> "cord" -> "word" -> "worm" -> "warm"
Both have 5 words.

Example 2:

Input:
beginWord = "big"
endWord = "cup"
words = ["bag","bug","cup","cap"]

Output: 0

Explanation: "cup" is in the list, but no ladder reaches it.
From "big" you can only get to "bag" and "bug".
Neither of them is one letter away from "cap" or "cup".

Example 3:

Input:
beginWord = "sit"
endWord = "sat"
words = ["sat"]

Output: 2

Explanation: One change is enough: "sit" -> "sat".
The ladder has 2 words.

Constraints:

  • The list has 1 to 5,000 words.
  • No word appears twice in the list.
  • All words have the same length, at most 10 letters. That includes beginWord and endWord.
  • Every letter is a lowercase English letter.
  • The words beginWord and endWord are different.
STEP 1 OF 16
    Ctrl + Enter to check

    PYTHON · GRAPHS

    Word Ladder in Python, explained

    Understanding the Problem

    The core challenge of this problem is to find the shortest path from the beginWord to the endWord by changing only one letter at a time, with each intermediate word existing in the given word list. This problem is significant in various applications such as spell checkers, word games, and natural language processing tasks.

    Potential pitfalls include not considering all possible transformations or not efficiently searching through the word list, leading to suboptimal solutions.

    Approach

    To solve this problem, we can use Breadth-First Search (BFS), which is well-suited for finding the shortest path in an unweighted graph. Here, each word represents a node, and an edge exists between two nodes if they differ by exactly one letter.

    Naive Solution

    A naive solution would involve generating all possible transformations for each word and checking if they exist in the word list. This approach is not optimal due to its high time complexity.

    Optimized Solution

    We can optimize the solution using BFS. The BFS will explore all possible transformations level by level, ensuring that the first time we reach the endWord, we have found the shortest path.

    Algorithm

    Here is a step-by-step breakdown of the BFS algorithm:

    1. Initialize a queue with the beginWord and a set for the word list.
    2. While the queue is not empty, dequeue the front element.
    3. For each character in the current word, try changing it to every other character from 'a' to 'z'.
    4. If the new word is in the word list, add it to the queue and remove it from the word list to prevent revisiting.
    5. If the new word is the endWord, return the current level + 1.
    6. If the queue is exhausted without finding the endWord, return 0.

    Code Implementation

    import collections
    
    def ladderLength(beginWord, endWord, wordList):
        # Convert wordList to a set for O(1) lookups
        wordSet = set(wordList)
        if endWord not in wordSet:
            return 0
        
        # Initialize the queue for BFS
        queue = collections.deque([(beginWord, 1)])
        
        while queue:
            current_word, level = queue.popleft()
            
            # Try changing each character of the current word
            for i in range(len(current_word)):
                for c in 'abcdefghijklmnopqrstuvwxyz':
                    next_word = current_word[:i] + c + current_word[i+1:]
                    
                    # If the next word is the end word, return the level + 1
                    if next_word == endWord:
                        return level + 1
                    
                    # If the next word is in the word set, add it to the queue and remove from the set
                    if next_word in wordSet:
                        wordSet.remove(next_word)
                        queue.append((next_word, level + 1))
        
        return 0
    

    Complexity Analysis

    The time complexity of this BFS approach is O(M^2 * N), where M is the length of each word and N is the number of words in the word list. This is because for each word, we are generating M possible transformations, and for each transformation, we are checking against the word list.

    The space complexity is O(M * N) due to the queue and the set used to store the word list.

    Edge Cases

    Potential edge cases include:

    • The endWord is not in the word list.
    • The beginWord is the same as the endWord.
    • All words are of length 1.

    These cases are handled by the initial checks and the BFS logic.

    Testing

    To test the solution comprehensively, consider the following test cases:

    • Simple cases with a direct transformation.
    • Cases where the endWord is not in the word list.
    • Cases with multiple possible paths to the endWord.

    Using a testing framework like unittest in Python can help automate and validate these test cases.

    Thinking and Problem-Solving Tips

    When approaching such problems, it is crucial to:

    • Understand the problem constraints and requirements.
    • Consider different algorithms and their suitability for the problem.
    • Break down the problem into smaller, manageable parts.
    • Write and test code incrementally to catch errors early.

    Practicing similar problems and studying various algorithms can significantly improve problem-solving skills.

    Conclusion

    In this blog post, we discussed the Word Ladder II problem, explored different approaches to solve it, and provided a detailed BFS-based solution in Python. Understanding and solving such problems is essential for developing strong algorithmic thinking and coding skills.

    Additional Resources

    For further reading and practice, consider the following resources:

    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free