Simple BFS with creating adjacent words in O(26⋅m) time. The total time complexity is O(n2⋅m) where n is the number of words and m is the length of the word.
from collections import defaultdict, deque
classSolution:defladderLength(self, beginWord:str, endWord:str, wordList: List[str])->int: adj = defaultdict(list) wordList.append(beginWord) wordSet =set(wordList) queue = deque() seen =set() queue.append((beginWord,0)) seen.add(beginWord)while queue: word, dist = queue.popleft()if word == endWord:return dist +1for i inrange(len(word)):for c in'abcdefghijklmnopqrstuvwxyz': adj_word = word[:i]+ c + word[i +1:]if adj_word in wordSet and adj_word notin seen: queue.append((adj_word, dist +1)) seen.add(adj_word)return0