1. Implement Trie (Prefix Tree)

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

Solution:

class Trie
{
public:
    /** Initialize your data structure here. */

    struct trieNode
    {
        char val;
        int count = 0;
        int endsHere = 0;
        trieNode *child[26];
    };
    trieNode *root;
    
    trieNode *getNode(int index)
    {
        trieNode *newNode = new trieNode;
        newNode->val = index;
        newNode->count = 0;
        newNode->endsHere = 0;
        for (int i = 0; i < 26; i++)
        {
            newNode->child[i] = NULL;
        }
        return newNode;
    }

    Trie()
    {
        root = getNode('/');
    }

    /** Inserts a word into the trie. */
    void insert(string word)
    {
        trieNode *cur = root;
        for (int i = 0; i < word.length(); i++)
        {
            int index = word[i] - 97;
            if (cur->child[index] == NULL)
            {
                cur->child[index] = getNode(index);
            }
            else
            {
                cur->child[index]->count++;
            }
            cur = cur->child[index];
        }
        cur->endsHere++;
    }

    /** Returns if the word is in the trie. */
    bool search(string word)
    {
        trieNode *cur = root;
        int index;
        for (int i = 0; i < word.length(); i++)
        {
            index = word[i] - 97;
            if (cur->child[index] == NULL)
            {
                return false;
            }
            cur = cur->child[index];
        }
        if (cur->endsHere > 0)
        {
            return true;
        }
        return false;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix)
    {
        trieNode *cur = root;
        int index;
        for (int i = 0; i < prefix.length(); i++)
        {
            index = prefix[i] - 97;
            if (cur->child[index] == NULL)
            {
                return false;
            }
            cur = cur->child[index];
        }
        return true;
    }
};

Time Complexity: O( len(longest String) * Q)

Last updated