Hash functions
What makes a hash function good, writing hash(into:) for your own types, why Swift’s hashes change on every run, the danger of keys that change, and open addressing with linear probing as a second way to handle collisions.
- CS61B
- Hashing II · Textbook Ch. 25
- Swift book
- Advanced Operators
- Documentation
- Hasher
Lesson 48 showed that a hash table is only as good as its hash codes. This lesson, following CS61B’s second hashing lecture, looks at what makes a hash function good, how Swift makes good ones easy to get and hard to attack, and a second design for the table itself.
What a hash function must do
A hash function for a type must be:
- Consistent with equality. If
a == b, they must hash the same (Lesson 32’s rule). Otherwise equal keys land in different buckets, and lookups miss. - Deterministic within a run: the same value must hash the same every time it is asked.
- Well spread: different values should give hash codes that look unrelated,
so that keys land evenly across buckets, even keys that look alike, such as
user1,user2,user3.
The first two are about correctness; the third is about speed. CS61B studies how
Java’s String.hashCode achieves it: it treats the characters as the digits of a
number in base 31, s[0]·31ⁿ⁻¹ + s[1]·31ⁿ⁻² + … + s[n−1], wrapping around on
overflow. The base should be odd, so that multiplying does not shift information off
the top of the number, and a small prime works well in practice.
Hashing your own types
In Swift you do not choose the arithmetic. A Hashable type implements
hash(into:) by feeding the parts that make it unique to a Hasher:
struct Card: Hashable {
let rank: Int
let suit: Character
let isFaceUp: Bool // not part of the card's identity
static func == (a: Card, b: Card) -> Bool {
a.rank == b.rank && a.suit == b.suit
}
func hash(into hasher: inout Hasher) {
hasher.combine(rank)
hasher.combine(suit)
}
}
let deck: Set = [Card(rank: 12, suit: "♠", isFaceUp: true), Card(rank: 12, suit: "♠", isFaceUp: false),
Card(rank: 1, suit: "♥", isFaceUp: false)]
print(deck.count) // 2
The rule of thumb: combine exactly the properties that == compares. Leaving
one out still satisfies rule 1, but makes more collisions; adding one that ==
ignores, like isFaceUp here, breaks rule 1. The Hasher mixes whatever it is
given, in order, so combine(rank) then combine(suit) differs from the reverse,
and the spread comes out well whatever the values.
Why the hashes change on every run
Run a program that prints "cat".hashValue twice, and it prints two different
numbers. Swift seeds its Hasher with a random number when each process starts.
Within one run hashes are consistent, satisfying rule 2, but across runs they
differ.
The reason is an attack called hash flooding. If hash codes were predictable,
an attacker could send a web server thousands of form fields or JSON keys that all
land in the same bucket, and turn every lookup into a linear scan, as Lesson 48’s
BadKey did, slowing the server to a crawl. With a secret random seed, the
attacker cannot know which keys collide.
Two consequences for programs:
- Never store or send a
hashValueexpecting it to mean the same thing later, or in another process. It is not an identifier. - Iterating over a
SetorDictionarycan give a different order on every run. Code that depends on that order, including tests, is buggy. Sort first.
For debugging, setting the environment variable SWIFT_DETERMINISTIC_HASHING=1
makes hashing repeatable across runs.
What would Swift print?
let a: Set = [3, 1, 2]
let b: Set = [2, 3, 1]
print(a == b, a.sorted(), Array(a).count)Show answer and explanation
Answertrue [1, 2, 3] 3
Sets are equal if they have the same elements, whatever order they were written in.
The order of Array(a) is not predictable, and may change between runs, which is
why only its count, and the sorted version, are printed.
Keys that change
A hash table assumes a key’s hash code stays the same as long as the key is in the
table. For value types, that is automatic: the table holds its own copy. For a
class whose hash(into:) uses mutable properties, it is not:
final class Point: Hashable {
var x: Int
var y: Int
init(_ x: Int, _ y: Int) { self.x = x; self.y = y }
static func == (a: Point, b: Point) -> Bool { a.x == b.x && a.y == b.y }
func hash(into hasher: inout Hasher) {
hasher.combine(x)
hasher.combine(y)
}
}
let p = Point(1, 2)
var visited: Set = [p]
p.x = 100 // changes the hash of an object in the set
print(visited.count, visited.contains(p)) // 1 false: almost always
The set still holds the object, but in the bucket for its old hash code; looking it
up with its new hash code searches the wrong bucket. (Rarely, both hash codes pick
the same bucket and the lookup succeeds, which makes the bug worse: it is
intermittent.) CS61B warns about exactly this with Java’s mutable objects. The
cures are to hash only immutable properties, to use a structure, or, for a class
whose identity is the object itself, to hash ObjectIdentifier(self) and compare
with ===.
Open addressing
Separate chaining keeps a list per bucket. Open addressing keeps every item in the array itself, one per slot. When a key’s slot is taken, it probes for another: with linear probing, the next slot, and the next, wrapping around, until it finds the key or an empty slot:
struct ProbingSet {
private enum Slot: Equatable {
case empty
case deleted // a tombstone: keep probing past it
case occupied(Int)
}
private var slots = Array(repeating: Slot.empty, count: 8)
private(set) var count = 0
private var used = 0 // occupied or deleted slots
private func start(_ key: Int) -> Int {
let h = key.hashValue % slots.count
return h < 0 ? h + slots.count : h
}
func contains(_ key: Int) -> Bool {
var i = start(key)
while slots[i] != .empty {
if slots[i] == .occupied(key) { return true }
i = (i + 1) % slots.count
}
return false
}
mutating func insert(_ key: Int) {
guard !contains(key) else { return }
if (used + 1) * 2 > slots.count { rebuild(to: slots.count * 2) }
var i = start(key)
while case .occupied = slots[i] { i = (i + 1) % slots.count }
if slots[i] == .empty { used += 1 }
slots[i] = .occupied(key)
count += 1
}
mutating func remove(_ key: Int) {
var i = start(key)
while slots[i] != .empty {
if slots[i] == .occupied(key) {
slots[i] = .deleted
count -= 1
return
}
i = (i + 1) % slots.count
}
}
private mutating func rebuild(to size: Int) {
let keys = slots.compactMap { slot -> Int? in
if case .occupied(let k) = slot { return k } else { return nil }
}
slots = Array(repeating: .empty, count: size)
count = 0
used = 0
for key in keys { insert(key) }
}
}
var set = ProbingSet()
for n in 0..<1_000 { set.insert(n) }
for n in stride(from: 0, to: 1_000, by: 2) { set.remove(n) }
print(set.count, set.contains(3), set.contains(4)) // 500 true false
Removing needs care. Simply emptying a slot would break the probe sequence of every key that probed past it, making them unfindable, so removal leaves a tombstone: lookups continue past it, and insertions may reuse it. The table is rebuilt when occupied slots plus tombstones reach half the array.
Open addressing uses one array and no lists, so it is compact and friendly to
memory caches, which is why Swift’s own Set and Dictionary use it (with linear
probing). Its weakness is clustering: runs of full slots grow, and a key landing
anywhere in a run must walk to its end. Keeping the load factor low, below about
three quarters, keeps runs short.
Put the lines in order
Put the lines in order so the program prints 0: key 18 starts at slot 2, which is taken, and wraps around.
var i = 18 % 4while slots[i] != nil { i = (i + 1) % 4 }print(i)var slots: [Int?] = [nil, nil, 10, 14]
Show the correct program
var slots: [Int?] = [nil, nil, 10, 14]
var i = 18 % 4
while slots[i] != nil { i = (i + 1) % 4 }
print(i)Lab 48: Hash functions
Q0: What would Swift print?
What would Swift print?
struct Name: Hashable {
let first: String
let last: String
}
let people: Set = [Name(first: "Ada", last: "Lovelace"), Name(first: "Ada", last: "Lovelace"), Name(first: "Lovelace", last: "Ada")]
print(people.count)Show answer and explanation
Answer2
The synthesized Hashable combines first then last, in order, so swapping them
makes a different value, and the duplicate collapses into one element.
Q1: Hashing a composite
A Route from one city to another is the same route in either direction. Write
== and hash(into:) so that Route(from: "SFO", to: "TPE") equals
Route(from: "TPE", to: "SFO"), and check that a set of routes treats them as one.
Show solution
struct Route: Hashable {
let from: String
let to: String
private var ends: (String, String) {
from < to ? (from, to) : (to, from)
}
static func == (a: Route, b: Route) -> Bool {
a.ends == b.ends
}
func hash(into hasher: inout Hasher) {
hasher.combine(ends.0)
hasher.combine(ends.1)
}
}
let routes: Set = [Route(from: "SFO", to: "TPE"), Route(from: "TPE", to: "SFO"), Route(from: "SFO", to: "JFK")]
assert(routes.count == 2)
assert(Route(from: "A", to: "B").hashValue == Route(from: "B", to: "A").hashValue)Both == and hash(into:) use the same canonical form, the two cities in sorted
order, which guarantees that equal routes hash equally. Computing a canonical form
once and using it for both is the safest pattern for any custom equality.
Q2: The mutated key, measured
Show how often Lesson’s mutated-key bug hides: insert 1,000 Point objects into a
set, change each one’s x, and count how many contains still finds.
Show solution
final class Point: Hashable {
var x: Int
var y: Int
init(_ x: Int, _ y: Int) { self.x = x; self.y = y }
static func == (a: Point, b: Point) -> Bool { a.x == b.x && a.y == b.y }
func hash(into hasher: inout Hasher) {
hasher.combine(x)
hasher.combine(y)
}
}
let points = (0..<1_000).map { Point($0, $0) }
let set = Set(points)
for point in points { point.x += 1_000_000 }
let found = points.filter { set.contains($0) }.count
assert(found < 100) // most lookups miss; a few land in the right bucket by luck
assert(set.count == 1_000) // the objects are all still in the setA few lookups still succeed, the ones whose old and new hash codes happen to pick the same starting slot, which is why this bug appears and disappears between runs.
Q3: Identity hashing
Write a class Node that is Hashable by identity: two different nodes are
different even if their contents are equal, and changing a node’s contents does not
affect its hash. Use ObjectIdentifier.
Show solution
final class Node: Hashable {
var label: String
init(_ label: String) { self.label = label }
static func == (a: Node, b: Node) -> Bool { a === b }
func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(self))
}
}
let a = Node("x")
let b = Node("x")
var visited: Set = [a]
a.label = "changed"
assert(visited.contains(a) && !visited.contains(b))
visited.insert(b)
assert(visited.count == 2)For graph algorithms over objects, identity is usually what “visited” means. The object identifier never changes while the object lives, so mutation cannot break the set.
Q4: Linear probing and clusters
Using ProbingSet’s design, measure the average number of slots examined by a
successful contains at load factors of 0.25, 0.5, and 0.9, on 10,000 random keys.
Show solution
func averageProbes(load: Double, keys: Int) -> Double {
let size = Int(Double(keys) / load)
var slots = [Int?](repeating: nil, count: size)
func start(_ k: Int) -> Int { let h = k.hashValue % size; return h < 0 ? h + size : h }
var generator = SystemRandomNumberGenerator()
var inserted: [Int] = []
while inserted.count < keys {
let k = Int.random(in: 0..<Int.max, using: &generator)
var i = start(k)
while slots[i] != nil { i = (i + 1) % size }
slots[i] = k
inserted.append(k)
}
var probes = 0
for k in inserted {
var i = start(k)
probes += 1
while slots[i] != k { i = (i + 1) % size; probes += 1 }
}
return Double(probes) / Double(keys)
}
let low = averageProbes(load: 0.25, keys: 10_000)
let medium = averageProbes(load: 0.5, keys: 10_000)
let high = averageProbes(load: 0.9, keys: 10_000)
assert(low < 1.3 && medium < 2 && high > 3)Theory predicts about ½(1 + 1/(1 − α)) probes for a successful search at load α: about 1.17, 1.5, and 5.5. At 0.9, clusters make every search several times longer, which is why open-addressing tables resize well before they are full.
Q5 (optional): Rolling hashes
Find every position where a pattern occurs in a text, comparing hashes of each window of the text with the pattern’s hash, and updating the window’s hash in constant time as it slides: the Rabin–Karp algorithm.
Show solution
func occurrences(of pattern: String, in text: String) -> [Int] {
let p = Array(pattern.utf8), t = Array(text.utf8)
guard !p.isEmpty, p.count <= t.count else { return [] }
let base = 256, modulus = 1_000_000_007
var highest = 1
for _ in 1..<p.count { highest = highest * base % modulus }
var patternHash = 0, windowHash = 0
for i in 0..<p.count {
patternHash = (patternHash * base + Int(p[i])) % modulus
windowHash = (windowHash * base + Int(t[i])) % modulus
}
var result: [Int] = []
for start in 0...(t.count - p.count) {
if windowHash == patternHash && Array(t[start..<(start + p.count)]) == p {
result.append(start)
}
if start + p.count < t.count {
windowHash = (windowHash - Int(t[start]) * highest % modulus + modulus) % modulus
windowHash = (windowHash * base + Int(t[start + p.count])) % modulus
}
}
return result
}
assert(occurrences(of: "ana", in: "bananarama") == [1, 3])
assert(occurrences(of: "x", in: "abc") == [] && occurrences(of: "abc", in: "abc") == [0])Sliding the window removes the leading character’s contribution and adds the new one, so each step is constant time, and matching hashes are confirmed by comparing characters, since hashes can collide. Plagiarism detectors and file-sync tools use rolling hashes to find repeated blocks in huge inputs.
What’s next
Next lesson: tries, which store strings by their characters and answer questions about prefixes that neither hash tables nor search trees handle well.