Trie or set? Time and memory trade-offs
🌍 In real life. A phone keeps your contacts. To check "is Nadia saved?" any list with a good index is enough. But to show every name starting with "Na" as you type, the phone needs names grouped by their starts. And it has only so much memory, so it can't keep every possible structure.
A programmer chooses the same way. Python's set (Chapter 35) is excellent for "is this exact word here?". A trie earns its place when the questions are about prefixes. This lesson weighs the two, and shows when a sorted list does the job instead.
The idea in one sentence: use a set when you only ask whether whole words are present, and a trie when you ask about prefixes (autocomplete, counting, shortest unique starts), remembering that each trie node is a separate object with its own dict, so a trie saves letters only when many words share their starts.
Its words:
- exact lookup: "is this whole word stored?"; a set does it in O(L) on average by hashing
- prefix query: "which words, or how many, start with p?"; a trie walks to p in O(L)
- sharing: words with a common start reuse the same nodes; the trie needs one node per distinct prefix
- overhead: the extra memory each node costs beyond its letter: a Python object and a dict, a few hundred bytes each
- shortest unique prefix: the fewest first letters that pick out one word from the list
How to choose, step by step:
- only exact lookups? use a
set - prefix questions on a list that rarely changes? a sorted list with
bisect(Chapter 43) finds the range of words starting with p in O(L log n) - many prefix questions while words keep being added, or per-prefix counts? use a trie
Watch how much in, inn, ink, into and inter share: 17 letters, but only 8 nodes:
Why the choice matters. A set stores every word whole and finds one by its hash, so it can't see that "into" and "inter" share "int". To answer a prefix question it has to test every word. A trie stores each distinct prefix once, so a prefix question is one walk down plus the answers below. The price is memory: a trie node holds one letter but is a whole Python object with a dict. A trie therefore saves space only when sharing is heavy, and in Python it often uses more memory than a set of the same words.
What it costs, by counting, for n words of about L letters each:
- exact lookup: set O(L) on average; trie O(L); sorted list O(L log n)
- all words starting with p, k of them: set O(n × L) (check every word); sorted list O(L log n + k); trie O(L + size of the subtree below p)
- adding a word: set and trie O(L) on average; sorted list O(n), to shift the items after it
- memory: set about n strings; trie one node per distinct prefix, at most n × L nodes, fewer when words share starts
For the five words above the trie needs 8 nodes for 17 letters; for five words with nothing in common it would need a node for every letter.
def sharing(words):
prefixes = {w[:i] for w in words for i in range(1, len(w) + 1)}
return len(prefixes), sum(len(w) for w in words) # (trie nodes, letters)
print(sharing(["in", "inn", "ink", "into", "inter"]))
print(sharing(["cat", "dog", "fox", "owl", "pig"])) # nothing shared
# prefix questions with a sorted list and bisect: the words in [p, p + "{")
import bisect
words = sorted(["in", "inn", "ink", "into", "inter", "cat"])
p = "int"
lo = bisect.bisect_left(words, p)
hi = bisect.bisect_left(words, p + "{") # "{" comes right after "z"
print(words[lo:hi])
def shortest_unique_prefixes(words):
root = {} # each node: {"n": words through it, "kids": {...}}
for w in words:
node = root
for ch in w:
node = node.setdefault(ch, {"n": 0, "kids": {}})
node["n"] += 1
node = node["kids"]
answer = []
for w in words:
node = root
for i, ch in enumerate(w):
if node[ch]["n"] == 1: # only this word passes here: unique
answer.append(w[: i + 1])
break
node = node[ch]["kids"]
return answer
print(shortest_unique_prefixes(["dog", "cat", "apple", "apricot", "fish"]))Mistakes and edge cases.
- a trie for exact lookups only: it is more code and usually more memory than a
set, for no gain - assuming a trie always saves memory: it saves letters, but each node is an object; with little sharing it costs more than the words themselves
- a word that is a prefix of another: in and into: "in" has no unique prefix shorter than itself, and not even the whole word picks it out, since into starts the same way; shortest-unique-prefix problems usually promise this can't happen
- the bisect trick needs a sorted list: and a character after every letter used (
"{"follows"z"for lower-case words) - many updates: a sorted list pays O(n) per insert, which hurts when words keep arriving; a trie or set doesn't
Quiz
What does this print?
def sharing(words): prefixes = {w[:i] for w in words for i in range(1, len(w) + 1)} return len(prefixes), sum(len(w) for w in words) # (trie nodes, letters) print(sharing(["in", "inn", "ink", "into", "inter"]), sharing(["cat", "dog"]))You only ever ask "is this exact word in the dictionary?". What should you use?
- A set: O(L) on average, less code and memory than a trie
- A trie: it is always faster
- A list: it keeps the order
What does this print?
def shortest_unique_prefixes(words): root = {} # each node: {"n": words through it, "kids": {...}} for w in words: node = root for ch in w: node = node.setdefault(ch, {"n": 0, "kids": {}}) node["n"] += 1 node = node["kids"] answer = [] for w in words: node = root for i, ch in enumerate(w): if node[ch]["n"] == 1: # only this word passes here: unique answer.append(w[: i + 1]) break node = node[ch]["kids"] return answer print(shortest_unique_prefixes(["zebra", "dog", "duck", "dove"]))A word list never changes, and you need the words starting with a prefix. Which is simplest and fast?
- A sorted list with bisect: the matches sit next to each other, found in O(L log n)
- A set: test every word with startswith
- A dict from word to True
Does a trie in Python always use less memory than a set of the same words?
- No: it stores fewer letters, but every node is an object with a dict, which usually costs more
- Yes, always
- Yes, if the words are short
This should list the words starting with "int": ['inter', 'into']. It prints []. Which line is wrong?
import bisect words = sorted(["in", "inn", "ink", "into", "inter", "cat"]) p = "int" lo = bisect.bisect_left(words, p) hi = bisect.bisect_left(words, p + "a") print(words[lo:hi])
Coding tasks
Write
shortest_unique_prefixes(words): for each word, in order, its shortest prefix that no other word in the list starts with. No word is a prefix of another, so every word has one. Count, on every trie node, how many words pass through it.Write
sharing(words): return a tuple(nodes, letters): how many nodes (not counting the root) a trie of these words needs, and how many letters the words have in all. The closer the two numbers, the less the words share.