PracticeNeetCode ↗LeetCode ↗
Given a beginWord, an endWord, and a wordList, return the length of the shortest transformation sequence from beginWord to endWord, changing exactly one letter at a time, where every intermediate word must appear in wordList. Return 0 if no such sequence exists.
wordList into a set for O(1) lookups; if endWord isn't in it, return 0 immediately.beginWord, tracking the transformation length (starting at 1).endWord is generated as a neighbor, return the current length + 1. If the queue empties first, return 0.Time: O(n · 26 · L), where n is the word count and L is the word length — Space: O(n · L)
from collections import deque
def ladderLength(beginWord: str, endWord: str, wordList: list[str]) -> int:
word_set = set(wordList)
if endWord not in word_set:
return 0
queue = deque([(beginWord, 1)])
word_set.discard(beginWord)
while queue:
word, length = queue.popleft()
if word == endWord:
return length
for i in range(len(word)):
for ch in "abcdefghijklmnopqrstuvwxyz":
next_word = word[:i] + ch + word[i + 1:]
if next_word in word_set:
word_set.remove(next_word)
queue.append((next_word, length + 1))
return 0How the solution above works, piece by piece.
endWord isn't in it, no ladder exists.beginWord, storing each word with its ladder length.endWord is popped, its length is the shortest. O(N · L · 26) for N words of length L.Running it on beginWord = "hit", endWord = "cog":
cog is reached is along a shortest chain: hit → hot → dot → dog → cog, length 5. (log → cog also exists, but cog was already taken from the word set by then.)