Sub topic 9
Memory and Comparison with Hash Sets and Sorted Arrays
This chapter assumes you can read the Trie class from earlier chapters, know Big-O notation, and know how Python dictionaries and sorted lists behave. It compares a trie with two common alternatives for storing a set of strings: a hash set and a sorted array.
Where a trie spends memory
A trie stores one node per distinct prefix, not one per word. The words car, card, care and cat need nodes for c, ca, car, card, care and cat. That is 6 nodes below the root, while the words contain 14 characters in total. Shared prefixes save space.
The saving is not guaranteed. Each node is an object with its own child container and flag. In Python, an empty dict and a TrieNode instance each cost tens of bytes, so one node often costs more than the single character it represents. Words with little shared structure, such as random identifiers, create nearly one node per character. A trie can then use many times the memory of the raw strings.
Two factors decide the footprint:
- Prefix sharing. Natural-language word lists and URL paths share many prefixes. Hashes, UUIDs and random tokens do not.
- Child storage. A dictionary per node costs memory in proportion to its children, plus overhead. A fixed array of 26 slots costs the same for every node, even a leaf with no children.
import sys
def count_nodes(node):
return 1 + sum(count_nodes(c) for c in node.children.values())
words = ["car", "card", "care", "cat"]
print("characters:", sum(len(w) for w in words))
print("empty dict bytes:", sys.getsizeof({}))Run this with the Trie from earlier chapters and call count_nodes(t.root) - 1 after inserting the words. The result is 6 nodes for 14 characters.
Comparing the three structures
Let n be the number of words, L the length of the key being looked up, and k the number of matches returned.
| Operation | Trie | Hash set | Sorted array |
|---|---|---|---|
| Exact lookup | O(L) | O(L) average, O(n·L) worst case | O(L log n) |
| Prefix check | O(L) | O(n·L) by scanning | O(L log n) with binary search |
| List all words with a prefix | O(L + size of subtree) | O(n·L) by scanning | O(L log n + k·L) |
| Insert | O(L) | O(L) average | O(n) for shifting elements |
| Sorted iteration | DFS with sorted children | Needs a sort first | Already sorted |
| Memory | High overhead per node | Moderate | Lowest, contiguous |
A hash set computes the hash of the whole key, which takes O(L), and then compares it with the stored key, which also takes O(L). Its exact lookup is therefore as fast as a trie in practice and uses less memory. Its weakness is prefix queries. A hash set has no notion of order or shared prefixes, so it must examine every key.
A sorted array answers prefix queries well. Binary search finds the first word at or after the prefix, and the matches follow in a contiguous run. Each comparison costs up to O(L), which gives O(L log n). Inserts are slow because elements shift, but for a fixed dictionary built once, this is often the best choice.
from bisect import bisect_left
def prefix_matches(sorted_words, prefix, limit=10):
i = bisect_left(sorted_words, prefix)
out = []
while i < len(sorted_words) and len(out) < limit:
if not sorted_words[i].startswith(prefix):
break
out.append(sorted_words[i])
i += 1
return out
words = sorted(["car", "card", "care", "cat"])
print(prefix_matches(words, "car")) # ['car', 'card', 'care']Decision criteria
- Choose a hash set when you only test exact membership. It is simple and compact.
- Choose a sorted array when the data is built once and read many times. It has the smallest memory use and good cache behavior.
- Choose a trie when you need frequent prefix queries on changing data, per-node data such as counts, or predictable O(L) cost that does not depend on
n.
A trie's O(L) bound is a strong guarantee, but constants matter. Following a pointer per character is slower in practice than a binary search over contiguous memory, so benchmark with your own data before committing.
Exercise
A static list of 1 million random 32-character hex tokens must support only exact membership checks. Which of the three structures would you pick, and why?
Show answer
A hash set. The tokens are random, so a trie would share almost no prefixes and use roughly one node per character, which is very costly. No prefix queries are needed, so a sorted array's main advantage is unused. A hash set gives O(L) average lookup with moderate memory.
Exercise
A word list of 100,000 entries is fixed at startup, and the program only runs autocomplete queries that return up to 10 words. Give one reason to choose a sorted array and one reason to choose a trie.
Show answer
Sorted array: it uses the least memory, and bisect_left plus a short forward scan finds the matches in O(L log n + k·L). Trie: it finds the prefix node in O(L), independent of n, and lets you store ranking data in nodes for better ordering of suggestions.