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

HashMap

Implement a complete generic hash map with separate chaining: configurable initial size and load factor, get, put, remove, resizing, iteration over keys, and a randomized test against Dictionary.

This homework goes with Lessons 48 and 49, like CS61B’s HashMap homework. You will build a map from scratch, one step at a time, and test it against Swift’s own Dictionary. Put everything in hw17.swift.

Q1: The skeleton

Write HashMap<Key: Hashable, Value> as a structure storing an array of buckets, each an array of key–value pairs. It takes an initial number of buckets (default 16) and a maximum load factor (default 0.75) in its initializer. Write count, get(_:), and put(_:_:), without resizing for now.

Show solution
struct HashMap<Key: Hashable, Value> {
    private var buckets: [[(key: Key, value: Value)]]
    private let maxLoad: Double
    private(set) var count = 0

    init(initialSize: Int = 16, maxLoad: Double = 0.75) {
        precondition(initialSize > 0 && maxLoad > 0)
        buckets = Array(repeating: [], count: initialSize)
        self.maxLoad = maxLoad
    }

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

    func get(_ key: Key) -> Value? {
        buckets[index(for: key)].first { $0.key == key }?.value
    }

    mutating func put(_ key: Key, _ value: Value) {
        let b = index(for: key)
        if let i = buckets[b].firstIndex(where: { $0.key == key }) {
            buckets[b][i].value = value
        } else {
            buckets[b].append((key, value))
            count += 1
        }
    }
}

var map = HashMap<String, Int>(initialSize: 4)
map.put("a", 1)
map.put("b", 2)
map.put("a", 3)
assert(map.count == 2 && map.get("a") == 3 && map.get("z") == nil)

Q2: Resizing

Add resizing to put: when adding a new key would make the load factor exceed maxLoad, double the number of buckets and rehash every pair. Expose bucketCount and check that it grows as expected.

Show solution
struct HashMap<Key: Hashable, Value> {
    private var buckets: [[(key: Key, value: Value)]]
    private let maxLoad: Double
    private(set) var count = 0

    init(initialSize: Int = 16, maxLoad: Double = 0.75) {
        buckets = Array(repeating: [], count: initialSize)
        self.maxLoad = maxLoad
    }

    var bucketCount: Int { buckets.count }

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

    func get(_ key: Key) -> Value? {
        buckets[index(for: key, in: buckets.count)].first { $0.key == key }?.value
    }

    mutating func put(_ key: Key, _ value: Value) {
        let b = index(for: key, in: buckets.count)
        if let i = buckets[b].firstIndex(where: { $0.key == key }) {
            buckets[b][i].value = value
            return
        }
        if Double(count + 1) / Double(buckets.count) > maxLoad {
            resize(to: buckets.count * 2)
        }
        buckets[index(for: key, in: buckets.count)].append((key, value))
        count += 1
    }

    private mutating func resize(to size: Int) {
        var fresh: [[(key: Key, value: Value)]] = Array(repeating: [], count: size)
        for pair in buckets.joined() {
            fresh[index(for: pair.key, in: size)].append(pair)
        }
        buckets = fresh
    }
}

var map = HashMap<Int, Int>(initialSize: 4, maxLoad: 1)
for n in 1...4 { map.put(n, n) }
assert(map.bucketCount == 4)
map.put(5, 5)
assert(map.bucketCount == 8)
for n in 6...100 { map.put(n, n) }
assert(map.bucketCount == 128 && (1...100).allSatisfy { map.get($0) == $0 })

The bucket index must be recomputed after a resize: the same key belongs in a different bucket once the bucket count changes.

Q3: Removing and iterating

Add remove(_:), which returns the removed value, removeAll(), and conformance to Sequence, iterating over (key, value) pairs in bucket order. Then add keys, a sorted array of keys when Key is Comparable.

Show solution
struct HashMap<Key: Hashable, Value> {
    fileprivate var buckets: [[(key: Key, value: Value)]]
    private let maxLoad: Double
    private(set) var count = 0

    init(initialSize: Int = 16, maxLoad: Double = 0.75) {
        buckets = Array(repeating: [], count: initialSize)
        self.maxLoad = maxLoad
    }

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

    func get(_ key: Key) -> Value? {
        buckets[index(for: key, in: buckets.count)].first { $0.key == key }?.value
    }

    mutating func put(_ key: Key, _ value: Value) {
        let b = index(for: key, in: buckets.count)
        if let i = buckets[b].firstIndex(where: { $0.key == key }) {
            buckets[b][i].value = value
            return
        }
        if Double(count + 1) / Double(buckets.count) > maxLoad {
            let size = buckets.count * 2
            var fresh: [[(key: Key, value: Value)]] = Array(repeating: [], count: size)
            for pair in buckets.joined() { fresh[index(for: pair.key, in: size)].append(pair) }
            buckets = fresh
        }
        buckets[index(for: key, in: buckets.count)].append((key, value))
        count += 1
    }

    @discardableResult
    mutating func remove(_ key: Key) -> Value? {
        let b = index(for: key, in: buckets.count)
        guard let i = buckets[b].firstIndex(where: { $0.key == key }) else { return nil }
        count -= 1
        return buckets[b].remove(at: i).value
    }

    mutating func removeAll() {
        buckets = Array(repeating: [], count: buckets.count)
        count = 0
    }
}

extension HashMap: Sequence {
    func makeIterator() -> FlattenSequence<[[(key: Key, value: Value)]]>.Iterator {
        buckets.joined().makeIterator()
    }
}

extension HashMap where Key: Comparable {
    var keys: [Key] { map(\.key).sorted() }
}

