In computer science, a trie, also called digital tree or prefix tree, is a kind of search tree—an ordered tree data structure used to store a dynamic set or associative array where the keys are usually strings.
Implement a Basic Trie
Great trie explaination:
https://leetcode.com/problems/implement-trie-prefix-tree/solution/
1 | class TrieNode: |
Complexity
M is the length of the word
Insert
- time: O(M)
- space: O(M)
Search
- time: O(M)
- space: O(1)
Implement a Trie with Fuzzy Search
A great article here:
https://leetcode.com/problems/design-add-and-search-words-data-structure/solution/
1 | class TrieNode: |
Complexity
M is the length of the word
N is the number of keys in the trie
Insert
- time: O(M)
- space: O(M)
Search
- time: O(N * 26^M)
- space: O(M)
Each word has 26 char, for M length of searched word, need to search 26^M times.
to search all keys, time complexity is O(N * 26^M)
Double-Array Trie
If the trie is static and huge, use Double-Array Trie is very fast to save/load and very fast to lookup. But insert/remove can be costly.
https://linux.thai.net/~thep/datrie/
Reference:
https://en.wikipedia.org/wiki/Trie
https://leetcode.com/problems/implement-trie-prefix-tree/solution/
https://leetcode.com/problems/design-add-and-search-words-data-structure/solution/
https://stackoverflow.com/questions/18963783/build-trie-faster
https://linux.thai.net/~thep/datrie/
https://en.wikipedia.org/wiki/Deterministic_acyclic_finite_state_automaton