Trie is a kind of digital search tree. (See[Knuth1972] for the detail of digital search tree.)[Fredkin1960] introduced the trieterminology, which is abbreviated from "Retrieval".
Trie is an efficient indexing method. It is indeed also a kind ofdeterministic finite automaton (DFA) (See [Cohen1990],for example, for the definition of DFA). Within the tree structure, each nodecorresponds to a DFA state, each (directed) labeled edge from a parent node toa child node corresponds to a DFA transition. The traversal starts at the rootnode. Then, from head to tail, one by one character in the key string is takento determine the next state to go. The edge labeled with the same character ischosen to walk. Notice that each step of such walking consumes one characterfrom the key and descends one step down the tree. If the key is exhausted anda leaf node is reached, then we arrive at the exit for that key. If we getstuck at some node, either because there is no branch labeled with the currentcharacter we have or because the key is exhausted at an internal node, thenit simply implies that the key is not recognized by the trie.
Notice that the time needed to traverse from the root to the leaf is notdependent on the size of the database, but is proportional to the length ofthe key. Therefore, it is usually much faster than B-tree or anycomparison-based indexing method in general cases. Its time complexity iscomparable with hashing techniques.
In addition to the efficiency, trie also provides flexibility in searchingfor the closest path in case that the key is misspelled. For example, byskipping a certain character in the key while walking, we can fix the insertionkind of typo. By walking toward all the immediate children of one node withoutconsuming a character from the key, we can fix the deletion typo, or evensubstitution typo if we just drop the key character that has no branch to goand descend to all the immediate children of the current node.
In general, a DFA is represented with a transition table, inwhich the rows correspond to the states, and the columns correspond to thetransition labels. The data kept in each cell is then the next state to go fora given state when the input is equal to the label.
This is an efficient method for the traversal, because every transitioncan be calculated by two-dimensional array indexing. However, in term of spaceusage, this is rather extravagant, because, in the case of trie, most nodeshave only a few branches, leaving the majority of the table cells blanks.
Meanwhile, a more compact scheme is to use a linked list to store thetransitions out of each state. But this results in slower access, due tothe linear search.
Hence, table compression techniques which still allows fast access havebeen devised to solve the problem.
As explained in [Aho+1985] pp. 144-146, a DFAcompression could be done using four linear arrays, namely default,base, next, and check. However, ina case simpler than the lexical analyzer, such as the mere trie for informationretrieval, the default array could be omitted. Thus, a triecan be implemented using three arrays according to this scheme.
The tripple-array structure is composed of:
Definition 1. For a transition from state s tot which takes character c as the input, the conditionmaintained in the tripple-array trie is:
check[ base[ s] + c] = s
next[ base[ s] + c] = t
According to definition 1, the walking algorithm for agiven state s and the input character c is:
To insert a transition that takes character c to traversefrom a state s to another state t, the cellnext[base[s] + c]]must be managed to be available. If it is already vacant, we are lucky.Otherwise, either the entire transition vector for the current owner of thecell or that of the state s itself must be relocated. Theestimated cost for each case could determine which one to move. After findingthe free slots to place the vector, the transition vector must berecalculated as follows. Assuming the new place begins at b,the procedure for the relocation is:
The tripple-array structure for implementing trie appears to be well defined,but is still not practical to keep in a single file. Thenext/checkpool may be able to keep in a single array of integer couples, but thebase array does not grow in parallel to the pool, and is thereforeusually split.
To solve this problem, [Aoe1989] reduced thestructure into two parallel arrays. In the double-array structure, thebase and next are merged, resulting in only twoparallel arrays, namely, base and check.
Instead of indirectly referencing through state numbers asin tripple-array trie, nodes in double-array trie are linked directly withinthe base/check pool.
Definition 2. For a transition from state s tot which takes character c as the input, the conditionmaintained in the double-array trie is:
check[ base[ s] + c] = s
base[ s] + c = t
According to definition 2, the walking algorithm for agiven state s and the input character c is:
The construction of double-array trie is in principle the same as that oftripple-array trie. The difference is the base relocation:
[Aoe1989] also suggested a storage compressionstrategy, by splitting non-branching suffixes into single string storages,called tail, so that the rest non-branching steps are reducedinto mere string comparison.
With the two separate data structures, double-array branches and suffix-spool tail, key insertion and deletion algorithms must be modifiedaccordingly.
To insert a new key, the branching position can be found by traversing thetrie with the key one by one character until it gets stuck. The state wherethere is no branch to go is the very place to insert a new edge, labeled bythe failing character. However, with the branch-tail structure, the insertionpoint can be either in the branch or in the tail.
Suppose that the new key is a stringa1a2...ah-1ahah+1...an,wherea1a2...ah-1traverses the trie from the root to a node sr in the double-arraystructure, and there is no edge labeled ah that goes out ofsr. The algorithm called A_INSERT in[Aoe1989] does as follows:
Since the path through a tail string has no branch, and therefore correspondsto exactly one key, suppose that the key corresponding to the tail is
a1a2...ah-1ah...ah+k-1b1...bm,
wherea1a2...ah-1 is in double-array structure, andah...ah+k-1b1...bm is in tail.Suppose that the substringa1a2...ah-1 traverses the trie from the rootto a node sr.
And suppose that the new key is in the form
a1a2...ah-1ah...ah+k-1ah+k...an,
where ah+k <> b1. The algorithm calledB_INSERT in [Aoe1989] does as follows:
To delete a key from the trie, all we need to do is delete the tail blockoccupied by the key, and all double-array nodes belonging exclusively to the key, without touching any node belonging to other keys.
Consider a trie which accepts a language K = {pool#, prepare#, preview#,prize#, produce#, producer#, progress#} :
The key "pool#" can be deleted by removing the tail string "ol#" from thetail pool, and node 3 from the double-array structure. This is the simplestcase.
To remove the key "produce#", it is sufficient to delete node 14 from thedouble-array structure. But the resulting trie will not obay the conventionthat every node in the double-array structure, except the separate nodes whichpoint to tail blocks, must belong to more than one key. The path from node 10on will belong solely to the key "producer#".
But there is no harm violating this rule. The only drawback is theuncompactnesss of the trie. Traversal, insertion and deletion algoritms areintact. Therefore, this should be relaxed, for the sake of simplicity andefficiency of the deletion algorithm. Otherwise, there must be extra stepsto examine other keys in the same subtree ("producer#" for the deletion of"produce#") if any node needs to be moved from the double-array structure totail pool.
Suppose further that having removed "produce#" as such (by removing onlynode 14), we also need to remove "producer#" from the trie. What we have to dois remove string "#" from tail, and remove nodes 15, 13, 12, 11, 10 (which nowbelong solely to the key "producer#") from the double-array structure.
We can thus summarize the algorithm to delete a keyk = a1a2...ah-1ah...an,where a1a2...ah-1 is in double-array structure,and ah...an is in tail pool, as follows :
Where outdegree(s) is the number of children nodesof s.
When inserting a new branch for a node, it is possible that the array elementfor the new branch has already been allocated to another node. In that case,relocation is needed. The efficiency-critical part then turns out to be thesearch for a new place. A brute force algoritm iterates along thecheck array to find an empty cell to place the first branch, andthen assure that there are empty cells for all other branches as well.The time used is therefore proportional to the size of the double-array pooland the size of the alphabet.
Suppose that there are n nodes in the trie, and the alphabet isof size m. The size of the double-array structure would ben + cm, where c is a coefficient whichis dependent on the characteristic of the trie. And the time complexity ofthe brute force algorithm would beO(nm + cm2).
[Aoe1989] proposed a free-space list in thedouble-array structure to make the time complexity independent of the sizeof the trie, but dependent on the number of the free cells only. The check array for the free cells are redefined to keep a pointerto the next free cell (called G-link) :
Definition 3. Let r1, r2, ... ,rcm be the free cells in the double-array structure, orderedby position. G-link is defined as follows :
check[0] = -r 1
check[r i] = -r i+1 ; 1 <= i <= cm-1
check[r cm] = -1
By this definition, negative check means unoccupied in the samesense as that for "none" check in the ordinary algorithm. Thisencoding scheme forms a singly-linked list of free cells. When searching for anempty cell, only cm free cells are visited, instead of alln + cm cells as in the brute force algorithm.
This, however, can still be improved. Notice that for those cells withnegative check, the corresponding base's are notgiven any definition. Therefore, in our implementation, Aoe's G-link ismodified to be doubly-linked list by letting base of every freecell points to a previous free cell. This can speed up the insertion anddeletion processes. And, for convenience in referencing the list head and tail,we let the list be circular. The zeroth node is dedicated to be the entry pointof the list. And the root node of the trie will begin with cell number one.
Definition 4. Let r1, r2, ... ,rcm be the free cells in the double-array structure, orderedby position. G-link is defined as follows :
check[0] = -r 1
check[r i] = -r i+1 ; 1 <= i <= cm-1
check[r cm] = 0
base[0] = -r cm
base[r 1] = 0
base[r i+1] = -r i ; 1 <= i <= cm-1
Then, the searching for the slots for a node with input symbol setP = {c1, c2, ..., cp} needs to iterate onlythe cells with negative check :
The time complexity for free slot searching is reduced toO(cm2). The relocation stage takes O(m2). The total time complexity is thereforeO(cm2 + m2) = O(cm2).
It is useful to keep the free list ordered by position, so that the accessthrough the array becomes more sequential. This would be beneficial when thetrie is stored in a disk file or virtual memory, because the disk caching orpage swapping would be used more efficiently. So, the free cell reusingshould maintain this strategy :
Time complexity of freeing a cell is thus O(cm).
In my implementation, I designed the API with persistent data in mind.Tries can be saved to disk and loaded for use afterward. And in newer versions,non-persistent usage is also possible. You can create a trie in memory, populate data to it, use it, and free it, without any disk I/O. Alternativelyyou can load a trie from disk and save it to disk whenever you want.
The trie data is portable across platforms. The byte order in the disk isalways little-endian, and is read correctly on either little-endian or big-endian systems.
Trie index is 32-bit signed integer. This allows 2,147,483,646 (231 - 2) total nodes in the trie data, which should be sufficientfor most problem domains. And each data entry can store a 32-bit integer valueassociated to it. This value can be used for any purpose, up to your needs.If you don't need to use it, just store some dummy value.
For sparse data compactness, the trie alphabet set should be continuous,but that is usually not the case in general character sets. Therefore, a mapbetween the input character and the low-level alphabet set for the trie iscreated in the middle. You will have to define your input character set bylisting their continuous ranges of character codes in a .abm (alphabet map)file when creating a trie. Then, each character will be automatically assignedinternal codes of continuous values.
Update: The double-array trie implementation has been simplified and rewritten from scratch in C, and is now named libdatrie. It is now available under the terms ofGNU Lesser General PublicLicense (LGPL):
SVN: svn co http://linux.thai.net/svn/software/datrie
The old C++ source code below is under the terms ofGNU Lesser General PublicLicense (LGPL):
Copyright © 1999 by Theppitak Karoonboonyanan, Software and Language Engineering Laboratory, National Electronics and Computer Technology Center. All rights reserved.
Copyright © 2003-2010 by Theppitak Karoonboonyanan. All rights reserved.