KatInterview

126. Word Ladder II

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 all the shortest transformation sequences from a beginWord to an endWord. A transformation is valid if adjacent words in the sequence differ by only one letter, and all words (except possibly beginWord) are in a given wordList. This problem can be modeled as finding all shortest paths in an unweighted graph.

Solution

Word Ladder II in Python

from collections import deque, defaultdict

class Solution:
    def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
        wordSet = set(wordList)
        if endWord not in wordSet:
            return []

        results = []
        # Use defaultdict to simplify adding parents
        parents = defaultdict(list)
        # dist map also serves as a visited set
        dist = {beginWord: 0}
        queue = deque([beginWord])
        
        found = False
        level = 0
        
        # BFS to build parent graph
        while queue and not found:
            level_size = len(queue)
            level += 1
            for _ in range(level_size):
                current_word = queue.popleft()
                
                for i in range(len(current_word)):
                    for char_code in range(ord('a'), ord('z') + 1):
                        char = chr(char_code)
                        neighbor = current_word[:i] + char + current_word[i+1:]
                        
                        if neighbor in wordSet:
                            # If not visited yet
                            if neighbor not in dist:
                                dist[neighbor] = level
                                parents[neighbor].append(current_word)
                                queue.append(neighbor)
                                if neighbor == endWord:
                                    found = True
                            # If visited and is on the same level, it's another shortest path
                            elif dist[neighbor] == level:
                                parents[neighbor].append(current_word)
            # No need to check 'not found' here, loop condition handles it.
            # The 'found' flag inside the loop ensures we finish the current level.

        # DFS to reconstruct paths
        if found:
            current_path = []
            self.dfs(endWord, beginWord, parents, current_path, results)
            
        return results

    def dfs(self, word, beginWord, parents, current_path, results):
        current_path.append(word)
        
        if word == beginWord:
            # Path found, add a reversed copy to results
            results.append(current_path[::-1])
            current_path.pop()
            return
        
        if word in parents:
            for p in parents[word]:
                self.dfs(p, beginWord, parents, current_path, results)
        
        # Backtrack
        current_path.pop()

Word Ladder II in Java

class Solution {
    public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
        // Use a Set for O(1) lookups
        Set<String> wordSet = new HashSet<>(wordList);
        if (!wordSet.contains(endWord)) {
            return new ArrayList<>();
        }

        List<List<String>> results = new ArrayList<>();
        // Map to store parent nodes for path reconstruction
        Map<String, List<String>> parents = new HashMap<>();
        // Map to store distances from beginWord, also serves as a visited set
        Map<String, Integer> dist = new HashMap<>();

        Queue<String> queue = new LinkedList<>();
        
        // BFS to build the parent graph
        queue.offer(beginWord);
        dist.put(beginWord, 0);
        
        int level = 0;
        boolean found = false;

        while (!queue.isEmpty()) {
            int levelSize = queue.size();
            level++;
            // Process one level at a time
            for (int i = 0; i < levelSize; 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++) {
                        wordChars[j] = c;
                        String neighbor = new String(wordChars);
                        
                        if (wordSet.contains(neighbor)) {
                            // If neighbor is not visited yet
                            if (!dist.containsKey(neighbor)) {
                                dist.put(neighbor, level);
                                queue.offer(neighbor);
                                parents.computeIfAbsent(neighbor, k -> new ArrayList<>()).add(currentWord);
                                if (neighbor.equals(endWord)) {
                                    found = true;
                                }
                            } else if (dist.get(neighbor) == level) {
                                // Found another shortest path to the neighbor
                                parents.get(neighbor).add(currentWord);
                            }
                        }
                    }
                    wordChars[j] = originalChar; // Backtrack character change
                }
            }
            if (found) {
                break; // Stop BFS once endWord's level is fully explored
            }
        }

        // DFS to reconstruct paths from endWord to beginWord
        if (found) {
            List<String> currentPath = new ArrayList<>();
            dfs(endWord, beginWord, parents, currentPath, results);
        }
        
        return results;
    }

    private void dfs(String word, String beginWord, Map<String, List<String>> parents, 
                     List<String> currentPath, List<List<String>> results) {
        currentPath.add(word);

        if (word.equals(beginWord)) {
            // Path found, create a copy, reverse it, and add to results
            List<String> pathCopy = new ArrayList<>(currentPath);
            Collections.reverse(pathCopy);
            results.add(pathCopy);
        } else if (parents.containsKey(word)) {
            // Recurse on parent nodes
            for (String parent : parents.get(word)) {
                dfs(parent, beginWord, parents, currentPath, results);
            }
        }

        // Backtrack
        currentPath.remove(currentPath.size() - 1);
    }
}

