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

DAGs, topological sort, and reductions

Directed acyclic graphs and dependency orders, topological sort by depth-first postorder and by in-degrees, shortest and longest paths in a DAG even with negative weights, and solving one problem by reducing it to another.

CS61B
Directed Acyclic Graphs · Textbook Ch. 23
Swift book
Functions

Many problems are about dependencies: a course needs its prerequisites, a file needs the files it imports compiled first, a recipe needs the dough to rise before baking. Dependencies form a directed graph, and it had better have no cycles, or nothing could ever start. This lesson, following CS61B’s DAGs lecture, puts such graphs in order, finds paths in them faster than Dijkstra can, and ends with the idea that ties much of algorithms together: reduction.

Directed acyclic graphs

A directed acyclic graph (DAG) is a directed graph with no directed cycle. Every tree is a DAG, if its edges point away from the root, but DAGs are more general: a vertex can have several parents.

A topological order of a DAG lists its vertices so that every edge goes from an earlier vertex to a later one: every task after all the tasks it depends on. A graph has a topological order if and only if it is a DAG, and a DAG usually has many.

Run DFS from every unvisited vertex, and record each vertex when its visit finishes, after all its descendants: postorder. Reversed, the postorder is a topological order.

func topologicalOrder(_ adjacent: [[Int]]) -> [Int] {
    var visited = Array(repeating: false, count: adjacent.count)
    var postorder: [Int] = []
    func visit(_ v: Int) {
        visited[v] = true
        for w in adjacent[v] where !visited[w] {
            visit(w)
        }
        postorder.append(v)
    }
    for v in adjacent.indices where !visited[v] {
        visit(v)
    }
    return postorder.reversed()
}

// 0: shirt, 1: tie, 2: jacket, 3: belt, 4: trousers, 5: shoes, 6: socks
let dressing = [[1, 3], [2], [], [2], [3, 5], [], [5]]
let order = topologicalOrder(dressing)
let position = Dictionary(uniqueKeysWithValues: order.enumerated().map { ($1, $0) })
let valid = dressing.indices.allSatisfy { v in dressing[v].allSatisfy { position[v]! < position[$0]! } }
print(order, valid)   // [6, 4, 5, 0, 3, 1, 2] true

Why it works: when v finishes, every vertex reachable from v has already finished, because DFS visited them before finishing v, or they had finished even earlier. So in the postorder each vertex comes after everything it points to, and reversing puts it before. The whole sort is one DFS: Θ(V + E).

Topological sort by in-degree

A second algorithm, due to Kahn, peels the graph from the top. A vertex with no incoming edges, in-degree 0, can go first. Remove it, which lowers its neighbors’ in-degrees, and repeat:

func kahn(_ adjacent: [[Int]]) -> [Int]? {
    var inDegree = Array(repeating: 0, count: adjacent.count)
    for neighbors in adjacent {
        for w in neighbors { inDegree[w] += 1 }
    }
    var ready = adjacent.indices.filter { inDegree[$0] == 0 }
    var order: [Int] = []
    while let v = ready.popLast() {
        order.append(v)
        for w in adjacent[v] {
            inDegree[w] -= 1
            if inDegree[w] == 0 { ready.append(w) }
        }
    }
    return order.count == adjacent.count ? order : nil     // leftovers mean a cycle
}

print(kahn([[1, 3], [2], [], [2], [3, 5], [], [5]])!, kahn([[1], [2], [0]]) as Any)
// [6, 4, 5, 0, 3, 1, 2] nil

If a cycle exists, its vertices never reach in-degree 0, and the algorithm stops early: Kahn’s algorithm detects cycles for free, which is why build systems and package managers use it to report circular dependencies.

What would Swift print?

let adjacent = [[2], [2], [3], []]
var inDegree = [0, 0, 0, 0]
for list in adjacent {
    for w in list { inDegree[w] += 1 }
}
print(inDegree, adjacent.indices.filter { inDegree[$0] == 0 })

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

Show answer and explanation

Answer[0, 0, 2, 1] [0, 1]

Vertex 2 has edges from 0 and 1, and 3 has one from 2. Vertices 0 and 1 have no prerequisites, so either can go first: a DAG usually has several topological orders.

Shortest paths in a DAG

In a DAG, shortest paths need no priority queue. Relax the edges of each vertex in topological order: by the time a vertex is processed, every edge into it has been relaxed, so its distance is final. That takes Θ(V + E), faster than Dijkstra, and it works even with negative weights, since the argument never used the sign of a weight:

struct Edge {
    let to: Int
    let weight: Double
}

func dagShortestPaths(_ adjacent: [[Edge]], from source: Int, order: [Int]) -> [Double] {
    var distTo = Array(repeating: Double.infinity, count: adjacent.count)
    distTo[source] = 0
    for v in order where distTo[v] < .infinity {
        for e in adjacent[v] where distTo[v] + e.weight < distTo[e.to] {
            distTo[e.to] = distTo[v] + e.weight
        }
    }
    return distTo
}

