Skip to content
LC-0127 Hard LeetCode

127. Word Ladder

Read the full problem statement on LeetCode.
Difficulty: hard Acceptance: 42% Topics: Hash Table, String, Breadth-First Search
View full problem on LeetCode
Reference solution (spoiler · python)
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, 1)])  # Start from the beginWord with level 1
        visited = set()

        while queue:
            word, level = queue.popleft()
            if word == endWord:
                return level

            for i in range(len(word)):
                for c in "abcdefghijklmnopqrstuvwxyz":
                    new_word = word[:i] + c + word[i + 1 :]
                    if new_word in wordSet and new_word not in visited:
                        visited.add(new_word)
                        queue.append((new_word, level + 1))

        return 0

Solution from kamyu104/LeetCode-Solutions · MIT