Tutorial outline

Unit 1

  1. 01Getting started
  2. 02Names and functions
  3. 03Control
  4. 04Higher-order functions
  5. 05Environments and closures
  6. 06Functional abstraction
  7. 07Recursion
  8. 08Tree recursion
  1. D0Getting started
  2. D1Control and environment diagrams
  3. HW1Functions and control
  4. D2Higher-order functions
  5. HW2Higher-order functions
  6. P1Hog
  7. D3Recursion
  8. D4Tree recursion
  9. HW3Recursion

Unit 2

  1. 09Sequences
  2. 10Dictionaries, sets, and tuples
  3. 11Optionals
  4. 12Structures and enumerations
  5. 13Linked lists and trees
  6. 14Mutation and value semantics
  7. 15Classes and inheritance
  8. 16Protocols and generics
  9. 17Iterators and lazy sequences
  10. 18Efficiency and memoization
  1. HW4Sequences and containers
  2. P2Cats
  3. D5Trees
  4. HW5Recursive data and mutation
  5. D6Objects and classes
  6. HW6Classes and interfaces
  7. P3Ants vs. SomeBees
  8. D7Iterators and efficiency
  9. HW7Lazy sequences and efficiency

Unit 3

  1. 19Algebraic data types and pattern matching
  2. 20Writing an interpreter
  3. 21Error handling
  4. 22Concurrency with async and await
  5. 23Testing
  6. 24Building a Swift package
  1. D8Algebraic data types
  2. HW8Pattern matching
  3. D9Interpreters
  4. HW9Interpreters and errors
  5. P4Scheme
  6. D10Concurrency
  7. D11Testing
  8. HW10Concurrency and testing

Unit 4

  1. 25References, identity, and memory
  2. 26Drawing with SwiftUI
  3. 27Testing data structures
  4. 28IntLists and SLLists
  5. 29Doubly linked lists and deques
  6. 30Arrays from scratch
  7. 31Interface and implementation inheritance
  8. 32Iteration, equality, and ordering
  9. 33Copy-on-write collections
  1. D12Swift review
  2. D13References, classes, and arrays
  3. HW11Swift warm-up
  4. P5Particle Simulator
  5. D14IntLists and SLLists
  6. HW12IntLists
  7. P6LinkedListDeque
  8. D15DLLists, default implementations, and array lists
  9. P7ArrayDeque
  10. D16Comparables and iterators
  11. HW13Review I

Unit 5

  1. 34Asymptotic analysis
  2. 35Disjoint sets
  3. 36Analyzing recursion
  4. 37Amortized analysis and the limits of big O
  5. 38Sets, maps, and binary search trees
  6. 39B-trees
  7. 40Left-leaning red-black trees
  8. 41Heaps and priority queues
  1. D17Asymptotics and disjoint sets
  2. P8Percolation
  3. D18Asymptotics II
  4. HW14Asymptotic analysis
  5. D19BSTs, B-trees, and LLRBs
  6. HW15BSTMap

Unit 6

  1. 42Data-driven apps with SwiftUI
  2. 43Tree and graph traversals
  3. 44Graph implementations
  4. 45Shortest paths: Dijkstra and A*
  5. 46Minimum spanning trees
  6. 47DAGs, topological sort, and reductions
  1. D20Tree traversals and graphs
  2. P9NGordNet
  3. D21Shortest paths and MSTs

Unit 7

  1. 48Hash tables
  2. 49Hash functions
  3. 50Tries and prefix operations
  4. 51Software engineering: managing complexity
  5. 52Games with SwiftUI
  6. 53Designing a world
  7. 54Basic sorts
  8. 55Quicksort and selection
  9. 56The limits of sorting
  10. 57Radix sorts
  11. 58Compression and complexity
  12. 59Computing, society, and what comes next
  1. D22Hashing and tries
  2. HW16Review II
  3. D23Hashing and tries, revisited
  4. P10Build Your Own World
  5. D24Sorting
  6. HW17HashMap
  7. D25Sorting II
  8. HW18LLRB set
  9. HW19Final review

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
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:

  1. 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.
  2. Deterministic within a run: the same value must hash the same every time it is asked.
  3. 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 hashValue expecting it to mean the same thing later, or in another process. It is not an identifier.
  • Iterating over a Set or Dictionary can 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)

Type Error if running it would crash. For several lines of output, put each on its own line.

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.

  1. var i = 18 % 4
  2. while slots[i] != nil { i = (i + 1) % 4 }
  3. print(i)
  4. 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)

Type Error if running it would crash. For several lines of output, put each on its own line.

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 set

A 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.