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

Asymptotic analysis

A theory homework: derive orders of growth for tricky loops and recursions, check each by counting, solve recurrences, prove a bound, and compare Θ, O, and Ω claims.

This homework goes with Lessons 34 to 37, like CS61B’s asymptotics homework. For each function, work out the answer on paper first, then check it by counting, as the solutions do. Several functions here are designed so that the first guess is wrong.

Each problem uses this counter:

var count = 0
func work() { count += 1 }

Q1: A tripling loop

func p1(_ n: Int) {
    var i = 1
    while i < n {
        for _ in 0..<i { work() }
        i *= 3
    }
}
Show solution

Θ(N). The inner loop runs 1, 3, 9, … times, up to the largest power of 3 below N: a geometric sum, less than 1.5 times its last term. For N = 729 = 3⁶, the powers below it are 1 to 243, which add up to 364.

var count = 0
func work() { count += 1 }

func p1(_ n: Int) {
    var i = 1
    while i < n {
        for _ in 0..<i { work() }
        i *= 3
    }
}

p1(729)
assert(count == (729 - 1) / 2)

Q2: A shrinking inner loop

func p2(_ n: Int) {
    for i in 1...n {
        var j = n
        while j > i {
            work()
            j /= 2
        }
    }
}
Show solution

Θ(N), although it looks like N log N. For each i, the inner loop halves j from N until it is at most i: about log₂(N / i) steps. For most i that is small: half the values of i are above N / 2 and take at most one step, a quarter take at most two, and so on. The total is roughly log₂(N / 1) + log₂(N / 2) + … + log₂(N / N), which is about 1.44 N; rounding each count up to a whole number of halvings adds up to one more step per i, and the measured total is close to 2N.

var count = 0
func work() { count += 1 }

func p2(_ n: Int) {
    for i in 1...n {
        var j = n
        while j > i {
            work()
            j /= 2
        }
    }
}

var counts: [Int] = []
for n in [1_000, 2_000, 4_000, 8_000] {
    count = 0
    p2(n)
    counts.append(count)
}
let ratios = zip(counts, counts.dropFirst()).map { Double($1) / Double($0) }
assert(ratios.allSatisfy { abs($0 - 2) < 0.05 })     // doubling: linear
assert(counts.allSatisfy { $0 < 2 * 8_000 })

The doubling ratios settle at 2, the fingerprint of linear growth. The upper bound N log N is true, but not tight.

Q3: Two recursions

Give recurrences and orders of growth for both, and check them.

func p3(_ n: Int) {
    if n <= 1 { work(); return }
    p3(n - 1)
    for _ in 0..<n { work() }
}

func p4(_ n: Int) {
    if n <= 1 { return }
    for _ in 0..<n { work() }
    p4(n / 3)
    p4(n / 3)
    p4(n / 3)
}
Show solution
  • p3: T(N) = T(N − 1) + N, so N + (N − 1) + … + 2 + 1: Θ(N²).
  • p4: T(N) = 3T(N/3) + N. Each level of the tree does N work in total and there are log₃ N levels: Θ(N log N), like merge sort but splitting in three.
var count = 0
func work() { count += 1 }

func p3(_ n: Int) {
    if n <= 1 { work(); return }
    p3(n - 1)
    for _ in 0..<n { work() }
}

func p4(_ n: Int) {
    if n <= 1 { return }
    for _ in 0..<n { work() }
    p4(n / 3)
    p4(n / 3)
    p4(n / 3)
}

count = 0; p3(729); assert(count == 729 * 730 / 2)
count = 0; p4(729); assert(count == 729 * 6)          // 729 = 3⁶: six levels

Q4: Proving a bound

Prove that 3N² − 10N + 5 ∈ Θ(N²) by giving k₁, k₂, and N₀, and check the inequality for every N from N₀ to 100,000.

Show solution

For the upper bound, 3N² − 10N + 5 ≤ 3N² + 5 ≤ 4N² once N² ≥ 5, so for N ≥ 3. For the lower bound, 3N² − 10N + 5 ≥ 2N² when N² ≥ 10N − 5, which holds for N ≥ 10. So k₁ = 2, k₂ = 4, N₀ = 10.

func r(_ n: Int) -> Int { 3 * n * n - 10 * n + 5 }

for n in 10...100_000 {
    assert(2 * n * n <= r(n) && r(n) <= 4 * n * n)
}
assert(r(3) < 2 * 3 * 3)     // the lower bound fails for small N, as it may

Big Theta only speaks about large N. For small N the function can even be negative (r(2) = −3), and the bound is still true.

Q5: True or false

  1. N² ∈ O(2ᴺ).
  2. log(N!) ∈ Θ(N log N).
  3. If f ∈ O(g) and g ∈ O(h), then f ∈ O(h).
  4. If f ∈ Θ(g), then 2^f ∈ Θ(2^g).
  5. The worst case of merge sort is Θ(N log N), and its best case is Θ(N).
Show solution
  1. True. Every polynomial is eventually below every exponential.
  2. True. log(N!) ≤ log(Nᴺ) = N log N, and log(N!) ≥ log((N/2)^(N/2)) = (N/2) log(N/2), which is Ω(N log N). Lesson 56 uses this to bound sorting.
  3. True. Multiply the constants: f ≤ k₁g ≤ k₁k₂h.
  4. False. f = 2N and g = N are Θ of each other, but 2^(2N) = 4ᴺ is not Θ(2ᴺ).
  5. False. Merge sort always splits and merges completely: its best case is also Θ(N log N), though it makes fewer comparisons on sorted input.

Q6 (optional): Worst and best cases

This function is a “lazy” duplicate finder. Give its best-case and worst-case orders of growth, and an input of each kind.

func firstRepeat(_ values: [Int]) -> Int? {
    var seen: [Int] = []
    for value in values {
        if seen.contains(value) { return value }
        seen.append(value)
    }
    return nil
}
Show solution
  • Best case, Θ(1): the first two items are equal, such as [7, 7, …].
  • Worst case, Θ(N²): no repeats, so every item is checked against every earlier one: 0 + 1 + … + (N − 1) comparisons.
var comparisons = 0

func firstRepeat(_ values: [Int]) -> Int? {
    var seen: [Int] = []
    for value in values {
        for s in seen {
            comparisons += 1
            if s == value { return value }
        }
        seen.append(value)
    }
    return nil
}

comparisons = 0
assert(firstRepeat([7, 7] + Array(0..<1_000)) == 7 && comparisons == 1)
comparisons = 0
assert(firstRepeat(Array(0..<1_000)) == nil && comparisons == 1_000 * 999 / 2)

With a Set for seen, the worst case becomes Θ(N), since each check takes constant time on average.