what is a trie

what is a trie

1 year ago 71
Nature

A trie, also known as a digital tree or prefix tree, is a type of k-ary search tree used for storing and searching a specific key from a set. It is a tree data structure used for locating specific keys from within a set, where the keys are most often strings. The idea behind a trie is that all strings sharing a common prefix should come from a common node. Tries are used in spell checking programs, predictive text or autocomplete dictionaries, and approximate matching algorithms. They enable faster searches and occupy less space, especially when the set contains a large number of short strings.

A trie can be used to replace a hash table, and it has several advantages over a hash table. For example, searching for a node with an associated key of size has the complexity of O(key_length), whereas an imperfect hash function may have numerous colliding keys, and the worst-case lookup speed of such a table would be O(n), where n denotes the total number of nodes within the table. Tries do not need a hash function for the operation, unlike a hash table, and there are also no collisions of different keys in a trie.

Tries are constructed by creating a root node and adding child nodes for each character in the string being inserted. If the input key is new or an extension of the existing key, non-existing nodes of the key are constructed, and the end of the word is marked for the last node. If the input key is a prefix of the existing key in the trie, the last node of the key is simply marked as the end of a word. The key length determines the trie depth.

Tries have a time complexity of O(n) for insertion and searching, where n is the size of the string and the number of strings that are stored in the trie. The memory requirements of a trie are O(ALPHABET_SIZE * key_length * N), where N is the number of keys in the trie. There are efficient representations of trie nodes, such as compressed tries and ternary search trees, to minimize the memory requirements of the trie.

Read Entire Article