Skip to content

208. Implement Trie (Prefix Tree)

A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.

Implement the Trie class:

  • Trie() Initializes the trie object.
  • void insert(String word) Inserts the string word into the trie.
  • boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
  • boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.

Example 1:

Input
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output
[null, null, true, false, true, null, true]

Explanation
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple");   // return True
trie.search("app");     // return False
trie.startsWith("app"); // return True
trie.insert("app");
trie.search("app");     // return True

Constraints:

  • 1 <= word.length, prefix.length <= 2000
  • word and prefix consist only of lowercase English letters.
  • At most 3 * 104 calls in total will be made to insert, search, and startsWith.

Solution:

class Trie {
    class TrieNode{
        TrieNode[] children = new TrieNode[26];
        boolean isWord = false;
    }

    TrieNode root;

    public Trie() {
        root = new TrieNode();
    }

    public void insert(String word) {
        TrieNode cur = root;
        for (int i = 0; i < word.length(); i++){
            TrieNode next = cur.children[word.charAt(i) - 'a'];
            if (next == null){
                next = new TrieNode();
                cur.children[word.charAt(i) - 'a'] = next;
            }
            cur = next;
        }

        cur.isWord = true;
    }

    public boolean search(String word) {
        TrieNode cur = root;

        for (int i = 0; i < word.length(); i++){
            TrieNode next = cur.children[word.charAt(i) - 'a'];
            if (next == null){
                return false;
            }

            cur = next;
        }

        if (cur.isWord == true){
            return true;
        }else {
            return false;
        }
    }

    public boolean startsWith(String prefix) {
        TrieNode cur = root;
        for (int i = 0; i < prefix.length(); i++){
            TrieNode next = cur.children[prefix.charAt(i) - 'a'];
            if (next == null){
                return false;
            }
            cur = next;
        }

        return true;

    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */
class TrieNode{
    private TrieNode[] links; // O(n)

    private final int R = 26;

    private boolean isEnd;

    public TrieNode(){
        links = new TrieNode[R]; // [ , , , , , , ]
    }

    public boolean containsKey(char ch){
        TrieNode cur = links[ch - 'a'];
        if (cur != null){
            return true;
        }else{
            return false;
        }
    }

    public TrieNode get(char ch){
        TrieNode cur = links[ch - 'a'];
        return cur;
    }

    public void put(char ch, TrieNode node){
        links[ch-'a'] = node;
    }

    public void setEnd(){
        isEnd = true;
    }

    public boolean isEnd(){
        return isEnd;
    }
}
class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }

    public void insert(String word) {
        TrieNode node = root;
        for (int i = 0; i < word.length(); i++){ // O(n)
            char curChar = word.charAt(i);
            if (!node.containsKey(curChar)){
                node.put(curChar, new TrieNode());
            }
            node = node.get(curChar);
        }

        node.setEnd();
    }

    // TC: O(n)
    // SC: O(n)


    private TrieNode searchPrefix(String word){
        TrieNode node = root;
        for (int i = 0; i < word.length(); i++){
            char curChar = word.charAt(i);
            if (node.containsKey(curChar)){
                node = node.get(curChar);
            }else{
                return null;
            }
        }

        return node;
    }

    // TC: O(n)
    // SC: O(1)

    public boolean search(String word) {
        TrieNode node = searchPrefix(word); // O(n)
        if (node != null && node.isEnd() == true){
            return true;
        }else{
            return false;
        }
    }

    // TC: O(n)
    // SC: O(1)

    public boolean startsWith(String prefix) {
        TrieNode node = searchPrefix(prefix); // O(n)
        if (node != null){
            return true;
        }else{
            return false;
        }

    }

    // TC: O(n)
    // SC: O(1)
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */