Implement a trie with insert, search, and startsWith methods.

Example:

Trie trie = new Trie(); trie.insert(“apple”); trie.search(“apple”); // returns true trie.search(“app”); // returns false trie.startsWith(“app”); // returns true trie.insert(“app”); trie.search(“app”); // returns true

Note:

  • You may assume that all inputs are consist of lowercase letters a-z.
  • All inputs are guaranteed to be non-empty strings.

Solution

Trie is a N-Ary tree with property like every node have max 26 child nodes. Store Words from the root to the leaf node and make leaf node as endOfWord.

Code

Output

true true false

We encourage you to write a comment if you have a better solution or having any doubt on the above topic.

Leave a Reply

Your email address will not be published. Required fields are marked *