let adjacent: [[Edge]] = [
    [Edge(to: 1, weight: 2), Edge(to: 2, weight: 5)],
    [Edge(to: 3, weight: 4)],
    [Edge(to: 1, weight: -4), Edge(to: 3, weight: 1)],
    [],
]
print(dagShortestPaths(adjacent, from: 0, order: [0, 2, 1, 3]))   // [0.0, 1.0, 5.0, 5.0]

This is the graph from Lesson 45’s lab, on which Dijkstra fails: here 1 is correctly reached through 2, with distance 1.

Reductions

To find the longest paths in a DAG, there is no need for a new algorithm. Negate every weight, find the shortest paths, and negate the answers: the path that was longest is now the most negative, which is the shortest. The method above allows negative weights, so this works.

That is a reduction: solving problem A by transforming its input into an input for problem B, solving B, and transforming the answer back. If the transformations are cheap, then A is no harder than B. CS61B uses reductions to organize the whole subject:

  • Longest paths in a DAG reduce to shortest paths in a DAG, by negation.
  • Scheduling tasks with durations and dependencies reduces to longest paths: the earliest a task can start is the longest path to it (the lab builds this).
  • Shortest paths with unweighted edges reduce to BFS; Lesson 43.
  • In Lesson 56, sorting will be shown to be at least as hard as a problem whose lower bound is known, which proves a lower bound for sorting.

Reductions also work the other way, to show a problem is hard. Longest paths in a general graph, with cycles, would solve the Hamilton path problem from Lesson 43, which has no known efficient algorithm; so longest paths in general graphs are hard too. Negating weights does not help there, because a graph with cycles and negative weights has no well-defined shortest path.

Put the lines in order

