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

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.

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

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

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:

  1. Make Student a structure. The set holds its own copy, which cannot be changed from outside; to update, remove the old value and insert the new one.
  2. 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

  1. 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?
  2. Why must a hash table’s bucket count grow multiplicatively?
  3. 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. Θ(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.
  2. 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.
  3. 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.