← Back to Leo Academy Masterclass

Problem #127: Word Ladder

Hard Graph BFS

Intuition & Strategy Breakdown

Use BFS starting from beginWord. Change one letter at a time to explore valid transformed words in wordList, returning shortest path length.

Python Solution

from collections import deque

class Solution:
    def ladderLength(self, beginWord: str, endWord: str, wordList: list[str]) -> int:
        wordSet = set(wordList)
        if endWord not in wordSet:
            return 0
        
        queue = deque([beginWord])
        level = 1
        
        while queue:
            for _ in range(len(queue)):
                word = queue.popleft()
                if word == endWord:
                    return level
                
                for i in range(len(word)):
                    for c in "abcdefghijklmnopqrstuvwxyz":
                        next_word = word[:i] + c + word[i+1:]
                        if next_word in wordSet:
                            wordSet.remove(next_word)
                            queue.append(next_word)
            level += 1
        
        return 0

Java Solution

import java.util.*;

class Solution {
    public int ladderLength(String beginWord, String endWord, List wordList) {
        Set wordSet = new HashSet<>(wordList);
        if (!wordSet.contains(endWord)) return 0;
        
        Queue queue = new LinkedList<>();
        queue.add(beginWord);
        int level = 1;
        
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                String word = queue.poll();
                if (word.equals(endWord)) return level;
                
                char[] chars = word.toCharArray();
                for (int j = 0; j < chars.length; j++) {
                    char originalChar = chars[j];
                    for (char c = 'a'; c <= 'z'; c++) {
                        chars[j] = c;
                        String nextWord = new String(chars);
                        if (wordSet.contains(nextWord)) {
                            wordSet.remove(nextWord);
                            queue.add(nextWord);
                        }
                    }
                    chars[j] = originalChar;
                }
            }
            level++;
        }
        return 0;
    }
}
Watch Interactive Video on Leo Academy Main App