var map = HashMap<String, Int>()
for (i, word) in ["pear", "fig", "kiwi", "apple"].enumerated() { map.put(word, i) }
assert(map.remove("fig") == 1 && map.remove("fig") == nil)
assert(map.keys == ["apple", "kiwi", "pear"] && map.count == 3)
assert(map.reduce(0) { $0 + $1.value } == 0 + 2 + 3)
map.removeAll()
assert(map.count == 0 && map.get("pear") == nil)

Iteration reuses the standard library: joined() flattens the buckets lazily, and its iterator becomes the map’s. The order is the bucket order, which depends on the hash seed and changes between runs, so keys sorts.

Q4: The randomized test

Test the map against Dictionary with 50,000 random put, get, and remove operations on a small key range, checking the count after each, and the contents at the end.

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

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

    func get(_ key: Key) -> Value? {
        buckets[index(for: key, in: buckets.count)].first { $0.key == key }?.value
    }

    mutating func put(_ key: Key, _ value: Value) {
        let b = index(for: key, in: buckets.count)
        if let i = buckets[b].firstIndex(where: { $0.key == key }) { buckets[b][i].value = value; return }
        if Double(count + 1) / Double(buckets.count) > 0.75 {
            let size = buckets.count * 2
            var fresh: [[(key: Key, value: Value)]] = Array(repeating: [], count: size)
            for pair in buckets.joined() { fresh[index(for: pair.key, in: size)].append(pair) }
            buckets = fresh
        }
        buckets[index(for: key, in: buckets.count)].append((key, value))
        count += 1
    }

    @discardableResult
    mutating func remove(_ key: Key) -> Value? {
        let b = index(for: key, in: buckets.count)
        guard let i = buckets[b].firstIndex(where: { $0.key == key }) else { return nil }
        count -= 1
        return buckets[b].remove(at: i).value
    }

    var pairs: [(key: Key, value: Value)] { Array(buckets.joined()) }
}

var map = HashMap<Int, Int>()
var reference: [Int: Int] = [:]
var generator = SystemRandomNumberGenerator()
for step in 0..<50_000 {
    let key = Int.random(in: 0..<1_000, using: &generator)
    switch Int.random(in: 0..<3, using: &generator) {
    case 0:
        map.put(key, step)
        reference[key] = step
    case 1:
        assert(map.get(key) == reference[key])
    default:
        assert(map.remove(key) == reference.removeValue(forKey: key))
    }
    assert(map.count == reference.count)
}
assert(Dictionary(uniqueKeysWithValues: map.pairs.map { ($0.key, $0.value) }) == reference)

A key range of 1,000 with 50,000 operations makes replacements and removals of present keys frequent. The final comparison turns the map into a Dictionary and compares whole contents, which catches lost or duplicated pairs that individual lookups might miss.

Q5 (optional): Pluggable buckets

CS61B’s version lets subclasses choose the bucket type: arrays, linked lists, or even trees. Make the bucket a generic parameter conforming to a small protocol, and provide two implementations: an array bucket and a sorted-array bucket that uses binary search for Comparable keys.

Show solution
protocol Bucket<Key, Value> {
    associatedtype Key: Hashable
    associatedtype Value
    init()
    func get(_ key: Key) -> Value?
    mutating func put(_ key: Key, _ value: Value) -> Bool       // true if the key was new
    var pairs: [(key: Key, value: Value)] { get }
}

struct ArrayBucket<Key: Hashable, Value>: Bucket {
    private(set) var pairs: [(key: Key, value: Value)] = []
    func get(_ key: Key) -> Value? { pairs.first { $0.key == key }?.value }
    mutating func put(_ key: Key, _ value: Value) -> Bool {
        if let i = pairs.firstIndex(where: { $0.key == key }) { pairs[i].value = value; return false }
        pairs.append((key, value)); return true
    }
}

struct SortedBucket<Key: Hashable & Comparable, Value>: Bucket {
    private(set) var pairs: [(key: Key, value: Value)] = []
    private func position(_ key: Key) -> Int {
        var (low, high) = (0, pairs.count)
        while low < high {
            let mid = (low + high) / 2
            if pairs[mid].key < key { low = mid + 1 } else { high = mid }
        }
        return low
    }
    func get(_ key: Key) -> Value? {
        let i = position(key)
        return i < pairs.count && pairs[i].key == key ? pairs[i].value : nil
    }
    mutating func put(_ key: Key, _ value: Value) -> Bool {
        let i = position(key)
        if i < pairs.count && pairs[i].key == key { pairs[i].value = value; return false }
        pairs.insert((key, value), at: i); return true
    }
}

struct Map<B: Bucket> {
    private var buckets = Array(repeating: B(), count: 8)
    private(set) var count = 0
    private func index(_ key: B.Key) -> Int { let h = key.hashValue % buckets.count; return h < 0 ? h + buckets.count : h }
    func get(_ key: B.Key) -> B.Value? { buckets[index(key)].get(key) }
    mutating func put(_ key: B.Key, _ value: B.Value) {
        if buckets[index(key)].put(key, value) {
            count += 1
            if count > buckets.count {
                let pairs = buckets.flatMap(\.pairs)
                buckets = Array(repeating: B(), count: buckets.count * 2)
                for p in pairs { _ = buckets[index(p.key)].put(p.key, p.value) }
            }
        }
    }
}

var a = Map<ArrayBucket<Int, String>>()
var s = Map<SortedBucket<Int, String>>()
for n in 0..<500 { a.put(n, "\(n)"); s.put(n, "\(n)") }
assert(a.count == 500 && s.count == 500 && a.get(321) == "321" && s.get(321) == "321" && s.get(999) == nil)

The map is written once against the protocol, and the bucket type is chosen when the map is created: Lesson 31’s interfaces used for performance tuning. With a good hash, buckets hold one or two pairs and the choice hardly matters; with a bad hash, sorted buckets turn a linear scan into a binary search.