Q&A-1What is a trie, how is its node structure represented in memory, and how do fixed-array versus hash-map child pointers trade off space and time?
Answer
A trie (prefix tree) is a search tree ordered by the constituent symbols of keys rather than whole-key comparisons, where each edge or child pointer corresponds to a character, and the path from the root defines a shared prefix.
Node Representation in Memory
A trie node stores two things: a terminal indicator (a boolean flag is_terminal or a payload pointer/value) and a collection of references to child nodes indexed by symbol:
# Fixed alphabet representation (e.g. lowercase ASCII, alphabet size R = 26)
class FixedArrayNode:
__slots__ = ("children", "is_terminal")
def __init__(self):
self.children = [None] * 26 # 26 pointer slots per node
self.is_terminal = False
# Dynamic representation (arbitrary alphabet / sparse branching)
class HashMapNode:
__slots__ = ("children", "is_terminal")
def __init__(self):
self.children = {} # Dynamic hash table
self.is_terminal = FalseSpace and Time Trade-offs
| Property | Fixed Array (Node[R]) | Hash Map (dict / std::unordered_map) |
|---|---|---|
| Branch lookup time | $O(1)$ worst-case direct index offset (arr[c - 'a']) | $O(1)$ average, $O(b)$ worst-case probe sequence under hash collision |
| Memory per node (sparse) | High: $R \times \text{sizeof(pointer)}$ always allocated | Low: base table overhead + only active edges |
| Memory per node (dense) | Low overhead: contiguous array of references | High overhead: hash table buckets, load factor slack (typically 25-50% empty), key/hash storage |
| Cache locality | Contiguous chunk per node; predictable indexing | Pointer indirection to hash table buffer + open-addressing / bucket chasing |
| Alphabet flexibility | Rigid: bounded small alphabets (ASCII $R=26, 128, 256$) | Flexible: sparse Unicode code points, arbitrary byte streams |
Worked Arithmetic
Consider storing $100{,}000$ nodes on a 64-bit architecture (8-byte pointers) with standard ASCII ($R = 256$):
- Fixed Array: $100{,}000 \times (256 \times 8\text{ bytes}) \approx 204.8\text{ MB}$ just for pointer arrays, even if each node averages only 2 active transitions (99.2% empty pointers).
- Hash Map: An empty hash map in Python 3.14 costs 64 bytes base. For an average branching factor of 2, a compact hash table consumes $\approx 120-180$ bytes per node: $100{,}000 \times 160\text{ bytes} \approx 16\text{ MB}$.
Conversely, if $R = 26$ (lowercase letters) and nodes are dense (average branching factor $> 15$):
- Fixed Array: $26 \times 8 = 208\text{ bytes}$ per node.
- Hash Map: Storing 15 entries in a hash map with standard resize thresholds (powers of two capacity 32) requires tracking 32 hash buckets, keys, and values, exceeding 350-500 bytes per node due to hash table metadata and load-factor slack.
Failure Modes & Practical Decision
- Fixed Array with Unbounded Alphabets (OOM Trap): Allocating fixed arrays for broad alphabets like full UTF-8 or 16-bit Unicode codepoints ($R = 65{,}536$) leads to gigabytes allocated for trivial key counts. Fixed arrays belong strictly to small, fixed alphabets ($R \le 256$).
- Hash Table Constant Factor Latency: While hash maps are asymptotically $O(k)$ for a string of length $k$, each hop computes a character hash, traverses map buckets, and incurs CPU cache misses. Fixed arrays compile down to a single base-pointer addition and dereference (
*(node->children + offset)), often running $3\times-5\times$ faster in hot lookup paths when memory limits are not breached.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.