The Indian Engineer

Problem 208 Implement Trie (Prefix Tree)

Posted on 7 mins

Hash-Table String Design Trie

Problem Statement

Link - Problem 208

Question

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:

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:

Solution

class TrieNode {
    public:
        TrieNode* links[26];
        bool isLeaf = false;
};

class Trie {
    TrieNode* root;
public:
    Trie() {
        root = new TrieNode();
    }

    void insert(string word) {
        TrieNode* temp = root;
        for(char c:word)
        {
            if(!temp->links[c-'a'])
                temp->links[c-'a'] = new TrieNode();
            temp = temp->links[c-'a'];
        }
        temp->isLeaf = true;
    }

    bool search(string word) {
        TrieNode* temp = root;
        for(char c : word)
        {
            if(!temp -> links[c - 'a'])
                return false;
            temp = temp -> links[c - 'a'];
        }
        return temp -> isLeaf;
    }

    bool startsWith(string prefix) {
         TrieNode* temp = root;
        for(char c : prefix)
        {
            if(!temp -> links[c - 'a'])
                return false;
            temp = temp -> links[c - 'a'];
        }
        return true;

    }
};

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

Complexity Analysis

| Algorithm                 | Time Complexity | Space Complexity |
| ------------------------- | --------------- | ---------------- |
| Trie Insertion and Search | O(m)            | O(m)             |

Explanation

Intial Thoughts

To start, we should think about how we can structure our data to efficiently store and retrieve strings. A tree-like structure comes to mind, where each node represents a character in the string. We can use a root node as the starting point and create child nodes for each subsequent character. This way, we can easily insert new strings, search for existing ones, and check for prefixes. The key is to ensure that our data structure allows for fast lookup and insertion. We can imagine it like a file system, where each directory (node) contains a list of its children (other directories or files). The main considerations are how to handle character storage, node creation, and traversal. We should also think about how to mark the end of a word and how to handle cases where a prefix is not found.

Intuitive Analysis

Intuitively, solving this problem involves creating a mental map of how the trie data structure works. We can think of it like a game of word association, where each character in the string is linked to the next one, forming a path. When we insert a new string, we’re essentially creating a new path from the root to the final character. Searching for a string is like following a path to see if it exists. Checking for a prefix is similar, but we only need to follow the path until we reach the end of the prefix. The main intuition here is to understand how the trie structure allows us to efficiently explore these paths. We can imagine using a ’links’ array to store the child nodes, where each index corresponds to a character in the alphabet. This way, we can quickly traverse the trie and perform the required operations.

1. Intuition

2. Implementation


Complexity Analysis

Time Complexity:

Space Complexity:


Footnote

This question is rated as Medium difficulty.


Similar Questions:

Title URL Difficulty
Design Add and Search Words Data Structure https://leetcode.com/problems/design-add-and-search-words-data-structure Medium
Design Search Autocomplete System https://leetcode.com/problems/design-search-autocomplete-system Hard
Replace Words https://leetcode.com/problems/replace-words Medium
Implement Magic Dictionary https://leetcode.com/problems/implement-magic-dictionary Medium
Encrypt and Decrypt Strings https://leetcode.com/problems/encrypt-and-decrypt-strings Hard
Implement Trie II (Prefix Tree) https://leetcode.com/problems/implement-trie-ii-prefix-tree Medium
Count Prefix and Suffix Pairs II https://leetcode.com/problems/count-prefix-and-suffix-pairs-ii Hard
Count Prefix and Suffix Pairs I https://leetcode.com/problems/count-prefix-and-suffix-pairs-i Easy