Implement Trie (Prefix Tree)

Medium

Implement a trie with insertsearch, 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.

Trie is a rooted tree. Its nodes have the following fields:

  • Maximum of R links to its children, where each link corresponds to one of R character values from dataset alphabet. In this article we assume that R is 26, the number of lowercase latin letters.
  • Boolean field which specifies whether the node corresponds to the end of the key, or is just a key prefix.
  • The word CODE will be represented in the following way in Trie.

TrieNode Implementation

class TrieNode{
    private boolean endOfWord;
    private Map<Character, TrieNode> children = new HashMap<>();
    
    public boolean containsKey(char ch){
        return this.children.containsKey(ch);
    }
    
    public TrieNode getNode(char ch){
        return this.children.get(ch);
    }
    
    public void addNode(char ch, TrieNode node){
        this.children.put(ch, node);
    }
    
    public void setEndOfWord(){
        this.endOfWord = true;
    }
    
    public boolean isEndOfWord(){
        return endOfWord;
    }
}

Trie Implementation

class Trie {

    TrieNode root = null;
    
    /** Initialize your data structure here. */
    public Trie() {
        root = new TrieNode();
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode node = root;
        for(char ch : word.toCharArray()){
            if(!node.containsKey(ch)){
                node.addNode(ch, new TrieNode());
            }
            node = node.getNode(ch);
        }
        node.setEndOfWord();
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode node = root;
        for(char ch : word.toCharArray()){
            if(!node.containsKey(ch)){
                return false;
            }
            node = node.getNode(ch);
        }
        return node != null && node.isEndOfWord();
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode node = root;
        for(char ch : prefix.toCharArray()){
            if(!node.containsKey(ch)){
                return false;
            }
            node = node.getNode(ch);
        }
        return node != null;
    }
}

Categories: Trie

Tagged as: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s