Start learning free

LESSON 580 OF 671 · GRAPHS

Word Ladder II - Java 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

    JAVA · GRAPHS

    Word Ladder in Java, 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 word games, natural language processing, and AI-based text generation.

    Potential pitfalls include not checking if the endWord is in the word list and not handling cases where no transformation is possible.

    Approach

    To solve this problem, we can use the Breadth-First Search (BFS) algorithm. BFS is suitable here because it explores all nodes at the present depth level before moving on to nodes at the next depth level, ensuring the shortest path is found.

    Initial naive solution might involve a Depth-First Search (DFS), but it is not optimal due to its potential to explore deeper paths before finding the shortest one.

    Optimized Solution

    Using BFS, we can systematically explore all possible transformations level by level. We use a queue to keep track of the current word and the number of transformations taken to reach it. We also use a set to keep track of visited words to avoid cycles.

    Algorithm

    1. Initialize a queue and add the beginWord with a transformation count of 1.
    2. Initialize a set with the word list for quick lookup.
    3. While the queue is not empty, dequeue the front element.
    4. For each character in the current word, try changing it to every other character from 'a' to 'z'.
    5. If the new word is the endWord, return the current transformation count + 1.
    6. If the new word is in the word list and not visited, add it to the queue and mark it as visited.
    7. If the queue is exhausted without finding the endWord, return 0.

    Code Implementation

    import java.util.*;
    
    public class WordLadder {
        public int ladderLength(String beginWord, String endWord, List<String> wordList) {
            Set<String> wordSet = new HashSet<>(wordList);
            if (!wordSet.contains(endWord)) {
                return 0;
            }
    
            Queue<String> queue = new LinkedList<>();
            queue.add(beginWord);
            int level = 1;
    
            while (!queue.isEmpty()) {
                int size = queue.size();
                for (int i = 0; i < size; i++) {
                    String currentWord = queue.poll();
                    char[] wordChars = currentWord.toCharArray();
    
                    for (int j = 0; j < wordChars.length; j++) {
                        char originalChar = wordChars[j];
                        for (char c = 'a'; c <= 'z'; c++) {
                            if (wordChars[j] == c) continue;
                            wordChars[j] = c;
                            String newWord = String.valueOf(wordChars);
    
                            if (newWord.equals(endWord)) {
                                return level + 1;
                            }
    
                            if (wordSet.contains(newWord)) {
                                queue.add(newWord);
                                wordSet.remove(newWord);
                            }
                        }
                        wordChars[j] = originalChar;
                    }
                }
                level++;
            }
            return 0;
        }
    }
    

    Complexity Analysis

    The time complexity of this approach is O(M^2 * N), where M is the length of each word and N is the total number of words in the word list. This is because for each word, we are iterating through each character and trying all possible transformations.

    The space complexity is O(M * N) due to the storage of the word list in a set and the queue used for BFS.

    Edge Cases

    Potential edge cases include:

    • The endWord not being in the word list.
    • All words being the same length but no possible transformations.
    • Empty word list.

    Each of these cases is handled by the algorithm, ensuring robustness.

    Testing

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

    • Basic transformation sequence.
    • No possible transformation.
    • Large word list with multiple possible paths.

    Using a testing framework like JUnit 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 thoroughly.
    • Consider different algorithms and their suitability for the problem.
    • Break down the problem into smaller, manageable parts.
    • Practice similar problems to improve problem-solving skills.

    Conclusion

    In this blog post, we discussed the Word Ladder problem, explored different approaches, and provided a detailed solution using BFS in Java. Understanding and solving such problems is essential for improving algorithmic thinking and coding skills.

    Additional Resources

    For further reading and practice, consider the following resources:

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