KatInterview

127. Word Ladder

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the length of the shortest transformation sequence from a beginWord to an endWord. This can be modeled as finding the shortest path in a graph. The nodes of the graph are the words, and an edge exists between two words if they differ by exactly one letter. Since all edges have an equal weight (1), Breadth-First Search (BFS) is the perfect algorithm to find the shortest path.

Solution

Word Ladder in Python

class Solution:
    def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
        # Use a set for O(1) average time complexity word lookup.
        wordSet = set(wordList)
        # If endWord is not in the dictionary, a transformation is impossible.
        if endWord not in wordSet:
            return 0

        # Sets for bidirectional BFS frontiers.
        beginSet = {beginWord}
        endSet = {endWord}
        
        # Visited set to prevent cycles and redundant work.
        visited = {beginWord, endWord}
        
        length = 1

        while beginSet and endSet:
            length += 1
            
            # Always expand the smaller frontier to optimize the search.
            if len(beginSet) > len(endSet):
                beginSet, endSet = endSet, beginSet

            nextLevelSet = set()
            # Iterate through the current frontier.
            for word in beginSet:
                # Generate all possible one-letter-different neighbors.
                for i in range(len(word)):
                    for char_code in range(ord('a'), ord('z') + 1):
                        new_char = chr(char_code)
                        if word[i] == new_char:
                            continue
                        
                        newWord = word[:i] + new_char + word[i+1:]
                        
                        # If a neighbor is in the other frontier, a path is found.
                        if newWord in endSet:
                            return length
                        
                        # If the neighbor is a valid word and not visited, add to the next frontier.
                        if newWord in wordSet and newWord not in visited:
                            visited.add(newWord)
                            nextLevelSet.add(newWord)
            
            # Move to the next level.
            beginSet = nextLevelSet

        return 0 # No path found.

Word Ladder in Java

class Solution {
    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        // Use a hash set for O(1) average time complexity word lookup.
        Set<String> wordSet = new HashSet<>(wordList);
        
        // If endWord is not in the dictionary, a transformation is impossible.
        if (!wordSet.contains(endWord)) {
            return 0;
        }

        // Sets for bidirectional BFS frontiers.
        Set<String> beginSet = new HashSet<>();
        beginSet.add(beginWord);
        Set<String> endSet = new HashSet<>();
        endSet.add(endWord);

        // Visited set to prevent cycles and redundant work.
        Set<String> visited = new HashSet<>();
        visited.add(beginWord);
        visited.add(endWord);

        int length = 1;

        while (!beginSet.isEmpty() && !endSet.isEmpty()) {
            length++;

            // Always expand the smaller frontier to optimize the search.
            if (beginSet.size() > endSet.size()) {
                Set<String> temp = beginSet;
                beginSet = endSet;
                endSet = temp;
            }

            Set<String> nextLevelSet = new HashSet<>();
            // Iterate through the current frontier.
            for (String word : beginSet) {
                char[] chars = word.toCharArray();
                // Generate all possible one-letter-different neighbors.
                for (int i = 0; i < chars.length; i++) {
                    char originalChar = chars[i];
                    for (char c = 'a'; c <= 'z'; c++) {
                        if (c == originalChar) continue;
                        
                        chars[i] = c;
                        String newWord = new String(chars);

                        // If a neighbor is in the other frontier, a path is found.
                        if (endSet.contains(newWord)) {
                            return length;
                        }

                        // If the neighbor is a valid word and not visited, add to the next frontier.
                        if (wordSet.contains(newWord) && !visited.contains(newWord)) {
                            visited.add(newWord);
                            nextLevelSet.add(newWord);
                        }
                    }
                    chars[i] = originalChar; // Backtrack the change.
                }
            }
            // Move to the next level.
            beginSet = nextLevelSet;
        }

        return 0; // No path found.
    }
}

Word Ladder in C++

class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        // Use a hash set for O(1) average time complexity word lookup.
        unordered_set<string> wordSet(wordList.begin(), wordList.end());
        
        // If endWord is not in the dictionary, a transformation is impossible.
        if (wordSet.find(endWord) == wordSet.end()) {
            return 0;
        }

        // Sets for bidirectional BFS frontiers.
        unordered_set<string> beginSet = {beginWord};
        unordered_set<string> endSet = {endWord};
        
        // Visited set to prevent cycles and redundant work.
        unordered_set<string> visited;
        visited.insert(beginWord);
        visited.insert(endWord);

        int length = 1;

        while (!beginSet.empty() && !endSet.empty()) {
            length++;

            // Always expand the smaller frontier to optimize the search.
            if (beginSet.size() > endSet.size()) {
                swap(beginSet, endSet);
            }

            unordered_set<string> nextLevelSet;
            // Iterate through the current frontier.
            for (string word : beginSet) {
                // Generate all possible one-letter-different neighbors.
                for (int i = 0; i < word.length(); ++i) {
                    char originalChar = word[i];
                    for (char c = 'a'; c <= 'z'; ++c) {
                        if (c == originalChar) continue;
                        
                        word[i] = c;
                        
                        // If a neighbor is in the other frontier, a path is found.
                        if (endSet.count(word)) {
                            return length;
                        }

                        // If the neighbor is a valid word and not visited, add to the next frontier.
                        if (wordSet.count(word) && visited.find(word) == visited.end()) {
                            visited.insert(word);
                            nextLevelSet.insert(word);
                        }
                    }
                    word[i] = originalChar; // Backtrack the change.
                }
            }
            // Move to the next level.
            beginSet = nextLevelSet;
        }

        return 0; // No path found.
    }
};

Word Ladder in TypeScript

function ladderLength(beginWord: string, endWord: string, wordList: string[]): number {
    // Use a set for O(1) average time complexity word lookup.
    const wordSet = new Set(wordList);
    // If endWord is not in the dictionary, a transformation is impossible.
    if (!wordSet.has(endWord)) {
        return 0;
    }

    // Sets for bidirectional BFS frontiers.
    let beginSet = new Set<string>([beginWord]);
    let endSet = new Set<string>([endWord]);
    
    // Visited set to prevent cycles and redundant work.
    const visited = new Set<string>([beginWord, endWord]);
    let length = 1;

    while (beginSet.size > 0 && endSet.size > 0) {
        length++;
        
        // Always expand the smaller frontier to optimize the search.
        if (beginSet.size > endSet.size) {
            [beginSet, endSet] = [endSet, beginSet]; // Swap sets
        }

        const nextLevelSet = new Set<string>();
        // Iterate through the current frontier.
        for (const word of beginSet) {
            // Generate all possible one-letter-different neighbors.
            for (let i = 0; i < word.length; i++) {
                for (let j = 0; j < 26; j++) {
                    const newChar = String.fromCharCode('a'.charCodeAt(0) + j);
                    if (word[i] === newChar) continue;
                    
                    const newWord = word.substring(0, i) + newChar + word.substring(i + 1);

                    // If a neighbor is in the other frontier, a path is found.
                    if (endSet.has(newWord)) {
                        return length;
                    }

                    // If the neighbor is a valid word and not visited, add to the next frontier.
                    if (wordSet.has(newWord) && !visited.has(newWord)) {
                        visited.add(newWord);
                        nextLevelSet.add(newWord);
                    }
                }
            }
        }
        // Move to the next level.
        beginSet = nextLevelSet;
    }

    return 0; // No path found.
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.