Trie from the word Retrieve
- A data structure, it is a tree and a search tree.
Introduction
Search Trees
- Usually ordered data structure
- search for some kind of “keys”
Example of Search Tree we are already very familiar: Binary Search Tree
- the keys are associsated with each node in the tree
- the keys can be any comparable type
- main the order of the keys by topological property(leftsubtree < root < rightsubtree)
Design a Dictionary
n - # of words
m - length of the string/word
- What is the requirement of this dictionary?
- search(word)
- delete
- add
- find all words with give prefix
- Options of data structures
- Hash Map
- Balanced BST
- ArrayList(sorted)
Time
- Looking up data in a trie is faster in the worst case, O(m) time (where m is the length of a search string)
- hashmap, remember we may need to calculate the hashCode() and compare eaquals, that is O(m).
- Array List (sorted) - O(logn) * O(m)
- Binary Search Tree - O(logn) * O(m)
DrawBack: if stored on disk, more random disk accesses (very expensive)
Space
- if the tire is not too sparse, since reusing the common prefix as many as possible, less space required. worst case O(nm), but usually much better than this.
DrawBack:
- Every TrieNode has extra space comsumption -> extra space usage
- memory allocation fragmentation, especially when the trie is sparse.
Use Case
- String or sequence typed elements
- fast worst search/add/delete
- grouping common prefix, both for time/space efficency
- problems related to prefix/matching
208. Implement Trie (Prefix Tree)
- Node <val, children>
TODO: delete!!!!
1 | class Node(object): |
211. Add and Search Word - Data structure design
1 | class TrieNode(object): |