Problem description:

Implement a trie with insert, search, and startsWith methods.

Example:

1
2
3
4
5
6
7
8
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.

Solution:

Trie is an important data structure that frequently appeared in interviews. To design a TrieNode, we need a word collection child[26], which is from a-z, and a boolean value isWord that denotes whether this node is a word or not.

Insertion in trie

Searching in trie

Searching prefix in trie

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class TrieNode:
def __init__(self):
self.child = defaultdict(TrieNode)
self.is_word = False

class Trie:

def __init__(self):
self.root = TrieNode()

def insert(self, word: str) -> None:
p = self.root
for c in word:
p = p.child[c]
p.is_word = True

def search(self, word: str) -> bool:
p = self.root
for c in word:
if c not in p.child:
return False
else:
p = p.child[c]
return p.is_word

def startsWith(self, prefix: str) -> bool:
p = self.root
for c in prefix:
if c not in p.child:
return False
else:
p = p.child[c]
return True
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class TrieNode{
public:
TrieNode* child[26];
bool isWord;

TrieNode(): isWord(false){
for(auto &c: child)
c= NULL;
}
};

class Trie {
public:
/** Initialize your data structure here. */
TrieNode* root;
Trie() {
root= new TrieNode();
}

/** Inserts a word into the trie. */
void insert(string word) {
TrieNode* p= root;
for(auto a: word){
int i= a-'a';
if(!p->child[i])
p->child[i]= new TrieNode();

p= p->child[i];
}
p->isWord= true; //!!!!!!!!!!!!!! important!!!!
}

/** Returns if the word is in the trie. */
bool search(string key) {
TrieNode* p= root;
for(auto c: key){
int i= c- 'a';
if(!p->child[i]) return false;
p= p->child[i];
}
return p->isWord;
}

/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
TrieNode* p= root;
for(auto c: prefix){
int i= c- 'a';
if(!p->child[i]) return false;
p= p->child[i];
}
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);
*/

Insertion:
time complexity: $O(m)$, m is key length
space complexity: $O(m)$, m is key length

Search:
time complexity: $O(m)$, m is key length
space complexity: $O(1)$

Search prefix:
time complexity: $O(m)$, m is key length
space complexity: $O(1)

reference:
https://goo.gl/JjdfdH
https://goo.gl/oYnq3P
https://goo.gl/QvAJQx