Intro
Trie is a tree-like data structure for storing sequences of tokens (characters, permutations of digits or shapes, etc.) where:
“”)dictionary in Python, a fixed array in other languages with the size of the alphabet)is_end) to mark that a complete word ends hereBitwise Trie uses individual bits from fixed-length binary data, such as integers or memory addresses, as keys
Usage
Comparison
Advantages
Disadvantages
usually space inefficient (rarely save space when compared to storing strings in a set)
ASCII characters in a string = 1 byte each
link between trie nodes = pointer to an address = 8 bytes on a 64-bit system
⇒ the overhead of linking nodes together often outweighs the savings from storing fewer characters
not standard, has to be implemented manually
Problems
Corner Cases
Implementation
Trie
insert(word)
remove(word)
isPrefix() - returns true if any word in the Trie begins with the given prefix
isWord(word) - returns true if the given word is present in the Trie
getWordWithPrefix(prefix) - return any word in the Trie that begins with the given prefix
getWordsWithPrefix(prefix) - return all words in the Trie that begin with the given prefix
getTotalWordsWithPrefix(prefix) - return the number of words in the Trie that begin with given prefix
getTotalWords() - return the number of words in the Trie
| Time Complexity | |
|---|---|
| Operations | Worst case |
| create() | O(l*n) |
| insert(word) | O(m*n) |
| remove(word) | O(m*n) |
| isPrefix() | |
| isWord(word) | O(m*n) |
| getWordWithPrefix(prefix) | |
| getWordsWithPrefix(prefix) | |
| getTotalWordsWithPrefix(prefix) | |
| getTotalWords() |
| Space Complexity | |
|---|---|
| Implementation | Worst case |
| Trie | O(n) |
l is the length of the longest string in the Trie
m is the length of the average string used in the operation
n is the number of words in the Trie
alphabet_size
Algorithms
Patterns
Code
Resources
void insert(String key)
Function to insert a key in the trie.
Inserts the string key into the trie.
Every character of the input key is inserted as an individual Trie node.
Note that the children is an array of pointers (or references) to next level trie nodes. The key character acts as an index to the array children.
If the input key is new or an extension of the existing key, we need to construct non-existing nodes of the key, and mark the end of the word for the last node.
If the input key is a prefix of the existing key in Trie, we simply mark the last node of the key as the end of a word.
The key length determines Trie depth.
void remove(String key)
Function to delete a key in the trie.
During delete operation we delete the key in bottom-up manner using recursion. The following are possible conditions when deleting key from trie: