classSolution{privateTrieNoderoot=newTrieNode();publicvoidinsert(Stringword){TrieNodenode=root;for(charch:word.toCharArray()){intindex=ch-'a';if(node.child[index]==null){node.child[index]=newTrieNode();}node=node.child[index];node.suggestion.offer(word);if(node.suggestion.size()>3){node.suggestion.pollLast();}}}publicList<List<String>>search(StringsearchWord){List<List<String>>result=newArrayList<>();TrieNodenode=root;for(charch:searchWord.toCharArray()){intindex=ch-'a';if(node!=null){node=node.child[index];}result.add(node==null?Arrays.asList():node.suggestion);}returnresult;}publicList<List<String>>suggestedProducts(String[]products,StringsearchWord){Arrays.sort(products);for(Stringproduct:products){insert(product);}returnsearch(searchWord);}}classTrieNode{TrieNode[]child=newTrieNode[26];LinkedList<String>suggestion=newLinkedList<>();}/*
Complexity depends on the process of building Trie and the length of searchWord. Building Trie cost time O(m * m * n), due to involving comparing String, which cost time O(m) for each comparison. Therefore,
Time: O(m * m * n + L), space: O(m * n + L * m) - including return list ans, where m = average length of products, n = products.length, L = searchWord.length().
*/
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
My Java Solution using Trie Data Structure :