What is a Trie (Prefix Tree), how do reTRIEval structures operate, and why is query time O(L) completely independent of dictionary key count n?
A Trie—derived from the word 'reTRIEval' by Edward Fredkin (1960) and pronounced either 'try' or 'tree'—is an ordered tree data structure utilized to store dynamic associative arrays or sets where keys are sequences (typically strings over an alphabet Σ or bitstrings over binary {0, 1}).
1. Structural Organization & Implicit Key Representation:
In standard comparison-based data structures (such as balanced Binary Search Trees, B-Trees, or Skip Lists), every node explicitly encapsulates a stored key. Searching for a key requires executing scalar comparisons between the query key and stored keys. Because each string comparison can inspect up to L characters, a BST containing n keys requires O(L · log n) time to find a key.
In stark contrast, a Trie organizes keys by their shared prefix structure:
- The Root Node represents the empty string prefix ϵ.
- Each Node maintains an array of child pointers `children[0 .. |Σ|-1]`, where each non-null pointer represents an edge labeled by a distinct character c ∈ Σ.
- Crucially, keys are NOT stored within nodes! The key associated with any node u is defined implicitly by the concatenated sequence of edge labels along the unique directed path from the root to node u.
- Nodes contain an auxiliary boolean attribute `is_terminal` (or a pointer to satellite user payload data). If `is_terminal == true`, the path from the root to that node represents a complete, valid dictionary key.
2. The Invariant O(L) Retrieval Complexity:
When searching for a query key K = (c₀, c₁, ..., c_{L-1}) of length L:
- The algorithm starts at the root.
- For each character c_i from i = 0 to L - 1, the algorithm reads the child pointer `current = current->children[c_i]`.
- If `current == NULL`, the prefix does not exist in the dictionary, and the search immediately terminates with failure.
- If all L characters are successfully traversed and `current->is_terminal == true`, the key is found successfully!
Notice the profound computational invariant: The search path length depends strictly on the length of the query string L. It does NOT depend on whether the dictionary contains 10 keys, 1,000,000 keys, or 100,000,000 keys! Search, insertion, and deletion all execute in guaranteed worst-case O(L) time. Furthermore, detecting whether a prefix exists in the dictionary terminates as soon as the prefix length is walked, making Tries the undisputed gold standard for Autocomplete, Spell Checking, and Predictive Text input engines.