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 tables

Constant-time lookup: data-indexed arrays, turning keys into numbers, integer overflow, collisions, separate chaining, load factor and resizing, and why a hash table is only as good as the spread of its hash codes.

CS61B
Hashing I · Textbook Ch. 24
Documentation
Hashable · Dictionary

Search trees find a key in Θ(log N) time by comparing. Swift’s Set and Dictionary do better: about the same time whether they hold ten items or ten million, and their keys need not be comparable at all. This lesson, following CS61B’s two hashing lectures, builds that structure, the hash table, from a simple idea that almost works.

Data-indexed arrays

To store a set of small non-negative integers, use an array of booleans: present[k] says whether k is in the set. Adding, removing, and checking are each one array access: constant time, no comparisons. The idea is to use the key itself as the position.

It has two problems. The array must be as large as the largest possible key, and most keys are not small integers. What position would the string "cat" go in?

Turning keys into numbers

Any value can be turned into a number. A lowercase word can be read as a number in base 27, with a = 1, b = 2, …, z = 26, just as “215” is 2 × 10² + 1 × 10 + 5:

func base27(_ word: String) -> Int {
    word.reduce(0) { value, letter in
        value * 27 + Int(letter.asciiValue! - Character("a").asciiValue! + 1)
    }
}

print(base27("a"), base27("cat"), base27("bee"))   // 1 2234 1598

Different words give different numbers, so this is a perfect representation. But the numbers grow fast: a 13-letter word exceeds 2⁶³, the largest Int, and the arithmetic overflows. Swift traps on overflow instead of silently wrapping, so this function crashes on long words. With the overflow operators from the Swift book’s advanced operators chapter, &* and &+, the arithmetic wraps around instead, keeping the lowest 64 bits:

func wrappingHash(_ word: String) -> Int {
    word.utf8.reduce(0) { $0 &* 31 &+ Int($1) }
}

let long = "pneumonoultramicroscopicsilicovolcanoconiosis"
print(wrappingHash(long) == wrappingHash(long), wrappingHash("cat") == wrappingHash("act"))   // true false

Now every string gets an Int, which is called its hash code, but different strings can get the same one: there are far more strings than 64-bit numbers. Two keys with the same hash code, or, as we will see, the same position, are a collision, and collisions cannot be avoided. The rest of the design is about living with them.

Separate chaining

Use an array of buckets, far fewer than the possible hash codes. A key goes in bucket hash % bucketCount (made non-negative, since hash codes can be negative). Each bucket holds a small list of the keys that landed there. To find a key, compute its bucket and search that one list with ==:

struct ChainedSet<Element: Hashable> {
    private var buckets: [[Element]] = Array(repeating: [], count: 8)
    private(set) var count = 0

    private func bucket(for item: Element) -> Int {
        let hash = item.hashValue
        return ((hash % buckets.count) + buckets.count) % buckets.count
    }

    func contains(_ item: Element) -> Bool {
        buckets[bucket(for: item)].contains(item)
    }

    mutating func insert(_ item: Element) {
        guard !contains(item) else { return }
        buckets[bucket(for: item)].append(item)
        count += 1
        if count > 3 * buckets.count / 4 {        // load factor above 0.75
            resize(to: buckets.count * 2)
        }
    }

    mutating func remove(_ item: Element) {
        let b = bucket(for: item)
        if let i = buckets[b].firstIndex(of: item) {
            buckets[b].remove(at: i)
            count -= 1
        }
    }

    private mutating func resize(to newCount: Int) {
        let items = buckets.joined()
        buckets = Array(repeating: [], count: newCount)
        for item in items {
            buckets[bucket(for: item)].append(item)
        }
    }

    var longestBucket: Int { buckets.map(\.count).max()! }
    var bucketCount: Int { buckets.count }
}

var words = ChainedSet<String>()
for n in 0..<10_000 {
    words.insert("word\(n)")
}
words.remove("word7")
print(words.count, words.contains("word42"), words.contains("word7"), words.bucketCount)   // 9999 true false 16384

Two numbers decide the speed. The load factor is the number of items divided by the number of buckets: the average bucket length. Keeping it below a constant, here 0.75, by doubling the buckets when it gets too high, keeps the average bucket short. Resizing moves every item to its new bucket, which is Θ(N), but, as with Lesson 30’s array list, doubling makes it amortized constant per insertion.

The second number is how evenly the hash codes spread items among buckets. With a good spread and a bounded load factor, each operation examines a constant number of items on average: Θ(1), for any number of items.

What would Swift print?

