Hashing and tries, revisited
Exam-level practice: hash codes of composite values, tombstones in open addressing, the danger of mutable keys, and trie variations for counting and longest prefixes.
- Lessons
- Hash tables · Hash functions · Tries and prefix operations
This discussion revisits Lessons 48 to 50 at exam level, like CS61B’s second discussion on hashing and tries.
Q1: What would Swift print?
What would Swift print?
enum Slot: Equatable {
case empty, deleted
case full(Int)
}
var slots: [Slot] = [.full(7), .full(14), .full(21), .empty, .empty, .empty, .empty]
slots[1] = .deleted
func contains(_ k: Int) -> Bool {
var i = k % 7
while slots[i] != .empty {
if slots[i] == .full(k) { return true }
i = (i + 1) % 7
}
return false
}
print(contains(21), contains(14))Show answer and explanation
Answertrue false
7, 14, and 21 all start at slot 0 and sit in slots 0 to 2. After 14 is deleted, a
tombstone in slot 1 keeps the probe sequence going, so 21 is still found. Had slot 1
been set to .empty, the search for 21 would have stopped there and missed it.
Q2: Keys that change
A Set<Student> uses a hash of the student’s name and grade. Later, a program raises a
student’s grade in place. Describe what can go wrong with contains and insert
afterwards, and give two different fixes.
Show solution
The student stays in the bucket for its old hash code. contains looks in the bucket for
the new hash code and usually misses it; insert of the updated student then adds a
second copy, so the set holds the same student twice. Fixes:
- Make
Studenta structure. The set holds its own copy, which cannot be changed from outside; to update, remove the old value and insert the new one. - Hash and compare only immutable properties, such as a
let id. Changing the grade then does not affect the hash at all.
Q3: Counting with a trie
Design a trie that, for a list of words inserted one by one (with repeats), answers
frequency(of:) and mostFrequent(withPrefix:), each in time proportional to the
length of the word or prefix, not to the number of words. What does each node store?
Show solution
Each node stores a count of how many times its word was inserted (0 if it is not a key),
and the most frequent key in its subtree along with that key’s count. frequency(of:)
walks to the word and reads its count. mostFrequent(withPrefix:) walks to the prefix
and reads the stored best. Insertion updates the word’s count, then walks back up the
path updating each node’s best if the new count beats it: insertion stays proportional
to the word’s length, because counts only grow.
final class Node {
var children: [Character: Node] = [:]
var count = 0
var best: (word: String, count: Int)? = nil
}
let root = Node()
func insert(_ word: String) {
var path = [root]
var node = root
for c in word {
let next = node.children[c] ?? Node()
node.children[c] = next
node = next
path.append(node)
}
node.count += 1
for n in path where n.best == nil || node.count > n.best!.count ||
(node.count == n.best!.count && word < n.best!.word) {
n.best = (word, node.count)
}
}
func mostFrequent(withPrefix prefix: String) -> String? {
var node = root
for c in prefix {
guard let next = node.children[c] else { return nil }
node = next
}
return node.best?.word
}
for w in ["car", "cat", "car", "cart", "cat", "car", "dog"] { insert(w) }
assert(mostFrequent(withPrefix: "ca") == "car")
assert(mostFrequent(withPrefix: "cat") == "cat" && mostFrequent(withPrefix: "d") == "dog")
assert(mostFrequent(withPrefix: "x") == nil)Q4: Exam-level: expected costs
- A hash table has N items in M buckets, with a perfect spread. What is the expected cost of an unsuccessful search, with separate chaining?
- Why must a hash table’s bucket count grow multiplicatively?
- A trie stores N words of average length L over an alphabet of R characters, with children in arrays of size R. Roughly how much memory can it use, at most?
Show solution
- Θ(1 + N/M): computing the bucket, plus scanning an average bucket of N/M items. With the load factor N/M bounded, that is constant.
- For the same reason as array lists (Lesson 30): each resize rehashes every item, and only geometric growth makes the total rehashing proportional to the number of insertions, keeping each insertion amortized constant.
- Up to N · L nodes (if no prefixes are shared), each with an array of R child references: Θ(N L R) memory. For R = 128, most of those slots are empty, which is why tries often store children in hash maps or trees instead.