Trie
Trie (Prefix Tree)
1. Introduction
Trie (Prefix Tree) is a useful data structure for storing prefix of strings and retrieval of string based on prefix
2. Implementation
3. Time & Space Complexity
insert(): O(L), where L is the length of word to be inserted
search(): O(L)
Space: O(size^L), size is the number of childeNode for each trie node. Normally, we define size as 26 if we only store alphabetical letters. Sometimes we may define size as 256 if we assume input is ASCII
4. Thoughts
Trie VS HashMap: Trie will be space efficient to solve store things that have common prefixes (e.g SSN, phone number), while lots of hash collisions will happen as hashMap increases in size.
By changing the structure of trieNode a little bit, we can use trie to do things like Google Suggestion (Add a minHeap to node), AutoComplete(Add a HashSet or List of Strings with the prefix), etc
Trie can also solve suffix problem (Distinct Substring)
5. Interview Questions
Last updated