Word Ladder II in C++

class Solution {
public:
    vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
        unordered_set<string> wordSet(wordList.begin(), wordList.end());
        if (wordSet.find(endWord) == wordSet.end()) {
            return {};
        }

        vector<vector<string>> results;
        unordered_map<string, vector<string>> parents;
        unordered_map<string, int> dist;
        
        queue<string> q;
        
        // BFS to build parent graph
        q.push(beginWord);
        dist[beginWord] = 0;
        
        int level = 0;
        bool found = false;
        
        while (!q.empty()) {
            int level_size = q.size();
            level++;
            for (int i = 0; i < level_size; ++i) {
                string current_word = q.front();
                q.pop();
                
                string temp_word = current_word;
                for (int j = 0; j < temp_word.length(); ++j) {
                    char original_char = temp_word[j];
                    for (char c = 'a'; c <= 'z'; ++c) {
                        temp_word[j] = c;
                        if (wordSet.count(temp_word)) {
                            // If not visited yet
                            if (dist.find(temp_word) == dist.end()) {
                                dist[temp_word] = level;
                                parents[temp_word].push_back(current_word);
                                q.push(temp_word);
                                if (temp_word == endWord) {
                                    found = true;
                                }
                            } else if (dist[temp_word] == level) {
                                // Found another path of same length
                                parents[temp_word].push_back(current_word);
                            }
                        }
                    }
                    temp_word[j] = original_char; // backtrack
                }
            }
            if (found) {
                break;
            }
        }

        // DFS to reconstruct paths
        if (found) {
            vector<string> current_path;
            dfs(endWord, beginWord, parents, current_path, results);
        }
        
        return results;
    }

private:
    void dfs(const string& word, const string& beginWord, 
             unordered_map<string, vector<string>>& parents, 
             vector<string>& current_path, 
             vector<vector<string>>& results) {
        
        current_path.push_back(word);
        
        if (word == beginWord) {
            vector<string> path_copy = current_path;
            reverse(path_copy.begin(), path_copy.end());
            results.push_back(path_copy);
            current_path.pop_back(); // backtrack
            return;
        }
        
        if (parents.count(word)) {
            for (const string& p : parents[word]) {
                dfs(p, beginWord, parents, current_path, results);
            }
        }
        
        current_path.pop_back(); // backtrack
    }
};

Word Ladder II in TypeScript

function findLadders(beginWord: string, endWord: string, wordList: string[]): string[][] {
    const wordSet = new Set(wordList);
    if (!wordSet.has(endWord)) {
        return [];
    }

    const results: string[][] = [];
    const parents = new Map<string, string[]>();
    const dist = new Map<string, number>();
    const queue: string[] = [];

    // BFS to build parent graph
    queue.push(beginWord);
    dist.set(beginWord, 0);

    let level = 0;
    let found = false;

    let head = 0;
    while (head < queue.length) {
        const levelSize = queue.length - head;
        level++;
        for (let i = 0; i < levelSize; i++) {
            const currentWord = queue[head++];

            for (let j = 0; j < currentWord.length; j++) {
                const originalChar = currentWord[j];
                for (let k = 0; k < 26; k++) {
                    const char = String.fromCharCode('a'.charCodeAt(0) + k);
                    const neighbor = currentWord.substring(0, j) + char + currentWord.substring(j + 1);

                    if (wordSet.has(neighbor)) {
                        if (!dist.has(neighbor)) {
                            dist.set(neighbor, level);
                            queue.push(neighbor);
                            parents.set(neighbor, [currentWord]);
                            if (neighbor === endWord) {
                                found = true;
                            }
                        } else if (dist.get(neighbor) === level) {
                            parents.get(neighbor)!.push(currentWord);
                        }
                    }
                }
            }
        }
        if (found) {
            break;
        }
    }

    // DFS to reconstruct paths
    if (found) {
        const currentPath: string[] = [];
        dfs(endWord, beginWord, parents, currentPath, results);
    }

    return results;
}

function dfs(
    word: string,
    beginWord: string,
    parents: Map<string, string[]>,
    currentPath: string[],
    results: string[][]
): void {
    currentPath.push(word);

    if (word === beginWord) {
        results.push([...currentPath].reverse());
    } else {
        const parentWords = parents.get(word) || [];
        for (const p of parentWords) {
            dfs(p, beginWord, parents, currentPath, results);
        }
    }

    currentPath.pop(); // Backtrack
}

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.