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

Asymptotics and disjoint sets

Derive orders of growth for loops, simplify expressions, trace weighted quick union with path compression, and an exam-level question about the worst case of union–find.

This discussion goes with Lessons 34 and 35.

Q1: What would Swift print?

What would Swift print?

var count = 0
let n = 16
for i in 1...n {
    var j = i
    while j <= n {
        count += 1
        j *= 2
    }
}
print(count)

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

Show answer and explanation

Answer31

For each i, the inner loop doubles j from i until it passes 16. For i = 1 that is 5 steps (1, 2, 4, 8, 16); for i = 2, 4 steps; for i = 3 and 4, 3 steps each; for i = 5 to 8, 2 each; and for i = 9 to 16, 1 each: 5 + 4 + 6 + 8 + 8 = 31. Half the values of i take a single step, so the total is about 2N: Θ(N), even though the inner loop can run log N times.

Q2: Orders of growth

Give the worst-case order of growth of each function, in terms of N.

func a(_ n: Int) {
    for i in 0..<n {
        for j in i..<min(i + 10, n) { work(j) }
    }
}

func b(_ n: Int) {
    var i = n
    while i > 0 {
        for _ in 0..<n { work(i) }
        i /= 2
    }
}

func c(_ values: [Int]) -> Bool {
    for (i, x) in values.enumerated() {
        if values[(i + 1)...].contains(x) { return true }
    }
    return false
}
Show solution
  • a: the inner loop runs at most 10 times, a constant, so Θ(N). A nested loop is not automatically quadratic: look at what the inner bound depends on.
  • b: the outer loop runs about log₂ N times and the inner loop N times each, so Θ(N log N). Unlike Lesson 36’s halving loop, the inner loop here does not shrink with i.
  • c: contains on the rest of the array is linear, so in the worst case, when there are no duplicates, the total is (N − 1) + (N − 2) + … = Θ(N²): it is dup1 with the inner loop hidden inside a library call.

Q3: Simplify

Give the tightest Θ for each, and for the first two, constants k₁ and k₂ that prove it.

  1. 5N³ + N² log N
  2. (N² + 1)(N + 3) / N
  3. log₂(8N) + log₂ log₂ N
  4. 2^(N + 10)
  5. 2^(2N)
Show solution
  1. Θ(N³). For N ≥ 1, log N ≤ N, so 5N³ ≤ R ≤ 6N³: k₁ = 5, k₂ = 6.
  2. Θ(N²). It is N² + 3N + 1 + 3/N. For N ≥ 1: N² ≤ R ≤ 8N².
  3. Θ(log N): log₂(8N) = 3 + log₂ N, and log log N grows slower still.
  4. Θ(2ᴺ): 2^(N + 10) = 1024 · 2ᴺ, a constant factor.
  5. Θ(4ᴺ): 2^(2N) = 4ᴺ, which is not a constant multiple of 2ᴺ. Constants in an exponent are not constant factors.

Q4: Tracing weighted quick union

Start with ten items, 0 to 9, each alone. Using weighted quick union where ties put the second item’s root under the first’s, and with path compression, perform these operations and give the parent array at the end:

connect(0, 1), connect(2, 3), connect(0, 2), connect(4, 5), connect(6, 7),
connect(4, 6), connect(0, 4), isConnected(3, 7)
Show solution
var parent = Array(0..<10)
var size = Array(repeating: 1, count: 10)

func find(_ p: Int) -> Int {
    var root = p
    while parent[root] != root { root = parent[root] }
    var p = p
    while parent[p] != root && p != root {
        let next = parent[p]
        parent[p] = root
        p = next
    }
    return root
}

func connect(_ p: Int, _ q: Int) {
    let (a, b) = (find(p), find(q))
    guard a != b else { return }
    if size[a] < size[b] { parent[a] = b; size[b] += size[a] }
    else { parent[b] = a; size[a] += size[b] }
}

connect(0, 1); connect(2, 3); connect(0, 2)
connect(4, 5); connect(6, 7); connect(4, 6)
connect(0, 4)
let connected = find(3) == find(7)
assert(connected)
assert(parent == [0, 0, 0, 0, 0, 4, 0, 0, 8, 9])

After the first three connections, 0 is the root of 3, with 3 under 2. The same happens to 7 under 4. connect(0, 4) joins two trees of size 4, a tie, so 4 goes under 0. Then isConnected(3, 7) runs find(3) and find(7), which compress their paths: 3 and 7 now point directly at 0, and so does 6, which was on 7’s path.

Q5: Exam-level: the worst case

  1. Give a sequence of connect calls on N items that makes plain quick union’s find take Θ(N) time.
  2. What is the worst-case height of a weighted quick union tree with 8 items? Give a sequence that reaches it.
  3. With weighted quick union but no path compression, what is the order of growth of M isConnected calls on N items, in the worst case?
Show solution
  1. connect(0, 1), connect(1, 2), connect(2, 3), …: with “make the first root a child of the second”, each call hangs the current chain’s root under a new item, and the chain grows into a path of length N − 1.
  2. 3, which is log₂ 8. Connect pairs, then pairs of pairs, then the two halves: connect(0, 1), connect(2, 3), connect(4, 5), connect(6, 7), connect(0, 2), connect(4, 6), connect(0, 4). Every merge is between equal sizes, so every merge makes some items one level deeper.
  3. Θ(M log N): each isConnected does two finds, each up to log₂ N steps, and an adversary can build a worst-case tree first and then query its deepest item M times.