let bucketCount = 8
let hashes = [13, -3, 21, 5, 16]
print(hashes.map { (($0 % bucketCount) + bucketCount) % bucketCount })

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

Show answer and explanation

Answer[5, 5, 5, 5, 0]

13, −3, 21, and 5 all land in bucket 5: in Swift, −3 % 8 is −3, and adding 8 before the second % makes it 5. Four of five items in one bucket is a bad spread, and it comes from the hash codes, not the table: they all differ by multiples of 8.

A bad hash code ruins everything

The Θ(1) depends entirely on the spread. If every key has the same hash code, every key lands in the same bucket, and the table degrades into a single linked list:

struct BadKey: Hashable {
    let value: Int
    func hash(into hasher: inout Hasher) {
        hasher.combine(0)                  // every key hashes the same
    }
}

let clock = ContinuousClock()
var good = Set<Int>()
var bad = Set<BadKey>()
let goodTime = clock.measure { for n in 0..<2_000 { good.insert(n) } }
let badTime = clock.measure { for n in 0..<2_000 { bad.insert(BadKey(value: n)) } }
print(good.count == bad.count, badTime > goodTime * 10)   // true true

Both sets are correct: == still distinguishes the keys. But every insertion into the bad set compares against everything already there, so inserting N keys takes Θ(N²). A correct but poor hash(into:) is a performance bug that tests of correctness never catch. Lesson 49 is about writing good ones.

Java versus Swift

CS61B uses Java, where every object has an int hashCode() method, and a HashMap computes hashCode() % buckets directly. Swift separates the two jobs:

  • A type conforming to Hashable implements hash(into:), feeding its identity-defining parts to a Hasher, the same parts == compares (Lesson 32).
  • The Hasher, provided by the standard library, turns those parts into a well-mixed hash value with a strong algorithm, so individual types cannot get the mixing wrong.

hashValue is derived from hash(into:); you rarely need it directly, and should never implement it yourself anymore.

Put the lines in order

Put the lines in order so the program prints [[4, 8], [5], [], [3]].

  1. var buckets: [[Int]] = Array(repeating: [], count: 4)
  2. for key in [4, 5, 8, 3] {
  3. buckets[key % 4].append(key)
  4. print(buckets)
  5. }

Show the correct program
var buckets: [[Int]] = Array(repeating: [], count: 4)
for key in [4, 5, 8, 3] {
    buckets[key % 4].append(key)
}
print(buckets)

Lab 47: Hash tables

Q0: What would Swift print?

What would Swift print?

func code(_ word: String) -> Int {
    word.utf8.reduce(0) { $0 + Int($1) }
}
print(code("cat") == code("act"), code("cat") == code("dog"))

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

Show answer and explanation

Answertrue false

Adding the letter codes ignores their order, so every anagram collides. A good hash of a sequence must depend on the order, which is why multiplying by 31 before adding each character, as in the lesson, works better.

Q1: A hash map

Write ChainedMap<Key: Hashable, Value> with separate chaining: buckets of key–value pairs, subscript(key:) for getting and setting (setting nil removes), count, and resizing at load factor 0.75. Test it against Dictionary with random operations.

Show solution
struct ChainedMap<Key: Hashable, Value> {
    private var buckets: [[(key: Key, value: Value)]] = Array(repeating: [], count: 8)
    private(set) var count = 0

    private func index(for key: Key) -> Int {
        let h = key.hashValue % buckets.count
        return h < 0 ? h + buckets.count : h
    }

    subscript(key: Key) -> Value? {
        get {
            buckets[index(for: key)].first { $0.key == key }?.value
        }
        set {
            let b = index(for: key)
            if let i = buckets[b].firstIndex(where: { $0.key == key }) {
                if let newValue {
                    buckets[b][i].value = newValue
                } else {
                    buckets[b].remove(at: i)
                    count -= 1
                }
            } else if let newValue {
                buckets[b].append((key, newValue))
                count += 1
                if count * 4 > buckets.count * 3 {
                    let pairs = buckets.joined()
                    buckets = Array(repeating: [], count: buckets.count * 2)
                    for pair in pairs { buckets[index(for: pair.key)].append(pair) }
                }
            }
        }
    }
}

var map = ChainedMap<Int, String>()
var reference: [Int: String] = [:]
var generator = SystemRandomNumberGenerator()
for step in 0..<20_000 {
    let key = Int.random(in: 0..<2_000, using: &generator)
    switch Int.random(in: 0..<3, using: &generator) {
    case 0:
        map[key] = "\(step)"
        reference[key] = "\(step)"
    case 1:
        map[key] = nil
        reference[key] = nil
    default:
        assert(map[key] == reference[key])
    }
    assert(map.count == reference.count)
}

