// Custom class Trie with function to get 3 words starting with given prefix classTrie {
// Node definition of a trie classNode { booleanisWord=false; List<Node> children = Arrays.asList(newNode[26]); }; Node Root, curr; List<String> resultBuffer;
// Runs a DFS on trie starting with given prefix and adds all the words in the resultBuffer, limiting result size to 3 voiddfsWithPrefix(Node curr, String word) { if (resultBuffer.size() == 3) return; if (curr.isWord) resultBuffer.add(word);
// Run DFS on all possible paths. for (charc='a'; c <= 'z'; c++) if (curr.children.get(c - 'a') != null) dfsWithPrefix(curr.children.get(c - 'a'), word + c); } Trie() { Root = newNode(); }
// Inserts the string in trie. voidinsert(String s) {
// Points curr to the root of trie. curr = Root; for (char c : s.toCharArray()) { if (curr.children.get(c - 'a') == null) curr.children.set(c - 'a', newNode()); curr = curr.children.get(c - 'a'); }
// Mark this node as a completed word. curr.isWord = true; } List<String> getWordsStartingWith(String prefix) { curr = Root; resultBuffer = newArrayList<String>(); // Move curr to the end of prefix in its trie representation. for (char c : prefix.toCharArray()) { if (curr.children.get(c - 'a') == null) return resultBuffer; curr = curr.children.get(c - 'a'); } dfsWithPrefix(curr, prefix); return resultBuffer; } }; classSolution { List<List<String>> suggestedProducts(String[] products, String searchWord) { Trietrie=newTrie(); List<List<String>> result = newArrayList<>(); // Add all words to trie. for (String w : products) trie.insert(w); Stringprefix=newString(); for (char c : searchWord.toCharArray()) { prefix += c; result.add(trie.getWordsStartingWith(prefix)); } return result; } };