Start learning free

LESSON 575 OF 667 · GRAPHS

Word Ladder in C++ with 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

    C++ · GRAPHS

    Word Ladder in C++, 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, 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

    The optimized solution involves using BFS to explore all possible transformations level by level. This ensures that the first time we reach the endWord, we have found the shortest transformation sequence.

    Algorithm

    1. Add the beginWord to a queue and start BFS.

    2. For each word, generate all possible transformations by changing one letter at a time.

    3. If a transformation exists in the word list, add it to the queue and mark it as visited.

    4. Continue this process until the queue is empty or the endWord is found.

    Code Implementation

    
    #include <iostream>
    #include <unordered_set>
    #include <queue>
    #include <string>
    #include <vector>
    
    using namespace std;
    
    // Function to check if two words differ by exactly one character
    bool isOneLetterDifferent(const string &word1, const string &word2) {
        int count = 0;
        for (int i = 0; i < word1.size(); ++i) {
            if (word1[i] != word2[i]) {
                count++;
                if (count > 1) return false;
            }
        }
        return count == 1;
    }
    
    // Function to find the length of the shortest transformation sequence
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        unordered_set<string> wordSet(wordList.begin(), wordList.end());
        if (wordSet.find(endWord) == wordSet.end()) return 0;
    
        queue<pair<string, int>> q;
        q.push({beginWord, 1});
    
        while (!q.empty()) {
            string currentWord = q.front().first;
            int currentLength = q.front().second;
            q.pop();
    
            for (int i = 0; i < currentWord.size(); ++i) {
                string tempWord = currentWord;
                for (char c = 'a'; c <= 'z'; ++c) {
                    tempWord[i] = c;
                    if (tempWord == endWord) return currentLength + 1;
                    if (wordSet.find(tempWord) != wordSet.end()) {
                        q.push({tempWord, currentLength + 1});
                        wordSet.erase(tempWord);
                    }
                }
            }
        }
        return 0;
    }
    
    int main() {
        string beginWord = "hit";
        string endWord = "cog";
        vector<string> wordList = {"hot", "dot", "dog", "lot", "log", "cog"};
        cout << "Length of shortest transformation sequence: " << ladderLength(beginWord, endWord, wordList) << endl;
        return 0;
    }
    

    Complexity Analysis

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

    The space complexity is O(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 valid transformations existing.
    • 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:

    • Simple transformations with a small word list.
    • Large word lists with multiple possible paths.
    • Edge cases where no transformation is possible.

    Using a testing framework like Google Test 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.
    • Think about the most efficient data structures to use.
    • Consider edge cases and how to handle them.
    • Practice similar problems to improve problem-solving skills.

    Conclusion

    Understanding and solving the Word Ladder problem is crucial for developing efficient algorithms for word transformation tasks. By using BFS, we can ensure that we find the shortest transformation sequence efficiently. Practice and exploration of similar problems can further enhance problem-solving skills.

    Additional Resources

    For further reading and practice, consider the following resources:

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