A Trie (derived from retrieval), also known as a Prefix Tree, is a specialized tree-like data structure used primarily to store an associative array or dynamic set where the keys are usually strings.
Unlike a binary search tree, no node in the tree stores the key associated with that node; instead, its position in the tree defines the key with which it is associated. All the descendants of a node have a common prefix of the string associated with that node, and the root is associated with the empty string.
isEndOfWord = true).isEndOfWord flag is true, the word exists. If at any point the next character is missing, the word does not exist.isEndOfWord flag at the end.Let L be the length of the word being inserted, searched, or prefixed, and N be the number of words in the Trie.
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| Insert | O(L) | O(L) |
| Search | O(L) | O(1) |
| Prefix | O(L) | O(1) |
While Hash Maps also provide O(1) or O(L) string lookups, Tries excel when you need to perform prefix searches or find all words with a common prefix. Hash maps cannot efficiently return "all words starting with 'app'". Furthermore, Tries can be more space-efficient than Hash Maps when storing many words sharing the same prefix.
What is the time complexity of inserting a word of length L into a Trie?