implement-trie

Problem

Implement Trie(prefix Tree)

Problem Description

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

First understand what is trie, please read Trie (Wiki).

Now define TrieNode with char, isWord, children. 1. do insert:

  • iterate through each char in word, check whether current char ch in current node's children. if not, create new TrieNode(ch), put into current node children, other wise do nothing

  • then reset current node as curr.children.get(ch).

  • after word, set current node isWord = true.

    1. do search:

  • iterate through each char in word, for each ch:

    • if ch is in current node children, continue, if not in current node's children, return false. terminate early.

    • reset current node as curr.children.get(ch), (go next level)

    • until at last char, check current node isWord is true or not, if isWord = true, return true. otherwise no word in trie.

      1. do prefix search:

  • same search steps as search word.

  • at last step, return true (meaning it has prefix, do need to check isWord).

For example:

Implement Trie

Complexity Analysis

insert(word): O(n) -- n is the length of word

search(word): O(n) -- n is the length of word

Code

Last updated

Was this helpful?