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
- 58 lines of Java from the credited upstream file 1268.java.
- The implementation visibly relies on sequence storage.
- 4 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 public TrieNode[] children = new TrieNode[26];3 public String word;4}5 6class Solution {7 public List<List<String>> suggestedProducts(String[] products, String searchWord) {8 List<List<String>> ans = new ArrayList<>();9 10 for (final String product : products)11 insert(product);12 13 TrieNode node = root;14 15 for (final char c : searchWord.toCharArray()) {16 if (node == null || node.children[c - 'a'] == null) {17 node = null;18 ans.add(new ArrayList<>());19 continue;20 }21 node = node.children[c - 'a'];22 ans.add(search(node));23 }24 25 return ans;26 }27 28 private TrieNode root = new TrieNode();29 30 private void insert(final String word) {31 TrieNode node = root;32 for (final char c : word.toCharArray()) {33 final int i = c - 'a';34 if (node.children[i] == null)35 node.children[i] = new TrieNode();36 node = node.children[i];37 }38 node.word = word;39 }40 41 private List<String> search(TrieNode node) {42 List<String> res = new ArrayList<>();43 dfs(node, res);44 return res;45 }46 47 private void dfs(TrieNode node, List<String> ans) {48 if (ans.size() == 3)49 return;50 if (node == null)51 return;52 if (node.word != null)53 ans.add(node.word);54 for (TrieNode child : node.children)55 dfs(child, ans);56 }57}58