- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 77 lines of Python from the credited upstream file 126.py.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- No explicit loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def findLadders(self, beginWord: str, endWord: str, wordList: list[str]) -> list[list[str]]:3 wordSet = set(wordList)4 if endWord not in wordList:5 return []6 7 8 graph: dict[str, list[str]] = collections.defaultdict(list)9 10 11 if not self._bfs(beginWord, endWord, wordSet, graph):12 return []13 14 ans = []15 self._dfs(graph, beginWord, endWord, [beginWord], ans)16 return ans17 18 def _bfs(19 self,20 beginWord: str,21 endWord: str,22 wordSet: set[str],23 graph: dict[str, list[str]],24 ) -> bool:25 currentLevelWords = {beginWord}26 27 while currentLevelWords:28 for word in currentLevelWords:29 wordSet.discard(word)30 nextLevelWords = set()31 reachEndWord = False32 for parent in currentLevelWords:33 for child in self._getChildren(parent, wordSet):34 if child in wordSet:35 nextLevelWords.add(child)36 graph[parent].append(child)37 if child == endWord:38 reachEndWord = True39 if reachEndWord:40 return True41 currentLevelWords = nextLevelWords42 43 return False44 45 def _getChildren(self, parent: str, wordSet: set[str]) -> list[str]:46 children = []47 s = list(parent)48 49 for i, cache in enumerate(s):50 for c in string.ascii_lowercase:51 if c == cache:52 continue53 s[i] = c54 child = ''.join(s)55 if child in wordSet:56 children.append(child)57 s[i] = cache58 59 return children60 61 def _dfs(62 self,63 graph: dict[str, list[str]],64 word: str,65 endWord: str,66 path: list[str],67 ans: list[list[str]],68 ) -> None:69 if word == endWord:70 ans.append(path.copy())71 return72 73 for child in graph.get(word, []):74 path.append(child)75 self._dfs(graph, child, endWord, path, ans)76 path.pop()77