from typing import List
from collections import deque
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
"""
Finds the length of the shortest transformation sequence from beginWord to endWord,
such that:
1. Only one letter can be changed at a time.
2. Each transformed word must exist in the word list.
Uses BFS for shortest path in an unweighted graph (words as nodes).
Time: O(N * L * 26), where N = len(wordList), L = len(beginWord)
Space: O(N)
:param beginWord: Starting word
:param endWord: Target word
:param wordList: List of valid words
:return: Length of shortest sequence, or 0 if impossible
"""
if endWord not in wordList:
return 0
# Use set for O(1) lookups
word_set = set(wordList)
queue = deque([(beginWord, 1)]) # (word, distance)
visited = set([beginWord])
while queue:
word, dist = queue.popleft()
if word == endWord:
return dist
# Try changing each position to each letter
for i in range(len(word)):
for c in 'abcdefghijklmnopqrstuvwxyz':
new_word = word[:i] + c + word[i+1:]
if new_word in word_set and new_word not in visited:
visited.add(new_word)
queue.append((new_word, dist + 1))
# Optional optimization: remove from set to avoid regenerating
# from other paths (prevents duplicates in queue)
word_set.discard(new_word)
return 0
# Example usage and test cases
def test_word_ladder():
sol = Solution()
# Test Case 1: Standard example
print(sol.ladderLength("hit", "cog", ["hot","dot","dog","lot","log","cog"]) == 5) # True
# Sequence: hit -> hot -> dot -> dog -> cog
# Test Case 2: No path
print(sol.ladderLength("hit", "cog", ["hot","dot","dog","lot","log"]) == 0) # True
# Test Case 3: Direct match
print(sol.ladderLength("hit", "hit", ["hot","dot","dog","lot","log"]) == 1) # True
# Test Case 4: beginWord not in list
print(sol.ladderLength("aa", "bb", ["bb"]) == 2) # True (aa -> ab -> bb, assuming ab generated but wait, no: only if intermediates in list? Wait, bb in list, but ab not.
# Correction: actually impossible unless intermediates present. This should be 0? Wait no:
# For "aa" to "bb": possible neighbor "ba","ab", etc., but if not in list, can't.
# In this case, list=["bb"], no path unless direct, so 0.
print(sol.ladderLength("aa", "bb", ["bb"]) == 0) # True
if __name__ == "__main__":
test_word_ladder()
Explanation
BFS Approach: Treat words as graph nodes. Edges exist between words differing by one letter. BFS guarantees the shortest path (fewest transformations).
Neighbor Generation: For each word, iterate over each position (L positions) and try all 26 letters, forming potential neighbors. Check if in word_set and unvisited.