Data structureadvanced
Packed trie
Also called Liang packed trie.
A trie whose node arrays are overlapped in one table by first fit, so that sparse nodes share space and lookup stays one index per character.
- Implements
- String symbol table
- Time
- O(m) worst
- Space
- Θ(S) extra
- Where
- F = the number of families (nodes with children); S = the number of slots of the table; m = the length of the key; sigma = the size of the alphabet
- Model
- Word RAM
- Properties
- not concurrentnot externalnot persistent
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Franklin Mark Liang, 1983
A packed trie stores an indexed trie in one table. In an indexed trie every node with children (a family) has an array with one slot per letter, and most slots are empty. The packed trie gives each family a base and puts its transition on the letter at slot of a shared table, so that the families fill each other's holes. Each slot also stores its letter, and no two families get the same base, so a lookup can tell its own transitions from the others. Franklin Liang designed it in 1983 to hold the hyphenation patterns of TeX82, and a lookup costs one table index per letter, as in the full indexed trie.
In plain words
A trie node for a word list usually has only a few of the 26 possible children. Giving it a full row of 26 slots wastes most of them. A packed trie slides all the rows over one long table, like combs with missing teeth pushed into each other, so that the teeth of one row fall into the gaps of the others.
To read a child, go to the row's start plus the letter's number. The slot there may belong to another row. So each slot also keeps its letter: if the letter matches, the slot is yours, because two rows never start at the same place. The rows are placed one at a time, each at the first place where it fits.
The abstract type
A packed trie is a static map from nonempty strings to values: a string symbol table without insertions after the build. It supports:
build(D): the table for a finite map ;get(x): the value , or nothing if is not a key;prefix_values(t, i): the keys that are prefixes of , with their values, which is the walk of Liang's hyphenation at one start position.
Representation
Give the letters the codes . The table has slots, and slot holds three fields:
- : the letter of the transition in this slot, or empty;
- : the base of the family of the child, or nil if the child has no children;
- : the value of the key that ends with this transition, or nil.
The root has a base . The invariant:
- (I1) the families have distinct bases;
- (I2) each slot holds the transition of at most one family;
- (I3) the transition of the family with base on the letter is in slot , with and the right link and output.
In TeX82 a transition takes 4 bytes, for the letter, the link and an index into a separate table of digit lists. TeX82 also merges equal subtries before packing (suffix compression), so a family can have several parents.
Operations
SLOT(b, c) ▷ the slot of the transition on c, or nil- 1
s ← b + code(c) - 2
if s < S and char[s] = c then return s - 3
return nil GET(x)- 4
b ← β0; for each letter c of x do - 5
s ← SLOT(b, c) - 6
if s = nil then return nil ▷ no key has this prefix - 7
b ← link[s] - 8
return out[s] FIRST-FIT(C) ▷ C: the codes of the letters of one family- 9
b ← 0 - 10
loop - 11
if b is not a base yet and slot b + a is empty for every a in C then - 12
return b - 13
b ← b + 1 BUILD(D) ▷ the trie of D is built first- 14
for each family φ in breadth-first order do - 15
b ← FIRST-FIT(the codes of the letters of φ) - 16
mark b as a base - 17
for each child of φ on a letter c do - 18
char[b + code(c)] ← c; out[b + code(c)] ← the value of the child, if any - 19
queue the child if it has children - 20
link[the slot of φ in its parent] ← b (or β0 ← b for the root)
Lookup (lines L1 to L8). One step reads one slot and compares one letter, so get(x) takes time. Line L2 is the ownership test: if the letter matches, the slot belongs to the current family, by (I1). prefix_values is the same walk, and it reports at each step where it is not nil.
Build (lines L9 to L20). Line L11 accepts a base when no other family uses it and all the slots the family needs are free. Slots past the end of the table count as free, and the table grows. A plain scan from 0, as here, costs per family in the worst case, so in all. Faster builds keep a list of the free slots and try only the bases that put the first letter of the family on a free slot. First fit is a heuristic: it does not promise the smallest table.
Example
Pack the nine patterns of TeXbook Appendix H as keys: hyph, hen, hena, henat, na, nat, tio, io and on. The letters are a, e, h, i, n, o, p, t, y with codes 1 to 9. The trie has 13 families and 18 transitions. In breadth-first order, first fit places them as follows:
| family | letters (codes) | base | slots used |
|---|---|---|---|
| root | h i n o t (3 4 5 6 8) | 0 | 3 4 5 6 8 |
| h | e y (2 9) | 5 | 7 14 |
| i | o (6) | 3 | 9 |
| n | a (1) | 1 | 2 |
| o | n (5) | 6 | 11 |
| t | i (4) | 8 | 12 |
| he | n (5) | 10 | 15 |
| hy | p (7) | 9 | 16 |
| na | t (8) | 2 | 10 |
| ti | o (6) | 7 | 13 |
| hen | a (1) | 16 | 17 |
| hyp | h (3) | 15 | 18 |
| hena | t (8) | 11 | 19 |
For the family "h", the bases 0 to 4 fail: base 0 is taken, and the bases 1 to 4 put e on one of the full slots 3 to 6. Base 5 puts e on slot 7 and y on slot 14, both free. The family "hen" needs one slot only, but every base from 0 to 15 is taken or puts a on a full slot, so it goes to 16. The table has 20 slots, of which 18 hold a transition (slots 0 and 1 stay empty), so the density is 0.9. An unpacked indexed trie needs slots.
Two lookups:
get("hen"): from base 0, h is slot 3 (char h, link 5); e is slot (char e, link 10); n is slot (char n, out he2n). Found.get("ho"): h is slot 3, link 5; o is slot , which holds n, the transition of the family "o". The letter does not match, so "ho" is not a prefix of any key.
Correctness
The build keeps (I1) to (I3): FIRST-FIT returns a base that is free and whose slots are free, line L16 marks the base, and lines L17 to L20 fill only those slots and the link of the parent. For the lookup: if the current family has a child on , slot holds by (I3). If it has none but the slot holds , the slot belongs to a family with , so and by (I1), a contradiction. So line L2 accepts exactly the transitions of the current family, and by induction on the letters get follows the path of in the trie. The full proof is in the proof file.
Proof: Lookup in a packed trie is correct when the letter is stored and bases are distinctfull
Claim. Let be a finite map from nonempty strings over an alphabet to values, with codes that are distinct for distinct letters. Build the packed trie with lines L9 to L20. Then the build stops, and afterwards, for every string , get(x) (lines L1 to L8) returns if is a key and the default otherwise. Also prefix_values(text, i) yields exactly the pairs for the keys that are prefixes of , in increasing order of .
Setup. Let be the trie of the keys: a node for each prefix of a key, the root for the empty string. A family is a node of with at least one child, and its transitions are the edges to its children. The build gives each family a base , and puts its transition on the letter in the slot , with , the value of the child if the child is a key, and the base of the child if the child is a family.
Invariant of the build. After each family is placed (lines L16 to L20):
- (I1) the bases of the placed families are distinct;
- (I2) every slot holds the transition of at most one placed family, and a slot with None holds exactly one;
- (I3) the slot of a placed family holds , the correct , and, once the child is placed, the correct .
Initialization. Before the first family nothing is placed and all slots are free.
Maintenance. Lines L9 to L13 return the least with not in the set of taken bases and with every slot , for the letters of the new family, free. Such a exists: any larger than every taken base and the current table length qualifies, so the search stops. Line L16 adds to the taken bases, which keeps (I1). The slots that lines L17 and L18 fill were free, and distinct letters have distinct codes, so (I2) is kept. Line L18 writes the letter and the output of each transition. The child families are queued (line L19) and placed later; when a child is placed, line L20 writes its base into the parent slot, which nothing else writes. So (I3) holds.
Termination of the build. The queue holds each family once (each node is queued only by its parent), there are finitely many, and each first-fit search stops.
Lemma (one step). Let be a family and a letter. Then _slot returns the slot of the transition of on if has a child on , and None otherwise.
Proof. If has a child on , its slot holds by (I3), so lines L1 and L2 return . Assume now that has no child on but line L2 finds . By (I2) the slot holds the transition of some placed family on some letter , with by (I3). So and , which gives . By (I1), , so has a child on , a contradiction. Hence line L3 returns None. (If the letter is not in the alphabet, or the base is None because the current node has no children, the code returns None at once, which is also correct.)
Proof of the claim. For get, show by induction on that after letters of the loop of line L4 is still running exactly when is a node of , and then is the slot of the edge into that node and base is its base if the node is a family, or None. For , base is the base of the root. In the step, by the lemma, line L5 finds the slot of the edge on exactly when the node for exists; otherwise line L6 returns the default, which is right because no key has this prefix. Line L7 reads the base of the child from (I3). After the last letter, is a node of , and is its value if it is a key and None otherwise, by (I3). Values are never None, so line L8 returns or the default exactly as claimed. prefix_values runs the same walk from position and reports at each step where it is not None, so it yields the keys that are prefixes of , shortest first, and stops when the walk leaves .
Termination of a lookup. Each step reads one letter, so get(x) takes at most steps and each step reads slots.
Why both checks are needed. Without the stored letter, a slot of another family could be read as a transition. Without distinct bases, two families with the same base and disjoint letters could both be placed, and a lookup from one would accept the letters of the other: the stored letter matches, but it is not the letter of the right family. The proof uses (I1) at exactly this point.
Complexity
| operation | time | notes |
|---|---|---|
get(x) |
worst | one slot and one comparison per letter |
prefix_values(t, i) |
worst | stops when the walk leaves the trie |
build(D) with the plain scan |
worst | plus the trie build, |
| space |
The bound on holds because the base equal to the current table length is always free, so each family adds at most slots. This bound is no better than the unpacked trie. The real gain is a measurement. In Liang's Table 1, the suffix-compressed trie of his pocket dictionary list of 31,036 words has 38,619 nodes, and the packed table has 38,638 slots, so almost no slot is wasted. The TeX82 patterns pack into 5943 locations. On the random set of 1000 keys in the tests of this page, the density is 0.975. Tarjan and Yao prove a bound for a related method: if the families are packed in decreasing order of size and the number of transitions in families with more than transitions satisfies (harmonic decay), every base is less than the total number of transitions.
Variants
- Suffix compression. Merge equal subtries before packing. For an acyclic machine this is state minimization (DFA minimization). TeX82 packs a suffix-compressed trie, so families are shared.
- Dynamic packed trie. Liang's pattern generator must insert patterns while it counts, so it uses a packed trie that supports insertion. A family that gets a new letter whose slot is full must move to a new base where all its slots fit.
- First fit decreasing. Pack the large families first; this is the method of the theorem of Tarjan and Yao. See first fit decreasing for the same idea in bin packing.
- Double-array trie. The double-array trie also packs nodes by displacement, but it stores for each slot the index of the parent node (the check array), keeps separate base and check arrays, and supports insertion by moving siblings. Liang's version stores the letter, which needs fewer bits, uses one table, and is static.
- Succinct tries. A LOUDS trie uses about two bits per node plus the letters, but each step needs rank and select operations.
When to use it
Use a packed trie for a static set of strings that is searched very often, when the alphabet is small and memory is tight, as for the hyphenation patterns in TeX. A hash table is simpler for exact lookup, but it does not give the prefix walk. A ternary search tree or a list of children per node supports changes but makes each step slower. When keys change often, use a double-array trie, which supports insertion.
Pitfalls
- Two families on one base. If line L11 does not check that the base is free, two families with disjoint letters can share a base, and a lookup from one accepts the letters of the other: the stored letter matches, but it is not a transition of the current family.
- No stored letter. Without the test in line L2, a lookup reads any full slot as its own. The test
test_no_slot_is_shared_and_lookups_never_cross_familieschecks both rules. - The end of the table. Slots past the end count as free in the build but must fail in the lookup; line L2 checks .
- Changes after suffix compression. A shared family has several parents, so a change made for one key changes the others too.
- Expecting the best packing. First fit depends on the order of the families, and another order can give a smaller or a larger table. Measure the density on real data.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/packed-trie/. The authors are listed in prov/JVDGBF.jsonl.
"""Liang's packed trie: the families of an indexed trie overlapped in one table.
An indexed trie gives each node (a family, or state) an array with one slot
per letter of the alphabet. Most slots are empty. The packed trie puts all
families into one table. A family with base b puts its transition on the
letter c in the slot b + code(c). Each slot stores the letter, so that a
lookup can tell its own transitions from those of other families that use
the same slot. Two families never get the same base. The families are
placed one at a time by first fit: each one goes to the lowest base where
its slots are free and the base is not taken.
A slot holds (letter, link, out). link is the base of the child family, or
None when the child has no transitions. out is the value of the key that
ends with this transition, or None.
"""
from typing import Dict, Iterator, List, Optional, Sequence, Tuple
class _Node:
__slots__ = ("children", "value", "has_value")
def __init__(self) -> None:
self.children: Dict[str, "_Node"] = {}
self.value = None
self.has_value = False
class PackedTrie:
"""A static map from nonempty strings to values, packed by first fit."""
def __init__(self, items: Dict[str, object], alphabet: Optional[Sequence[str]] = None) -> None:
if any(len(k) == 0 for k in items):
raise ValueError("keys must be nonempty")
if any(v is None for v in items.values()):
raise ValueError("None marks a missing value, so it cannot be a value")
letters = sorted(set("".join(items))) if alphabet is None else list(alphabet)
self.code = {c: i + 1 for i, c in enumerate(letters)} # codes 1 .. sigma
root = _Node()
for key, value in items.items():
node = root
for ch in key:
node = node.children.setdefault(ch, _Node())
node.value, node.has_value = value, True
self.char: List[Optional[str]] = []
self.link: List[Optional[int]] = []
self.out: List[object] = []
self.owner: List[Optional[int]] = [] # the family that claimed the slot, for tests
self.taken: set = set()
self.families = 0
self.transitions = 0
self.first_fit_tries = 0
self.root_base = self._pack(root)
def _grow(self, size: int) -> None:
while len(self.char) < size:
self.char.append(None)
self.link.append(None)
self.out.append(None)
self.owner.append(None)
def _first_fit(self, codes: List[int]) -> int:
"""The lowest base b, not taken, with every slot b + code free."""
b = 0 # @line L9
while True: # @line L10
self.first_fit_tries += 1
if b not in self.taken and all(b + c >= len(self.char) or self.char[b + c] is None for c in codes): # @line L11
return b # @line L12
b += 1 # @line L13
def _pack(self, root: _Node) -> Optional[int]:
"""Pack the families in breadth-first order; return the base of the root."""
if not root.children:
return None
order: List[Tuple[_Node, Optional[Tuple[int]]]] = [(root, None)]
base_of_root = None
q = 0
while q < len(order): # @line L14
node, parent_slot = order[q]
q += 1
codes = sorted(self.code[c] for c in node.children)
b = self._first_fit(codes) # @line L15
fam = self.families
self.families += 1
self.taken.add(b) # @line L16
self._grow(b + codes[-1] + 1)
for ch, child in sorted(node.children.items()): # @line L17
s = b + self.code[ch]
self.char[s] = ch # @line L18
self.owner[s] = fam
self.out[s] = child.value if child.has_value else None
self.transitions += 1
if child.children:
order.append((child, (s,))) # @line L19
if parent_slot is None:
base_of_root = b
else:
self.link[parent_slot[0]] = b # @line L20
return base_of_root
def _slot(self, base: Optional[int], ch: str) -> Optional[int]:
if base is None or ch not in self.code:
return None
s = base + self.code[ch] # @line L1
if s < len(self.char) and self.char[s] == ch: # @line L2
return s
return None # @line L3
def get(self, key: str, default=None):
"""The value of key, or default. One table index per letter."""
base = self.root_base
s = None
for ch in key: # @line L4
s = self._slot(base, ch) # @line L5
if s is None:
return default # @line L6
base = self.link[s] # @line L7
if s is None or self.out[s] is None:
return default
return self.out[s] # @line L8
def __contains__(self, key: str) -> bool:
return self.get(key, None) is not None
def prefix_values(self, text: str, start: int = 0) -> Iterator[Tuple[int, object]]:
"""Yield (end, value) for each key equal to text[start:end].
This is the walk of Liang's method at one start position.
"""
base = self.root_base
for j in range(start, len(text)):
s = self._slot(base, text[j])
if s is None:
return
if self.out[s] is not None:
yield j + 1, self.out[s]
base = self.link[s]
def check_invariant(self) -> None:
"""Distinct bases, one owner per used slot, and every used slot inside a family."""
assert len(self.taken) == self.families
used = [s for s in range(len(self.char)) if self.char[s] is not None]
assert len(used) == self.transitions
for s in used:
assert self.owner[s] is not None
def size(self) -> int:
"""The number of slots of the table (its length)."""
return len(self.char)
def density(self) -> float:
"""The fraction of slots that hold a transition."""
return self.transitions / max(1, self.size())
test_packed_trie.py 112 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/packed-trie/. The authors are listed in prov/JVDGBF.jsonl.
import random
from packed_trie import PackedTrie
# The nine patterns of the example in The TeXbook, Appendix H, as letters -> gap values.
TEXBOOK = {
"hyph": (0, 0, 3, 0, 0),
"hen": (0, 0, 2, 0),
"hena": (0, 0, 0, 0, 4),
"henat": (0, 0, 0, 5, 0, 0),
"na": (1, 0, 0),
"nat": (0, 2, 0, 0),
"tio": (1, 0, 0, 0),
"io": (2, 0, 0),
"on": (0, 2, 0),
}
def check_invariants(t, keys):
t.check_invariant()
# every slot is claimed by at most one family: the owner list records one family per slot
claimed = [s for s, ch in enumerate(t.char) if ch is not None]
assert len(claimed) == t.transitions
assert len(t.taken) == t.families # distinct bases
# each family's slots are exactly base + code(letter) for its letters
trie_transitions = len({k[:i] for k in keys for i in range(1, len(k) + 1)})
assert t.transitions == trie_transitions
assert t.size() >= t.transitions
def test_texbook_patterns():
t = PackedTrie(TEXBOOK)
for k, v in TEXBOOK.items():
assert t.get(k) == v
for k in ["h", "he", "hy", "hyp", "henx", "x", "", "nati", "o", "tion"]:
assert t.get(k) is None
check_invariants(t, TEXBOOK)
# the walk of Liang's method on .hyphenation. finds the same patterns as a scan
w = ".hyphenation."
found = sorted((i, w[i:e]) for i in range(len(w)) for e, _ in t.prefix_values(w, i))
scan = sorted((i, k) for k in TEXBOOK for i in range(len(w)) if w.startswith(k, i))
assert found == scan
v = [0] * (len(w) + 1)
for i in range(len(w)):
for _, vals in t.prefix_values(w, i):
for d, x in enumerate(vals):
v[i + d] = max(v[i + d], x)
assert v[2:12] == [0, 3, 0, 0, 2, 5, 4, 2, 0, 2]
def random_keys(rng, n, alphabet, kmax):
keys = {}
while len(keys) < n:
k = "".join(rng.choice(alphabet) for _ in range(rng.randint(1, kmax)))
keys[k] = len(keys)
return keys
def test_lookup_agrees_with_a_dict():
rng = random.Random(5)
for trial in range(30):
alphabet = "abcdefghij"[: rng.randint(2, 10)]
keys = random_keys(rng, rng.randint(1, 60), alphabet, 6)
t = PackedTrie(keys, alphabet=alphabet)
check_invariants(t, keys)
for k, v in keys.items():
assert t.get(k) == v and k in t
for _ in range(200):
q = "".join(rng.choice(alphabet + "z") for _ in range(rng.randint(0, 7)))
assert t.get(q) == keys.get(q)
def test_no_slot_is_shared_and_lookups_never_cross_families():
rng = random.Random(9)
keys = random_keys(rng, 300, "abcdefghijklmnopqrstuvwxyz", 7)
t = PackedTrie(keys)
check_invariants(t, keys)
# follow every transition and check that it lands in a slot owned by the right family
fam_of_base = {}
stack = [(t.root_base, "")]
seen = 0
while stack:
base, prefix = stack.pop()
fams = set()
for ch in t.code:
s = t._slot(base, ch)
if s is not None:
fams.add(t.owner[s])
seen += 1
if t.link[s] is not None:
stack.append((t.link[s], prefix + ch))
assert len(fams) == 1 # all transitions found from one base belong to one family
assert base not in fam_of_base
fam_of_base[base] = fams.pop()
assert seen == t.transitions
def test_size_against_sum_of_node_sizes():
# The density of first fit is a measurement, not a guarantee. On this fixed
# random set of 1000 keys the table must beat the unpacked indexed trie by far.
# Measured: 3563 transitions, 2670 families, 3654 slots, density 0.975.
rng = random.Random(1983)
keys = random_keys(rng, 1000, "abcdefghijklmnopqrstuvwxyz", 8)
t = PackedTrie(keys)
sigma = len(t.code)
unpacked = t.families * sigma # one array of sigma slots per family
assert t.transitions <= t.size() <= t.transitions + 2 * sigma + t.families // 10
assert t.size() * 5 < unpacked
assert t.density() > 0.85
History
Liang described the packed trie in Chapter 2 of his 1983 thesis. He wrote that the first-fit method was inspired by the paper "Storing a sparse table" of Tarjan and Yao (1979), and that storing the letter with each transition seemed to be new. TeX82 keeps its hyphenation patterns in a packed trie, and the format file stores the packed table.
References
- Franklin Mark Liang, Word Hy-phen-a-tion by Com-put-er, PhD thesis, Stanford University, August 1983, report STAN-CS-83-977, Chapter 2 (packed tries, first-fit packing, suffix compression and Table 1) and Table 5 (the size of the TeX82 pattern trie)
- Robert Endre Tarjan and Andrew Chi-Chih Yao, Storing a sparse table, Communications of the ACM 22(11), 606-611, 1979, row displacement and the first-fit-decreasing method with the harmonic decay condition
- Donald E. Knuth, TeX: The Program, Computers and Typesetting volume B, Addison-Wesley, 1986, the parts on the hyphenation trie and its packing
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag JVDGBF Edit this page History Report an error Markdown