Leetcode 208. Implement Trie (Prefix Tree)
Implement a trie with insert
, search
, and startsWith
methods.
A trie (pronounced as “try”) or prefix tree is a tree data structure used to efficiently store and search a set of strings, where the keys are usually strings. The main operations of a trie are:
insert(string word)
: Inserts the string word
into the trie.search(string word)
: Returns true
if the string word
is in the trie (i.e., was inserted before), and false
otherwise.startsWith(string prefix)
: Returns true
if there is any string in the trie that starts with the given prefix
, and false
otherwise.Character Set: Do the strings only contain lowercase English letters?
Assumption: Yes, strings only contain ‘a’ to ‘z’.
Case Sensitivity: Are the strings case-sensitive?
Assumption: No, we can assume the strings are lowercase for simplicity.
Operations Frequency:
Will any operation (insert
, search
, startsWith
) be called more frequently than others?
Assumption: No specific operation is highlighted as being more frequent.
Each node in a Trie will contain:
true
.false
.true
.false
.true
.#include <iostream>
#include <vector>
using namespace std;
class TrieNode {
public:
bool isEndOfWord;
vector<TrieNode*> children;
TrieNode() : children(26, nullptr), isEndOfWord(false) {}
};
class Trie {
private:
TrieNode* root;
public:
Trie() {
root = new TrieNode();
}
void insert(string word) {
TrieNode* node = root;
for(char c : word) {
int index = c - 'a';
if (!node->children[index]) {
node->children[index] = new TrieNode();
}
node = node->children[index];
}
node->isEndOfWord = true;
}
bool search(string word) {
TrieNode* node = root;
for(char c : word) {
int index = c - 'a';
if (!node->children[index]) {
return false;
}
node = node->children[index];
}
return node != nullptr && node->isEndOfWord;
}
bool startsWith(string prefix) {
TrieNode* node = root;
for(char c : prefix) {
int index = c - 'a';
if (!node->children[index]) {
return false;
}
node = node->children[index];
}
return node != nullptr;
}
};
n
: The length of the word to be inserted.n
: The length of the word to be searched.n
: The length of the prefix.Given these complexities, the trie operations will be very efficient, particularly for string sets with a large number of common prefixes.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?