Put the lines in order so the program prints [0, 1, 2].

  1. var order: [Int] = []
  2. order.append(v)
  3. for w in adjacent[v] { visit(w) }
  4. let adjacent = [[1], [2], []]
  5. }
  6. func visit(_ v: Int) {
  7. print(Array(order.reversed()))
  8. visit(0)

Show the correct program
let adjacent = [[1], [2], []]
var order: [Int] = []
func visit(_ v: Int) {
    for w in adjacent[v] { visit(w) }
    order.append(v)
}
visit(0)
print(Array(order.reversed()))

Lab 46: DAGs

Q0: What would Swift print?

What would Swift print?

let adjacent = [[1, 2], [3], [3], []]
var post: [Int] = []
var seen = Set<Int>()
func dfs(_ v: Int) {
    seen.insert(v)
    for w in adjacent[v] where !seen.contains(w) { dfs(w) }
    post.append(v)
}
dfs(0)
print(post, Array(post.reversed()))

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

Show answer and explanation

Answer[3, 1, 2, 0] [0, 2, 1, 3]

DFS from 0 goes to 1, then 3, which finishes first; then 1 finishes. Back at 0, it visits 2, whose neighbor 3 is done, so 2 finishes, then 0. Reversed: 0, 2, 1, 3, a valid order, with 0 before both 1 and 2, and both before 3.

Q1: Course schedule

Courses have prerequisites, given as pairs (course, prerequisite) of names. Write schedule(_:), which returns an order in which to take all courses, or nil if the prerequisites are circular. Map names to numbers as in Lesson 44.

Show solution
func schedule(_ prerequisites: [(course: String, needs: String)]) -> [String]? {
    var index: [String: Int] = [:]
    var names: [String] = []
    func id(_ name: String) -> Int {
        if let i = index[name] { return i }
        index[name] = names.count
        names.append(name)
        return names.count - 1
    }
    var edges: [(Int, Int)] = []
    for p in prerequisites {
        edges.append((id(p.needs), id(p.course)))          // needs → course
    }
    var adjacent: [[Int]] = Array(repeating: [], count: names.count)
    var inDegree = Array(repeating: 0, count: names.count)
    for (v, w) in edges {
        adjacent[v].append(w)
        inDegree[w] += 1
    }
    var ready = names.indices.filter { inDegree[$0] == 0 }.sorted { names[$0] > names[$1] }
    var order: [String] = []
    while let v = ready.popLast() {
        order.append(names[v])
        for w in adjacent[v] {
            inDegree[w] -= 1
            if inDegree[w] == 0 { ready.append(w) }
        }
    }
    return order.count == names.count ? order : nil
}

let plan = schedule([("61B", "61A"), ("61C", "61B"), ("162", "61C"), ("170", "61B"), ("170", "70")])!
func before(_ a: String, _ b: String) -> Bool { plan.firstIndex(of: a)! < plan.firstIndex(of: b)! }
assert(before("61A", "61B") && before("61B", "61C") && before("61C", "162"))
assert(before("61B", "170") && before("70", "170"))
assert(schedule([("A", "B"), ("B", "A")]) == nil)

The edge goes from the prerequisite to the course, “must come before”. The tests check the constraints rather than one exact order, since several orders are valid.

Q2: The critical path

A project’s tasks have durations and dependencies, and tasks run in parallel whenever their dependencies are done. Find the shortest time in which the whole project can finish: the longest path through the DAG, weighted by durations. Reduce it to shortest paths by negating.

Show solution
func finishTime(durations: [Double], dependencies: [(before: Int, after: Int)]) -> Double {
    let n = durations.count
    var adjacent: [[Int]] = Array(repeating: [], count: n)
    var inDegree = Array(repeating: 0, count: n)
    for d in dependencies {
        adjacent[d.before].append(d.after)
        inDegree[d.after] += 1
    }
    // Topological order by Kahn’s algorithm.
    var ready = (0..<n).filter { inDegree[$0] == 0 }
    var order: [Int] = []
    while let v = ready.popLast() {
        order.append(v)
        for w in adjacent[v] {
            inDegree[w] -= 1
            if inDegree[w] == 0 { ready.append(w) }
        }
    }
    // Shortest paths with negated weights: -(finish time of each task).
    var negatedFinish = durations.map { -$0 }          // a task with no dependencies
    for v in order {
        for w in adjacent[v] where negatedFinish[v] - durations[w] < negatedFinish[w] {
            negatedFinish[w] = negatedFinish[v] - durations[w]
        }
    }
    return -(negatedFinish.min() ?? 0)
}

// 0: foundation (5), 1: walls (10), 2: plumbing (4), 3: roof (6), 4: painting (3)
let time = finishTime(durations: [5, 10, 4, 6, 3],
                      dependencies: [(0, 1), (0, 2), (1, 3), (2, 4), (3, 4)])
assert(time == 5 + 10 + 6 + 3)

The foundation, walls, roof, and painting form the critical path, 24 units: delaying any of them delays the whole project, while plumbing has slack. Negating turns “latest finish” into “most negative”, so the shortest-path relaxation computes it unchanged, which is the reduction the lesson described.

Q3: Counting paths

Count the number of distinct paths from s to t in a DAG, processing vertices in topological order: the number of paths to w is the sum of the numbers of paths to each vertex with an edge into w.

Show solution
func countPaths(_ adjacent: [[Int]], from s: Int, to t: Int) -> Int {
    var visited = Array(repeating: false, count: adjacent.count)
    var postorder: [Int] = []
    func visit(_ v: Int) {
        visited[v] = true
        for w in adjacent[v] where !visited[w] { visit(w) }
        postorder.append(v)
    }
    visit(s)
    var paths = Array(repeating: 0, count: adjacent.count)
    paths[s] = 1
    for v in postorder.reversed() {
        for w in adjacent[v] { paths[w] += paths[v] }
    }
    return paths[t]
}

// A 3 × 3 grid of vertices, with edges right and down: C(4, 2) = 6 paths.
var grid: [[Int]] = Array(repeating: [], count: 9)
for r in 0..<3 {
    for c in 0..<3 {
        let v = r * 3 + c
        if c < 2 { grid[v].append(v + 1) }
        if r < 2 { grid[v].append(v + 3) }
    }
}
assert(countPaths(grid, from: 0, to: 8) == 6)
assert(countPaths([[1, 2], [3], [3], []], from: 0, to: 3) == 2)

The number of paths can grow exponentially with the size of the graph, but this counts them in Θ(V + E) without listing any. It is dynamic programming: each answer is built from answers to smaller subproblems, in an order (here, topological) where those are always ready. Lesson 18’s memoization was the same idea, discovering the order by recursion.

Q4 (optional): Detecting the cycle

When a dependency graph has a cycle, reporting just “there is a cycle” is not very helpful. Modify DFS to return the vertices of one cycle, using three colors: white (unvisited), gray (on the current path), and black (finished). An edge to a gray vertex closes a cycle.

Show solution
func findCycle(_ adjacent: [[Int]]) -> [Int]? {
    enum Color { case white, gray, black }
    var color = Array(repeating: Color.white, count: adjacent.count)
    var path: [Int] = []

    func visit(_ v: Int) -> [Int]? {
        color[v] = .gray
        path.append(v)
        for w in adjacent[v] {
            switch color[w] {
            case .gray:
                return Array(path[path.lastIndex(of: w)!...])      // from w back to v
            case .white:
                if let cycle = visit(w) { return cycle }
            case .black:
                continue
            }
        }
        path.removeLast()
        color[v] = .black
        return nil
    }

    for v in adjacent.indices where color[v] == .white {
        if let cycle = visit(v) { return cycle }
    }
    return nil
}

assert(findCycle([[1], [2], [3], [1]]) == [1, 2, 3])
assert(findCycle([[1, 2], [3], [3], []]) == nil)

Gray vertices are exactly the current DFS path, so an edge to a gray vertex leads back up the path, closing a cycle. An edge to a black vertex does not: that vertex and everything below it are finished, as in a diamond, which is not a cycle.

What’s next

Unit 6 ends with Project 9, NGordNet, which puts maps, graphs, and SwiftUI charts together. Unit 7 continues with hashing.