Trie with three suggestions per node
Time O(total characters + n log n) Space O(total characters)Sort products, then insert each; every node on its path keeps it if it has fewer than three. Walk searchWord, collecting each node's list (empty once the path breaks).
import java.util.*;
class Solution {
private static class Node {
Node[] next = new Node[26];
List<String> top = new ArrayList<>();
}
public List<List<String>> suggestedProducts(String[] products, String searchWord) {
Arrays.sort(products);
Node root = new Node();
for (String p : products) {
Node n = root;
for (char c : p.toCharArray()) {
if (n.next[c - 'a'] == null) n.next[c - 'a'] = new Node();
n = n.next[c - 'a'];
if (n.top.size() < 3) n.top.add(p);
}
}
List<List<String>> out = new ArrayList<>();
Node n = root;
for (char c : searchWord.toCharArray()) {
n = n == null ? null : n.next[c - 'a'];
out.add(n == null ? new ArrayList<>() : n.top);
}
return out;
}
}Verdict: Good when many queries share the same products.