Tries and prefix operations
Storing strings character by character: the trie, lookups in time proportional to the key’s length, ways to store children, prefix queries such as keys with a prefix and longest prefix, and autocomplete.
- CS61B
- Tries · Textbook Ch. 26
- Swift book
- Strings and Characters
- Documentation
- String
When the keys are strings, a general-purpose map treats each key as an opaque value to hash or compare. But strings have structure: many share beginnings, “car”, “card”, “care”, “cart”. A trie, CS61B’s last search structure, is built around that structure, and it answers questions about prefixes that hash tables cannot, such as “every word starting with car”.
Tries
A trie (from retrieval, pronounced “try”) stores strings character by character. Each node has children, one for each character that can come next, and a flag saying whether the path from the root to this node spells a stored key:
(root)
└─ c
└─ a
├─ r ★
│ ├─ d ★
│ ├─ e ★
│ └─ t ★
└─ t ★
Here ★ marks nodes whose path is a key: “car”, “cat”, “card”, “care”, and “cart”. The five words share the path c–a, and the prefix “car” is stored once.
final class Trie {
private final class Node {
var children: [Character: Node] = [:]
var isKey = false
}
private let root = Node()
private(set) var count = 0
func insert(_ word: String) {
var node = root
for character in word {
if let next = node.children[character] {
node = next
} else {
let next = Node()
node.children[character] = next
node = next
}
}
if !node.isKey {
node.isKey = true
count += 1
}
}
private func node(for prefix: String) -> Node? {
var node = root
for character in prefix {
guard let next = node.children[character] else { return nil }
node = next
}
return node
}
func contains(_ word: String) -> Bool {
node(for: word)?.isKey ?? false
}
func keys(withPrefix prefix: String) -> [String] {
guard let start = node(for: prefix) else { return [] }
var result: [String] = []
func collect(_ node: Node, _ path: String) {
if node.isKey { result.append(path) }
for (character, child) in node.children.sorted(by: { $0.key < $1.key }) {
collect(child, path + String(character))
}
}
collect(start, prefix)
return result
}
}
let trie = Trie()
for word in ["car", "cat", "card", "care", "cart", "dog"] {
trie.insert(word)
}
print(trie.contains("car"), trie.contains("ca"), trie.keys(withPrefix: "car"), trie.count)
// true false ["car", "card", "care", "cart"] 6
contains("ca") is false: the path exists, but no key ends there. That is the job
of the isKey flag.
What it costs
Looking up a key of length L follows L links, one per character, and then checks a flag. That is Θ(L), and it does not depend on N, the number of keys stored. A hash table also spends Θ(L) hashing the key, and a search tree spends Θ(log N) comparisons, each of which may read up to L characters; for strings, the trie is often the fastest, and it never needs to hash or compare whole keys.
The price is memory: a node per character of every key, minus shared prefixes, each with a structure for its children. How the children are stored is a real choice:
| Children stored as | Lookup of one child | Memory per node |
|---|---|---|
an array indexed by character code (CS61B’s DataIndexedCharMap) |
Θ(1) | one slot per possible character, even if unused |
| a hash table, as here | Θ(1) on average | proportional to the actual children |
| a search tree | O(log R), for R possible characters | proportional to the actual children |
An array of 128 slots per node is fast for ASCII keys but wasteful when nodes have
one or two children, which most do. A dictionary adapts to Unicode keys, which
Swift strings make natural: a Character can be “é” or a flag emoji.
What would Swift print?
var nodes = 1
var children: [String: Set<Character>] = [:]
for word in ["tea", "ten", "to", "team"] {
var prefix = ""
for c in word {
if children[prefix, default: []].insert(c).inserted {
nodes += 1
}
prefix.append(c)
}
}
print(nodes)Show answer and explanation
Answer7
Count the nodes of the trie: the root, then one for each distinct prefix: t, te, tea, ten, to, and team. Shared prefixes are stored once: “team” adds only one node, after “tea”. That is 1 + 6 = 7 nodes for 13 characters in the four words.
Prefix operations
A trie answers questions about prefixes by walking to the prefix’s node and looking below it:
- Keys with a prefix, as above: walk to the prefix, then collect every key in that subtree. The cost is the prefix’s length plus the size of the answer.
- Longest prefix of a string that is a key: walk along the string as far as possible, remembering the last node whose flag was set. A router uses this to choose the most specific route for an address; a tokenizer, to find the longest keyword at the start of the input.
func longestPrefix(of text: String) -> String {
var node = root
var longest = ""
var path = ""
for character in text {
guard let next = node.children[character] else { break }
path.append(character)
node = next
if node.isKey { longest = path }
}
return longest
}
// With car, card, care, cart stored: longestPrefix(of: "cardigan") is "card",
// and longestPrefix(of: "carbon") is "car".
A hash table has no notion of “keys that start with” and would have to examine every key. A search tree can find the range of keys between “car” and “cas”, which works too, with comparisons of whole strings.
Autocomplete
Typing “car” into a search box shows the most popular completions. With a weight on every key, how often it is searched, a trie finds them: walk to the prefix, then collect the keys below it and keep the k heaviest, with Lesson 41’s heap if the subtree is large. Search engines precompute more, storing in each node the best completions of its subtree, so a query costs only the walk to the prefix.
Put the lines in order
Put the lines in order so the program prints true false.
let isPrefix = words.contains { $0.hasPrefix(prefix) }var words: Set<String> = ["car", "cart"]print(isPrefix, words.contains(prefix))let prefix = "ca"
Show the correct program
var words: Set<String> = ["car", "cart"]
let prefix = "ca"
let isPrefix = words.contains { $0.hasPrefix(prefix) }
print(isPrefix, words.contains(prefix))Lab 49: Tries
Q0: What would Swift print?
What would Swift print?
final class Node {
var children: [Character: Node] = [:]
var isKey = false
}
let root = Node()
func insert(_ word: String) {
var node = root
for c in word {
let next = node.children[c] ?? Node()
node.children[c] = next
node = next
}
node.isKey = true
}
for w in ["an", "and", "ant", "any"] { insert(w) }
let a = root.children["a"]!
let n = a.children["n"]!
print(root.children.count, a.isKey, n.isKey, n.children.count)Show answer and explanation
Answer1 false true 3
Every word starts with “a”, so the root has one child. “a” alone is not a key, but “an” is. Below “an” are three children: d, t, and y.
Q1: Removing
Add remove(_:) to the lesson’s Trie: clear the key’s flag, then remove the
nodes that no longer lead to any key, from the end of the word back toward the root.
Check that removing “card” leaves “car” and “cart” in place and deletes the d
node.
Show solution
final class Trie {
private final class Node {
var children: [Character: Node] = [:]
var isKey = false
}
private let root = Node()
private(set) var count = 0
var nodeCount: Int {
func size(_ n: Node) -> Int { 1 + n.children.values.map(size).reduce(0, +) }
return size(root)
}
func insert(_ word: String) {
var node = root
for c in word {
let next = node.children[c] ?? Node()
node.children[c] = next
node = next
}
if !node.isKey { node.isKey = true; count += 1 }
}
func contains(_ word: String) -> Bool {
var node = root
for c in word {
guard let next = node.children[c] else { return false }
node = next
}
return node.isKey
}
func remove(_ word: String) {
var path: [(node: Node, character: Character)] = []
var node = root
for c in word {
guard let next = node.children[c] else { return }
path.append((node, c))
node = next
}
guard node.isKey else { return }
node.isKey = false
count -= 1
// Walk back up, removing nodes that are neither keys nor lead to keys.
var current = node
while let (parent, c) = path.popLast(), !current.isKey, current.children.isEmpty {
parent.children[c] = nil
current = parent
}
}
}
let trie = Trie()
for w in ["car", "card", "cart"] { trie.insert(w) }
let before = trie.nodeCount
trie.remove("card")
assert(!trie.contains("card") && trie.contains("car") && trie.contains("cart"))
assert(trie.nodeCount == before - 1 && trie.count == 2)
trie.remove("car")
assert(trie.nodeCount == before - 1) // "car" still leads to "cart", so no nodes goRemoving a key only removes nodes that became useless: those with no children that are not keys themselves. The loop stops at the first node that is still needed.
Q2: Counting by prefix
Store in each node the number of keys in its subtree, so that
count(withPrefix:) takes time proportional to the prefix’s length alone, not the
number of matching keys.
Show solution
final class CountingTrie {
private final class Node {
var children: [Character: Node] = [:]
var isKey = false
var below = 0 // keys in this subtree, including this node
}
private let root = Node()
func insert(_ word: String) {
guard !contains(word) else { return }
var node = root
node.below += 1
for c in word {
let next = node.children[c] ?? Node()
node.children[c] = next
node = next
node.below += 1
}
node.isKey = true
}
func contains(_ word: String) -> Bool {
var node = root
for c in word {
guard let next = node.children[c] else { return false }
node = next
}
return node.isKey
}
func count(withPrefix prefix: String) -> Int {
var node = root
for c in prefix {
guard let next = node.children[c] else { return 0 }
node = next
}
return node.below
}
}
let trie = CountingTrie()
for w in ["car", "card", "care", "cart", "cat", "dog", "car"] { trie.insert(w) }
assert(trie.count(withPrefix: "car") == 4 && trie.count(withPrefix: "ca") == 5)
assert(trie.count(withPrefix: "") == 6 && trie.count(withPrefix: "x") == 0)Inserting a duplicate must not change the counts, which is why insert checks first.
Every node on the path of a new key gains one key below it.
Q3: Autocomplete
Given words with weights, write complete(_:k:), which returns the k heaviest keys
starting with a prefix, heaviest first, with ties broken alphabetically.
Show solution
final class WeightedTrie {
private final class Node {
var children: [Character: Node] = [:]
var weight: Int? // nil: not a key
}
private let root = Node()
func insert(_ word: String, weight: Int) {
var node = root
for c in word {
let next = node.children[c] ?? Node()
node.children[c] = next
node = next
}
node.weight = weight
}
func complete(_ prefix: String, k: Int) -> [String] {
var node = root
for c in prefix {
guard let next = node.children[c] else { return [] }
node = next
}
var found: [(word: String, weight: Int)] = []
func collect(_ node: Node, _ path: String) {
if let w = node.weight { found.append((path, w)) }
for (c, child) in node.children { collect(child, path + String(c)) }
}
collect(node, prefix)
return found.sorted { $0.weight != $1.weight ? $0.weight > $1.weight : $0.word < $1.word }
.prefix(k).map(\.word)
}
}
let trie = WeightedTrie()
for (word, weight) in [("swift", 90), ("swiftui", 70), ("switch", 70), ("swim", 40), ("sword", 10)] {
trie.insert(word, weight: weight)
}
assert(trie.complete("sw", k: 3) == ["swift", "swiftui", "switch"])
assert(trie.complete("swi", k: 10) == ["swift", "swiftui", "switch", "swim"])
assert(trie.complete("x", k: 3).isEmpty)This collects every completion and sorts them, which is fine for small subtrees. For a search engine, where “s” may have millions of completions, each node would store its subtree’s top k, making every query as fast as the walk to the prefix.
Q4 (optional): Longest common prefix
Write longestCommonPrefix(_:) for a list of words using a trie: insert them all,
then walk from the root while the current node has exactly one child and is not the
end of a word.
Show solution
final class Node {
var children: [Character: Node] = [:]
var isKey = false
}
func longestCommonPrefix(_ words: [String]) -> String {
guard !words.isEmpty else { return "" }
let root = Node()
for word in words {
var node = root
for c in word {
let next = node.children[c] ?? Node()
node.children[c] = next
node = next
}
node.isKey = true
}
var prefix = ""
var node = root
while !node.isKey, node.children.count == 1, let (c, child) = node.children.first {
prefix.append(c)
node = child
}
return prefix
}
assert(longestCommonPrefix(["interview", "internet", "interval"]) == "inter")
assert(longestCommonPrefix(["swift", "swim"]) == "swi")
assert(longestCommonPrefix(["car", "cart"]) == "car") // stops at the end of "car"
assert(longestCommonPrefix(["abc", "xyz"]) == "")The walk stops at the first branch, where the words disagree, or at the end of a word, since a prefix cannot be longer than the shortest word.
What’s next
That finishes CS61B’s search structures. Next lesson: software engineering, and why large programs become hard to change.