Start learning free

LESSON 579 OF 671 · GRAPHS

Word Ladder - JavaScript Solution and Time Complexity Analysis

Practice O(N2 * L) 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

    JAVASCRIPT · GRAPHS

    Word Ladder in JavaScript, 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 the Breadth-First Search (BFS) algorithm. BFS is ideal for finding the shortest path in an unweighted graph, which aligns with our need to find the shortest transformation sequence.

    Here’s a step-by-step approach:

    1. Use a queue to perform BFS. Initialize the queue with the beginWord and a level counter set to 1.
    2. Use a set to keep track of words that have been visited to avoid cycles.
    3. For each word in the queue, generate all possible transformations by changing one letter at a time.
    4. If a transformation matches the endWord, return the current level + 1.
    5. If the transformation exists in the word list and hasn’t been visited, add it to the queue and mark it as visited.
    6. If the queue is exhausted without finding the endWord, return 0.

    Algorithm

    Here’s a detailed breakdown of the BFS algorithm:

    1. Initialize a queue with the beginWord and a level counter set to 1.
    2. Initialize a set to keep track of visited words.
    3. While the queue is not empty:
      1. Dequeue the front word and its level.
      2. For each character in the word, generate all possible transformations by changing it to every letter from 'a' to 'z'.
      3. If a transformation matches the endWord, return the current level + 1.
      4. If the transformation exists in the word list and hasn’t been visited, add it to the queue and mark it as visited.
    4. If the queue is exhausted without finding the endWord, return 0.

    Code Implementation

    
    /**
     * @param {string} beginWord
     * @param {string} endWord
     * @param {string[]} wordList
     * @return {number}
     */
    function ladderLength(beginWord, endWord, wordList) {
        // Convert wordList to a set for O(1) lookups
        const wordSet = new Set(wordList);
        if (!wordSet.has(endWord)) return 0;
    
        // Initialize the queue for BFS
        const queue = [[beginWord, 1]];
        const visited = new Set();
        visited.add(beginWord);
    
        while (queue.length > 0) {
            const [currentWord, level] = queue.shift();
    
            // Generate all possible transformations
            for (let i = 0; i < currentWord.length; i++) {
                for (let c = 97; c <= 122; c++) { // ASCII 'a' to 'z'
                    const newWord = currentWord.slice(0, i) + String.fromCharCode(c) + currentWord.slice(i + 1);
    
                    // If the new word is the end word, return the level + 1
                    if (newWord === endWord) {
                        return level + 1;
                    }
    
                    // If the new word is in the word set and not visited
                    if (wordSet.has(newWord) && !visited.has(newWord)) {
                        queue.push([newWord, level + 1]);
                        visited.add(newWord);
                    }
                }
            }
        }
    
        // If no transformation sequence is found
        return 0;
    }
    

    Complexity Analysis

    The time complexity of this approach is O(N * M * 26), where N is the number of words in the word list, M is the length of each word, and 26 represents the number of possible transformations for each character. The space complexity is O(N) due to the queue and visited set.

    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.

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

    Testing

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

    • Basic cases with a clear transformation sequence.
    • Cases where the endWord is not in the word list.
    • Cases with multiple possible transformation sequences.

    Using a testing framework like Jest can help automate and validate these test cases.

    Thinking and Problem-Solving Tips

    When approaching such problems, consider the following tips:

    • Break down the problem into smaller, manageable parts.
    • Use diagrams or pseudo-code to visualize the solution.
    • Practice similar problems to build familiarity with common patterns and algorithms.

    Conclusion

    Understanding and solving the Word Ladder problem helps improve problem-solving skills and familiarity with graph traversal algorithms like BFS. Practice and exploration of similar problems can further enhance these skills.

    Additional Resources

    For further reading and practice, consider the following resources:

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