208. Implement Trie (Prefix Tree)

Description of Problem

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 * 10^4 calls in total will be made to insert, search, and startsWith.

Solution 1 - using HashMap with Lazy Initialisation

Tags: Trie

Code

import java.util.HashMap;
import java.util.Map;

class Trie {
    private Map<Character,Trie> children;
    private boolean isLastChar;

    public Trie() {
        this.children = null;
        this.isLastChar = false;
    }

    public Trie(boolean isLastChar) {
        this.children = null;
        this.isLastChar = isLastChar;
    }

    public boolean isLastChar(){
        return this.isLastChar;
    }

    public void setIsLastChar(boolean isLastChar){
        this.isLastChar = isLastChar;
    }
    
    public void insert(String word) {
       Trie curr = this;
       int n = word.length();
        for (int i = 0; curr != null && i < n; i++){
            if (curr.children == null){
                curr.children = new HashMap();            
            } 

            Trie next = curr.children.get(word.charAt(i));
            if ( next == null ){
                Trie next_children = new Trie(i == n - 1 ? true: false);
                curr.children.put(word.charAt(i), next_children);
                curr = next_children;
            }else {
                if (i == n - 1) {next.setIsLastChar(true);}
                curr = next;
            }
        }
    }
    
    public boolean search(String word) {
        Trie curr = this;
        int n = word.length();
        for (int i = 0; curr != null && i < n; i++){
            Trie next = curr.children != null ? curr.children.get(word.charAt(i)) : null;
            if ( next == null ){
                return false;
            }else {
                curr = next;
            }
        }
        return curr != null ? curr.isLastChar() : false;
    }
    
    public boolean startsWith(String prefix) {
        Trie curr = this;
        int n = prefix.length();
        for (int i = 0; i < n; i++){
            Trie next = curr.children != null ? curr.children.get(prefix.charAt(i)) : null;
            if ( next == null ){
                return false;
            }else {
                curr = next;
            }
        }
        return curr != null ? true : false;
    }
}

/**
 * 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);
 */

Solution 2 - using Array

Tags: Trie

Code

class Trie {
    private Trie[] children;
    private boolean isLastChar;

    public Trie() {
        this.children = new Trie[26];
        this.isLastChar = false;
    }

    public Trie(boolean isLastChar) {
        this.children = new Trie[26];
        this.isLastChar = isLastChar;
    }

    public boolean isLastChar(){
        return this.isLastChar;
    }

    public void setIsLastChar(boolean isLastChar){
        this.isLastChar = isLastChar;
    }
    
    public void insert(String word) {
       Trie curr = this;
       int n = word.length();
        for (int i = 0; curr != null && i < n; i++){
            Trie next = curr.children[word.charAt(i) - 'a'];
            if ( next == null ){
                Trie next_children = new Trie(i == n - 1 ? true: false);
                curr.children[word.charAt(i) - 'a'] = next_children;
                curr = next_children;
            }else {
                if (i == n - 1) {next.setIsLastChar(true);}
                curr = next;
            }
        }
    }
    
    public boolean search(String word) {
        Trie curr = this;
        int n = word.length();
        for (int i = 0; curr != null && i < n; i++){
            Trie next = curr.children[word.charAt(i) - 'a'];
            if ( next == null ){
                return false;
            }else {
                curr = next;
            }
        }
        return curr != null ? curr.isLastChar() : false;
    }
    
    public boolean startsWith(String prefix) {
        Trie curr = this;
        int n = prefix.length();
        for (int i = 0; i < n; i++){
            Trie next = curr.children[prefix.charAt(i) - 'a'];
            if ( next == null ){
                return false;
            }else {
                curr = next;
            }
        }
        return curr != null ? true : false;
    }
}

/**
 * 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);
 */

Solution 3 - using Array with Lazy initialisation

Tags: Trie

It does not consume less RAM however.

Code

class Trie {
    private Trie[] children;
    private boolean isLastChar;

    public Trie() {
        this.children = null;
        this.isLastChar = false;
    }

    public Trie(boolean isLastChar) {
        this.children = null;
        this.isLastChar = isLastChar;
    }

    public boolean isLastChar(){
        return this.isLastChar;
    }

    public void setIsLastChar(boolean isLastChar){
        this.isLastChar = isLastChar;
    }
    
    public void insert(String word) {
       Trie curr = this;
       int n = word.length();
        for (int i = 0; curr != null && i < n; i++){

            if (curr.children == null) {
                curr.children = new Trie[26];
            }

            Trie next = curr.children == null ? null : curr.children[word.charAt(i) - 'a'];
            if ( next == null ){
                Trie next_children = new Trie(i == n - 1 ? true: false);
                curr.children[word.charAt(i) - 'a'] = next_children;
                curr = next_children;
            }else {
                if (i == n - 1) {next.setIsLastChar(true);}
                curr = next;
            }
        }
    }
    
    public boolean search(String word) {
        Trie curr = this;
        int n = word.length();
        for (int i = 0; curr != null && i < n; i++){
            Trie next = curr.children == null ? null : curr.children[word.charAt(i) - 'a'];
            if ( next == null ){
                return false;
            }else {
                curr = next;
            }
        }
        return curr != null ? curr.isLastChar() : false;
    }
    
    public boolean startsWith(String prefix) {
        Trie curr = this;
        int n = prefix.length();
        for (int i = 0; i < n; i++){
            Trie next = curr.children == null ? null : curr.children[prefix.charAt(i) - 'a'];
            if ( next == null ){
                return false;
            }else {
                curr = next;
            }
        }
        return curr != null ? true : false;
    }
}

/**
 * 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);
 */