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

Final review

Exam-style review of the last third of the course: heaps, shortest paths, minimum spanning trees, hashing, sorting and its lower bound, radix sorts, and compression.

CS61B ends with a review homework before the final. This one covers the whole second half of the course, with an emphasis on Lessons 45 to 58. Try every problem on paper before opening its solution.

Q1: What would Swift print?

What would Swift print?

let edges = [(0, 1, 4), (0, 2, 1), (1, 2, 2), (1, 3, 5), (2, 3, 8), (3, 4, 3), (2, 4, 9)]
var inTree: Set<Int> = [0]
var order: [Int] = []
var total = 0
while inTree.count < 5 {
    let e = edges.filter { inTree.contains($0.0) != inTree.contains($0.1) }
                 .min { $0.2 < $1.2 }!
    let v = inTree.contains(e.0) ? e.1 : e.0
    inTree.insert(v)
    order.append(v)
    total += e.2
}
print(order, total)

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

Show answer and explanation

Answer[2, 1, 3, 4] 11

This is Prim’s algorithm, written simply: each step adds the cheapest edge crossing the cut between the tree and the rest. From 0 it takes 0–2 (1), then 2–1 (2), then 1–3 (5), the cheapest way to reach 3, and finally 3–4 (3). The total is 1 + 2 + 5 + 3 = 11.

Q2: Kruskal on the same graph

Run Kruskal’s algorithm on the graph of Q1. List the weights of the edges it adds, in order, and name each edge it skips before finishing, with the reason.

Show solution

Sorted by weight: 0–2 (1), 1–2 (2), 3–4 (3), 0–1 (4), 1–3 (5), 2–3 (8), 2–4 (9).

  • Adds 1, 2, and 3.
  • Skips 0–1 (4): 0 and 1 are already connected through 2, so it would close a cycle.
  • Adds 5 (1–3), joining 2 with 4. All five vertices are connected; the remaining edges are skipped for the same reason.

The added weights are 1, 2, 3, 5, total 11: the same tree as Prim’s, as it must be, because all the weights are distinct and the MST is then unique.

let edges = [(0, 1, 4), (0, 2, 1), (1, 2, 2), (1, 3, 5), (2, 3, 8), (3, 4, 3), (2, 4, 9)]
var parent = Array(0..<5)
func find(_ x: Int) -> Int {
    var x = x
    while parent[x] != x { x = parent[x] }
    return x
}
var added: [Int] = []
for (u, v, w) in edges.sorted(by: { $0.2 < $1.2 }) {
    let (a, b) = (find(u), find(v))
    if a != b {
        parent[a] = b
        added.append(w)
    }
}
assert(added == [1, 2, 3, 5])

Q3: Huffman coding

Characters appear with these frequencies: a 45, b 13, c 12, d 16, e 9, f 5. Build a Huffman code. How many bits does each character get, and how many bits does the whole text of 100 characters take? How does that compare with a fixed-length code?

Show solution

Merging the two smallest trees each time: e + f = 14; c + b = 25; 14 + d = 30; 25 + 30 = 55; a + 55 = 100. The code lengths are a: 1, b, c, d: 3, and e, f: 4. The text takes 45·1 + (13 + 12 + 16)·3 + (9 + 5)·4 = 224 bits. A fixed-length code needs 3 bits for 6 characters: 300 bits. Huffman saves a quarter.

let frequency: [Character: Int] = ["a": 45, "b": 13, "c": 12, "d": 16, "e": 9, "f": 5]
var trees: [(weight: Int, characters: [Character])] = frequency.map { ($0.value, [$0.key]) }
var length: [Character: Int] = [:]
while trees.count > 1 {
    trees.sort { $0.weight < $1.weight }
    let (x, y) = (trees.removeFirst(), trees.removeFirst())
    for c in x.characters + y.characters { length[c, default: 0] += 1 }   // one level deeper
    trees.append((x.weight + y.weight, x.characters + y.characters))
}
assert(length == ["a": 1, "b": 3, "c": 3, "d": 3, "e": 4, "f": 4])
assert(frequency.reduce(0) { $0 + $1.value * length[$1.key]! } == 224)

Q4: Choosing algorithms

For each task, name the algorithm or data structure and its running time.

  1. The 100 largest of 10⁹ numbers arriving one at a time, with little memory.
  2. Shortest driving routes between two cities in a road network, with a good estimate of the remaining distance.
  3. The order to take courses given their prerequisites.
  4. Removing duplicates from 10⁷ strings.
  5. Sorting 10⁸ 32-bit integers.
  6. Cheapest set of cables connecting all the buildings on a campus.
Show solution
  1. A min-heap of size 100: keep the 100 largest so far, replacing the minimum when a larger number arrives. Θ(N log 100) time and Θ(100) memory.
  2. A* with the straight-line distance as heuristic (Lesson 45): Dijkstra’s O((V + E) log V) at worst, usually far fewer vertices explored.
  3. Topological sort (Lesson 47): Θ(V + E); it also detects a cycle, which makes the courses impossible.
  4. A hash set: expected Θ(N L) for N strings of length L.
  5. LSD radix sort on bytes: 4 passes, Θ(4(N + 256)) = Θ(N).
  6. A minimum spanning tree, with Kruskal or Prim: Θ(E log E) or Θ(E log V).

Q5: True or false?

  1. Dijkstra’s algorithm works with negative edge weights if no cycle is negative.
  2. Every comparison sort takes Ω(N log N) time on every input.
  3. The heaviest edge in a cycle is never in any minimum spanning tree, if weights are distinct.
  4. A hash table’s worst-case lookup is Θ(N).
  5. No lossless compression algorithm can shrink every file.
  6. Heapsort is stable.
Show solution
  1. False. Dijkstra finalizes a vertex when it leaves the queue; a negative edge discovered later could still make its path shorter. (Bellman-Ford handles negative weights.)
  2. False. The bound is for the worst case. Insertion sort takes Θ(N) on a sorted input.
  3. True. That is the cycle property: replacing it with another edge of the cycle always gives a lighter spanning tree.
  4. True. If every key hashes to the same bucket, a lookup scans all of them. The expected Θ(1) depends on a good spread.
  5. True. There are 2ᴺ files of N bits and only 2ᴺ − 1 shorter ones, so some file must stay the same length or grow (Lesson 58’s counting argument).
  6. False. Moving the maximum to the end jumps it past equal items. For example, heapifying [1a, 1b] keeps 1a at the root, which is then moved to the end: [1b, 1a].

Q6: Exam-level: the shortest path tree

A graph has a shortest path tree from s computed with Dijkstra. Then every edge weight is doubled. Is the tree still a shortest path tree? What if 1 is added to every weight instead?

Show solution
  • Doubling: yes. Every path’s length doubles, so the order of all path lengths is unchanged, and the shortest ones stay the shortest.
  • Adding 1: not necessarily. A path with k edges grows by k, so paths with many edges are penalized. Counterexample: the path s–a–t with weights 1 and 1 (length 2) and a direct edge s–t with weight 2.5. Before, s–a–t wins, 2 against 2.5. After adding 1, s–a–t has length 4 and s–t has 3.5, so the direct edge wins and the tree changes.