- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 68 lines of Python from the credited upstream file 425.py.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class TrieNode:2 def __init__(self):3 self.children: dict[str, TrieNode] = {}4 self.startsWith: list[str] = []5 6 7class Trie:8 def __init__(self, words: list[str]):9 self.root = TrieNode()10 for word in words:11 self._insert(word)12 13 def findBy(self, prefix: str) -> list[str]:14 node = self.root15 for c in prefix:16 if c not in node.children:17 return []18 node = node.children[c]19 return node.startsWith20 21 def _insert(self, word: str) -> None:22 node = self.root23 for c in word:24 node = node.children.setdefault(c, TrieNode())25 node.startsWith.append(word)26 27 28class Solution:29 def wordSquares(self, words: list[str]) -> list[list[str]]:30 if not words:31 return []32 33 n = len(words[0])34 ans = []35 path = []36 trie = Trie(words)37 38 for word in words:39 path.append(word)40 self._dfs(trie, n, path, ans)41 path.pop()42 43 return ans44 45 def _dfs(self, trie: Trie, n: int, path: list[str], ans: list[list[str]]):46 if len(path) == n:47 ans.append(path.copy())48 return49 50 prefix = self._getPrefix(path)51 52 for s in trie.findBy(prefix):53 path.append(s)54 self._dfs(trie, n, path, ans)55 path.pop()56 57 def _getPrefix(self, path: list[str]) -> str:58 """59 e.g. path = ["wall",60 "area"]61 prefix = "le.."62 """63 prefix = []64 index = len(path)65 for s in path:66 prefix.append(s[index])67 return ''.join(prefix)68