Problem solution · Java

Search Suggestions System

Search Suggestions System: a Java solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Depth-first search
Source
walkccc LeetCode Solutions
Length
58 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

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.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeSearch Suggestions System · JavaJava
Use this to learn the idea, then write your own version.
class TrieNode {  public TrieNode[] children = new TrieNode[26];  public String word;} class Solution {  public List<List<String>> suggestedProducts(String[] products, String searchWord) {    List<List<String>> ans = new ArrayList<>();     for (final String product : products)      insert(product);     TrieNode node = root;     for (final char c : searchWord.toCharArray()) {      if (node == null || node.children[c - 'a'] == null) {        node = null;        ans.add(new ArrayList<>());        continue;      }      node = node.children[c - 'a'];      ans.add(search(node));    }     return ans;  }   private TrieNode root = new TrieNode();   private void insert(final String word) {    TrieNode node = root;    for (final char c : word.toCharArray()) {      final int i = c - 'a';      if (node.children[i] == null)        node.children[i] = new TrieNode();      node = node.children[i];    }    node.word = word;  }   private List<String> search(TrieNode node) {    List<String> res = new ArrayList<>();    dfs(node, res);    return res;  }   private void dfs(TrieNode node, List<String> ans) {    if (ans.size() == 3)      return;    if (node == null)      return;    if (node.word != null)      ans.add(node.word);    for (TrieNode child : node.children)      dfs(child, ans);  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