Approach
Depth-first search
For Search Suggestions System, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 52 lines of Python from the credited upstream file 1268.py.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
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.word: str | None = None5 6 7class Solution:8 def suggestedProducts(9 self,10 products: list[str],11 searchWord: str12 ) -> list[list[str]]:13 ans = []14 root = TrieNode()15 16 def insert(word: str) -> None:17 node = root18 for c in word:19 node = node.children.setdefault(c, TrieNode())20 node.word = word21 22 def search(node: TrieNode | None) -> list[str]:23 res: list[str] = []24 dfs(node, res)25 return res26 27 def dfs(node: TrieNode | None, res: list[str]) -> None:28 if len(res) == 3:29 return30 if not node:31 return32 if node.word:33 res.append(node.word)34 for c in string.ascii_lowercase:35 if c in node.children:36 dfs(node.children[c], res)37 38 for product in products:39 insert(product)40 41 node = root42 43 for c in searchWord:44 if not node or c not in node.children:45 node = None46 ans.append([])47 continue48 node = node.children[c]49 ans.append(search(node))50 51 return ans52