Skip to main content

Implement Trie

Problem Statement​

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:

  1. Trie() Initializes the trie object.

  2. void insert(String word) Inserts the string word into the trie.

  3. boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.

  4. 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

Solutions​

A Trie prefix tree is a tree data structure which is used to store the strings. Each node in the Trie represents a character of the string and stores the boolean value to indicate whether it is the end of a word. The Trie tree is used to find all the possible words by traversing all the nodes of the tree. Insertion in the Trie tree is performed by iterating each character of the string and checking if the character is already present in the Trie tree. If it is present, then move to the corresponding node of that character, otherwise create a new node and connect it with the Trie tree.

Written by @Ajay-Dhangar
#include <iostream>
#include <string>

class TrieNode {
public:
TrieNode *child[26];
bool isWord;
TrieNode() {
isWord = false;
for (auto &a : child) a = nullptr;
}
};

class Trie {
TrieNode* root;
public:
Trie() {
root = new TrieNode();
}
void insert(std::string s) {
TrieNode *p = root;
for (auto &a : s) {
int i = a - 'a';
if (!p->child[i]) p->child[i] = new TrieNode();
p = p->child[i];
}
p->isWord = true;
}
bool search(std::string key, bool prefix=false) {
TrieNode *p = root;
for (auto &a : key) {
int i = a - 'a';
if (!p->child[i]) return false;
p = p->child[i];
}
if (prefix == false) return p->isWord;
return true;
}
bool startsWith(std::string prefix) {
return search(prefix, true);
}
};

// Driver code
int main() {
Trie trie;
trie.insert("apple");
std::cout << trie.search("apple") << "\n"; // returns true
std::cout << trie.search("app") << "\n"; // returns false
std::cout << trie.startsWith("app") << "\n"; // returns true
trie.insert("app");
std::cout << trie.search("app") << "\n"; // returns true
return 0;
}

Video Lecture:​