Skip to content

Commit 4d500fd

Browse files
authored
Add trie data structure explanation (#229)
1 parent 6886024 commit 4d500fd

File tree

1 file changed

+158
-0
lines changed

1 file changed

+158
-0
lines changed

Diff for: en/Data Structures/Tries/trie.md

+158
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
# Trie
2+
3+
A trie (also called a prefix tree) is a tree data structure that shows order, linking parents to children. It is an efficient way of storing objects that have commonalities. A good example would be in storing phone numbers, or strings in general
4+
5+
For the strings example, supposing we have a list of strings to store in our data store
6+
7+
1. egg
8+
2. eat
9+
3. ear
10+
4. end
11+
12+
And one of the methods we are to support is a search operation for any of the words, we can approach it the basic way - select each word, and do a string comparison, matching letter to letter. The algorithm would be as follows:
13+
14+
15+
```
16+
## searching for ear in data store
17+
18+
data_store = ["egg", "eat", "ear", "end"]
19+
to_find = "ear"
20+
21+
## pick each word
22+
## do a string match letter by letter
23+
## when you find a mismatch, move to the next string
24+
## continue this process
25+
## if at the end of an iteration, index has been increased to
26+
## the length of the word to find, we have found a match
27+
28+
for word in data_store:
29+
index = 0
30+
while index < len(word):
31+
if to_find[index] != word[index]:
32+
break
33+
index += 1
34+
if index == len(to_find):
35+
print("a match has been found")
36+
37+
```
38+
39+
Without a doubt, this strategy will work, but the time complexity of doing this is *O(num of words x len of longest word)* which is quite expensive.
40+
However, if we represent the storage of numbers in a tree such that each letter appears only once in a particular level in the tree, we can achieve a much better search time. Take, for example, the tree below
41+
42+
```
43+
e
44+
/ | \
45+
a n g
46+
/ \ | |
47+
r t d g
48+
49+
```
50+
51+
You can see from the above representation, that all the words are in the tree, starting from the letter e, which is found at the beginning of all the words, then a, n, and g coming in the next level and so on...
52+
The above representation is called a trie.
53+
54+
# Standard Trie Operations
55+
56+
1) insert(): inserts the string into the trie.
57+
2) search(): searches for the string within the trie.
58+
59+
# Building a Trie
60+
61+
## Defining a node class for the elements of the trie
62+
63+
To start building a trie, you first need to define a node with the revelant attributes needed for any trie.
64+
65+
```
66+
class Node:
67+
def __init__(self, is_word: bool=False):
68+
self.is_word = is_word
69+
self.children = {}
70+
```
71+
72+
Here, you can see that the class `Node` has three instance attributes:
73+
1. is_word: *bool* = to mark whether that node in the trie marks the completion of a word
74+
2. children: *Dict* = to hold pointers to other children nodes
75+
76+
Then the trie gets built by creating a node for each letter and adding it as a child to the node before it
77+
78+
## Building the trie itself
79+
80+
Start by initializing an empty node
81+
82+
```
83+
class Trie:
84+
def __init__(self):
85+
self.node = Node()
86+
```
87+
88+
For the insert operation, fetch the starting node, then for every letter in the word, add it to the children of the letter before it. The final node has its `is_word` attribute marked as **True** because we want to be aware of where the word ends
89+
90+
```
91+
def insert(self, word: str) -> None:
92+
node = self.node
93+
for ltr in word:
94+
if ltr not in node.children:
95+
node.children[ltr] = Node()
96+
node = node.children[ltr]
97+
node.is_word=True
98+
```
99+
100+
*In the code above, the `node` variable starts by holding a reference to the null node, while the `ltr` iterating variable starts by holding the first letter in `word`. This would ensure that `node` is one level ahead of `ltr`. As they are both moved forward in the iterations, `node` will always remain one level ahead of `ltr`*
101+
102+
For the search operation, fetch the starting node, then for every letter in the word, check if it is present in the `children` attribute of the current node. As long as it is present, repeat for the next letter and next node. If during the search process, we find a letter that is not present, then the word does not exist in the trie. If we successfully get to the end of the iteration, then we have found what we are looking for. It is time to return a value
103+
104+
Take a look at the code
105+
106+
```
107+
def search(self, word: str) -> bool:
108+
node = self.node
109+
for ltr in word:
110+
if ltr not in node.children:
111+
return False
112+
node = node.children[ltr]
113+
return node.is_word
114+
```
115+
116+
For the return value, there are two cases:
117+
1. we are searching for a word -> return `node.is_word` because we want to be sure it is actually a word, and not a prefix
118+
2. we are searching for a prefix -> return **True** because whether it is a word or not, it is prefix that exists in the trie
119+
120+
Now here is the full code
121+
122+
```
123+
class Node:
124+
def __init__(self, is_word: bool=False):
125+
self.is_word = is_word
126+
self.children = {}
127+
128+
class Trie:
129+
130+
def __init__(self):
131+
self.node = Node()
132+
133+
134+
def insert(self, word: str) -> None:
135+
node = self.node
136+
for ltr in word:
137+
if ltr not in node.children:
138+
node.children[ltr] = Node()
139+
node = node.children[ltr]
140+
node.is_word=True
141+
142+
143+
def search(self, word: str) -> bool:
144+
node = self.node
145+
for ltr in word:
146+
if ltr not in node.children:
147+
return False
148+
node = node.children[ltr]
149+
return node.is_word
150+
```
151+
152+
# Helpful links
153+
154+
1) [Trie Data Structure - GeeksForGeeks](https://www.geeksforgeeks.org/trie-insert-and-search/)
155+
156+
# Video Playlist
157+
158+
- [Trie Data Structure](https://www.youtube.com/watch?v=zIjfhVPRZCg)

0 commit comments

Comments
 (0)