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
- 62 lines of C++ from the credited upstream file 1268.cpp.
- 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.
1struct TrieNode {2 vector<shared_ptr<TrieNode>> children;3 const string* word = nullptr;4 TrieNode() : children(26) {}5};6 7class Solution {8 public:9 vector<vector<string>> suggestedProducts(vector<string>& products,10 string searchWord) {11 vector<vector<string>> ans;12 13 for (const string& product : products)14 insert(product);15 16 shared_ptr<TrieNode> node = root;17 18 for (const char c : searchWord) {19 if (node == nullptr || node->children[c - 'a'] == nullptr) {20 node = nullptr;21 ans.push_back({});22 continue;23 }24 node = node->children[c - 'a'];25 ans.push_back(search(node));26 }27 28 return ans;29 }30 31 private:32 shared_ptr<TrieNode> root = make_shared<TrieNode>();33 34 void insert(const string& word) {35 shared_ptr<TrieNode> node = root;36 for (const char c : word) {37 const int i = c - 'a';38 if (node->children[i] == nullptr)39 node->children[i] = make_shared<TrieNode>();40 node = node->children[i];41 }42 node->word = &word;43 }44 45 vector<string> search(shared_ptr<TrieNode> node) {46 vector<string> res;47 dfs(node, res);48 return res;49 }50 51 void dfs(shared_ptr<TrieNode> node, vector<string>& ans) {52 if (ans.size() == 3)53 return;54 if (node == nullptr)55 return;56 if (node->word != nullptr)57 ans.push_back(*node->word);58 for (shared_ptr<TrieNode> child : node->children)59 dfs(child, ans);60 }61};62