Link: 127. Word Ladder - Hard
Track: Amazon Tag
Question
Restate
Edge Case
Method 1
Method 2
Method
Approach
Complexity
- Time Complexity: O()
- Space Complexity: O(N)
Code
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
wordList_set = set(wordList)
if endWord not in wordList_set:
return 0
if beginWord == endWord:
return 1
queue = deque([beginWord])
visited = set([beginWord])
count = 1
while queue:
for _ in range(len(queue)):
word = queue.popleft()
for i in range(len(word)): # O(L)
for c in 'abcdefghijklmnopqrstuvwxyz':
new_word = word[:i] + c + word[i + 1:] # O(L)
if new_word == endWord:
return count + 1
if (new_word in wordList_set
and new_word not in visited):
queue.append(new_word)
visited.add(new_word)
count += 1
return 0History
- Jan-xx-2026 Peeked