-
-
Notifications
You must be signed in to change notification settings - Fork 776
Add trie datastructure #229
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
appgurueu
merged 14 commits into
TheAlgorithms:master
from
Xceptions:add-trie-datastructure
Feb 28, 2024
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
1061992
started adding tries doc
Xceptions 07d9617
added standard trie operations
Xceptions 1d07b73
added trie documentation
Xceptions ed0f5c4
added trie documentation - fixed some type
Xceptions 9930447
removed gitignore and env file- fixed a small typo in trie file
Xceptions 9192bb2
removed gitignore
Xceptions 5e179b4
fixed the isword => is_word typo
Xceptions 89fcab0
removed the 'ignore the return value statement'
Xceptions a132ca6
updated the code to remove redundant val attribute, also updated ever…
Xceptions f72b02b
updated line 61 to say defining a node class rather than building a node
Xceptions ff6ddc4
added linking sentence to line 40 to make it more coherent with line 51
Xceptions 197d0a1
corrected the name tries.md to trie.md to match convention
Xceptions ac30856
removed tries.md
Xceptions 752e521
Merge branch 'master' into add-trie-datastructure
Xceptions File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,158 @@ | ||
# Trie | ||
|
||
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 | ||
|
||
For the strings example, supposing we have a list of strings to store in our data store | ||
|
||
1. egg | ||
2. eat | ||
3. ear | ||
4. end | ||
|
||
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: | ||
|
||
|
||
``` | ||
## searching for ear in data store | ||
|
||
data_store = ["egg", "eat", "ear", "end"] | ||
to_find = "ear" | ||
|
||
## pick each word | ||
## do a string match letter by letter | ||
## when you find a mismatch, move to the next string | ||
## continue this process | ||
## if at the end of an iteration, index has been increased to | ||
## the length of the word to find, we have found a match | ||
|
||
for word in data_store: | ||
index = 0 | ||
while index < len(word): | ||
if to_find[index] != word[index]: | ||
break | ||
index += 1 | ||
if index == len(to_find): | ||
print("a match has been found") | ||
|
||
``` | ||
|
||
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. | ||
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 | ||
|
||
``` | ||
e | ||
/ | \ | ||
a n g | ||
/ \ | | | ||
r t d g | ||
|
||
``` | ||
|
||
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... | ||
The above representation is called a trie. | ||
|
||
# Standard Trie Operations | ||
|
||
1) insert(): inserts the string into the trie. | ||
2) search(): searches for the string within the trie. | ||
|
||
# Building a Trie | ||
|
||
## Defining a node class for the elements of the trie | ||
|
||
To start building a trie, you first need to define a node with the revelant attributes needed for any trie. | ||
|
||
``` | ||
class Node: | ||
def __init__(self, is_word: bool=False): | ||
self.is_word = is_word | ||
Xceptions marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self.children = {} | ||
``` | ||
|
||
Here, you can see that the class `Node` has three instance attributes: | ||
1. is_word: *bool* = to mark whether that node in the trie marks the completion of a word | ||
2. children: *Dict* = to hold pointers to other children nodes | ||
|
||
Then the trie gets built by creating a node for each letter and adding it as a child to the node before it | ||
|
||
## Building the trie itself | ||
|
||
Start by initializing an empty node | ||
|
||
``` | ||
class Trie: | ||
def __init__(self): | ||
self.node = Node() | ||
``` | ||
|
||
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 | ||
|
||
``` | ||
def insert(self, word: str) -> None: | ||
node = self.node | ||
for ltr in word: | ||
if ltr not in node.children: | ||
node.children[ltr] = Node() | ||
node = node.children[ltr] | ||
node.is_word=True | ||
``` | ||
|
||
*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`* | ||
|
||
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 | ||
|
||
Take a look at the code | ||
|
||
``` | ||
def search(self, word: str) -> bool: | ||
node = self.node | ||
for ltr in word: | ||
if ltr not in node.children: | ||
return False | ||
node = node.children[ltr] | ||
return node.is_word | ||
``` | ||
|
||
For the return value, there are two cases: | ||
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 | ||
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 | ||
|
||
Now here is the full code | ||
|
||
``` | ||
class Node: | ||
def __init__(self, is_word: bool=False): | ||
self.is_word = is_word | ||
self.children = {} | ||
|
||
class Trie: | ||
|
||
def __init__(self): | ||
self.node = Node() | ||
|
||
|
||
def insert(self, word: str) -> None: | ||
node = self.node | ||
for ltr in word: | ||
if ltr not in node.children: | ||
node.children[ltr] = Node() | ||
node = node.children[ltr] | ||
node.is_word=True | ||
|
||
|
||
def search(self, word: str) -> bool: | ||
node = self.node | ||
for ltr in word: | ||
if ltr not in node.children: | ||
return False | ||
node = node.children[ltr] | ||
return node.is_word | ||
``` | ||
|
||
# Helpful links | ||
|
||
1) [Trie Data Structure - GeeksForGeeks](https://www.geeksforgeeks.org/trie-insert-and-search/) | ||
|
||
# Video Playlist | ||
|
||
- [Trie Data Structure](https://www.youtube.com/watch?v=zIjfhVPRZCg) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.