The subscript’s setter handles four cases: replace, remove, insert, and removing a key that is not there, which does nothing. Using nil to mean “remove” is exactly how Dictionary’s subscript works.

Q2: Load factor and bucket length

Insert 100,000 integers into ChainedSets that resize at load factors 0.75, 2, and 8, and compare the longest bucket and the average length of the buckets examined by contains.

Show solution
struct ChainedSet {
    private var buckets: [[Int]] = Array(repeating: [], count: 8)
    private(set) var count = 0
    let maxLoad: Double

    init(maxLoad: Double) { self.maxLoad = maxLoad }

    private func index(_ x: Int) -> Int {
        let h = x.hashValue % buckets.count
        return h < 0 ? h + buckets.count : h
    }

    mutating func insert(_ x: Int) {
        buckets[index(x)].append(x)
        count += 1
        if Double(count) > maxLoad * Double(buckets.count) {
            let items = buckets.joined()
            buckets = Array(repeating: [], count: buckets.count * 2)
            for item in items { buckets[index(item)].append(item) }
        }
    }

    var longest: Int { buckets.map(\.count).max()! }
    /// The average length of the bucket a random item is in.
    var averageSearch: Double {
        Double(buckets.map { $0.count * $0.count }.reduce(0, +)) / Double(count)
    }
}

var results: [(Double, Int, Double)] = []
for load in [0.75, 2, 8] {
    var set = ChainedSet(maxLoad: load)
    for n in 0..<100_000 { set.insert(n) }
    results.append((load, set.longest, set.averageSearch))
}
assert(results[0].2 < results[1].2 && results[1].2 < results[2].2)
assert(results.allSatisfy { $0.1 < 40 })

The average search length grows with the load factor, but stays a constant: about 1 + load, whatever N is. The longest bucket stays small too, since the Hasher spreads even consecutive integers evenly. A higher load factor saves memory and costs time: the classic trade-off, which is why real tables keep it around 0.75.

Q3: A spelling checker

Load a word list into a Set<String> and write misspelled(_:), which returns the words of a text that are not in the list. Compare with an array-based version for a list of 50,000 words.

Show solution
let dictionary = (0..<50_000).map { "word\($0)" }
let lookup = Set(dictionary)

func misspelled(_ text: [String], in words: Set<String>) -> [String] {
    text.filter { !words.contains($0) }
}

func misspelledSlowly(_ text: [String], in words: [String]) -> [String] {
    text.filter { !words.contains($0) }
}

let text = ["word12", "wrod3", "word49999", "ward7"]
let clock = ContinuousClock()
var fast: [String] = []
var slow: [String] = []
let fastTime = clock.measure { fast = misspelled(text, in: lookup) }
let slowTime = clock.measure { slow = misspelledSlowly(text, in: dictionary) }
assert(fast == ["wrod3", "ward7"] && slow == fast)
assert(slowTime > fastTime)

The set answers each check in constant time; the array scans up to 50,000 words for each misspelling. For a whole book, the difference is between instant and minutes.

Q4 (optional): Counting collisions

Write a function that computes, for a list of keys and a bucket count, how many keys land in the fullest bucket. Compare three hash functions on 10,000 words: summing letter codes, wrappingHash from the lesson, and Swift’s hashValue, using 1,024 buckets.

Show solution
func fullest(_ keys: [String], buckets: Int, hash: (String) -> Int) -> Int {
    var counts = Array(repeating: 0, count: buckets)
    for key in keys {
        let h = hash(key) % buckets
        counts[h < 0 ? h + buckets : h] += 1
    }
    return counts.max()!
}

let keys = (0..<10_000).map { "user\($0)" }
let sum = fullest(keys, buckets: 1024) { $0.utf8.reduce(0) { $0 + Int($1) } }
let polynomial = fullest(keys, buckets: 1024) { $0.utf8.reduce(0) { $0 &* 31 &+ Int($1) } }
let swift = fullest(keys, buckets: 1024) { $0.hashValue }
assert(sum > 100)                 // sums of similar strings cluster in a few buckets
assert(polynomial < sum && swift < 40)

Keys that look alike, like user0 to user9999, are exactly what real programs store, and a weak hash maps them to a handful of buckets. The polynomial hash spreads them far better, and Swift’s Hasher, which mixes bits thoroughly, spreads them about as evenly as random numbers would.

What’s next

Next lesson: what makes a hash function good, how Swift’s Hasher works, why its results change on every run, and a second way to resolve collisions.