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

Efficiency and memoization

Counting the work a program does, orders of growth from constant to exponential, memoization with a dictionary, fast exponentiation, and choosing data structures for speed.

CS61A
Efficiency · Composing Programs 2.8
Documentation
Dictionary · Set

Lesson 8’s fib(20) made 21,891 calls to compute one number, and each step up in n makes that worse. A correct program that takes a year to answer is not much use. This lesson is about measuring how much work a program does, and about the most useful trick for doing less.

Counting work

Timing a program depends on the machine, the load, and luck. CS61A measures something steadier: how the number of steps grows with the size of the input. Count the operations, not the seconds.

var comparisons = 0

func hasDuplicates(_ values: [Int]) -> Bool {
    for i in values.indices {
        for j in values.indices where j > i {
            comparisons += 1
            if values[i] == values[j] {
                return true
            }
        }
    }
    return false
}

_ = hasDuplicates(Array(1...100))
print(comparisons)   // 4950

With 100 distinct values, every pair is compared once: 100 × 99 / 2 = 4,950. With 1,000 values it would be 499,500. Multiplying the input by 10 multiplies the work by about 100.

Orders of growth

The order of growth describes that relationship while ignoring constant factors. The common ones, from best to worst:

Order Name Doubling the input… Example
Θ(1) constant changes nothing array element, dictionary lookup
Θ(log n) logarithmic adds one step halving until 1, fast exponentiation
Θ(n) linear doubles the work sumDigits loop, array contains
Θ(n²) quadratic quadruples the work comparing every pair
Θ(bⁿ) exponential squares the work tree-recursive fib

What would Swift print?

var steps = 0
var k = 1024
while k > 1 {
    k /= 2
    steps += 1
}
print(steps)

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

Show answer and explanation

Answer10

1024 is 2¹⁰, so halving reaches 1 after 10 steps. Doubling the start to 2048 would add just one more step: logarithmic growth.

Memoization

Tree-recursive fib is exponential because it recomputes the same values over and over; fib(2) alone is computed thousands of times for fib(20). Memoization remembers each result the first time it is computed, in a dictionary, and looks it up after that:

var calls = 0
var memo: [Int: Int] = [:]

func fib(_ n: Int) -> Int {
    calls += 1
    if let known = memo[n] {
        return known
    }
    let result = n < 2 ? n : fib(n - 2) + fib(n - 1)
    memo[n] = result
    return result
}

print(fib(90), calls)   // 2880067194370816120 179

Each value from 0 to 90 is computed once; the other calls are instant lookups. The same definition, the same tree-shaped reasoning, and linear work instead of exponential.

What would Swift print?

var calls = 0
var memo: [Int: Int] = [:]
func fib(_ n: Int) -> Int {
    calls += 1
    if let known = memo[n] {
        return known
    }
    let result = n < 2 ? n : fib(n - 2) + fib(n - 1)
    memo[n] = result
    return result
}
_ = fib(10)
print(calls)

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

Show answer and explanation

Answer19

Without memoization, fib(10) makes 177 calls. With it, 11 calls compute a new value, one for each n from 0 to 10, and the other 8 find the answer already stored: 19 in all. More importantly, the count now grows linearly with n.

Global variables for the memo are fine in a lab, but a memo is better kept private. A nested function can use a dictionary from its enclosing function, as Lesson 5 showed, so each top-level call gets a fresh, hidden memo; the lab does it that way.

Fast exponentiation

Computing bⁿ by multiplying b together n times is linear. Squaring does better: b¹⁰ is (b⁵)², so half the problem answers the whole thing.

Put the lines in order

Put the lines in order so the program prints 1024.

  1. return half * half
  2. print(power(2, 10))
  3. }
  4. let half = power(base, n / 2)
  5. if n == 0 {
  6. return 1
  7. return base * power(base, n - 1)
  8. func power(_ base: Int, _ n: Int) -> Int {
  9. }
  10. }
  11. if n % 2 == 0 {

Show the correct program
func power(_ base: Int, _ n: Int) -> Int {
    if n == 0 {
        return 1
    }
    if n % 2 == 0 {
        let half = power(base, n / 2)
        return half * half
    }
    return base * power(base, n - 1)
}
print(power(2, 10))

Even exponents halve; odd ones take one step to become even. Either way, at most two calls halve n, so the work is logarithmic: 2⁶² takes 11 calls instead of 62 multiplications.

What would Swift print?

var calls = 0
func power(_ base: Int, _ n: Int) -> Int {
    calls += 1
    if n == 0 {
        return 1
    }
    if n % 2 == 0 {
        let half = power(base, n / 2)
        return half * half
    }
    return base * power(base, n - 1)
}
print(power(2, 10), calls)

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

Show answer and explanation

Answer1024 6

The exponents visited are 10, 5, 4, 2, 1, and 0: six calls. The plain loop would multiply ten times.

Searching a sorted array can halve the problem each step, like guessing a number when told “higher” or “lower”:

func binarySearch(_ sorted: [Int], _ target: Int) -> Int? {
    var low = 0
    var high = sorted.count - 1
    while low <= high {
        let middle = (low + high) / 2
        if sorted[middle] == target {
            return middle
        } else if sorted[middle] < target {
            low = middle + 1
        } else {
            high = middle - 1
        }
    }
    return nil
}

print(binarySearch([1, 3, 5, 7, 9, 11], 7) as Any)   // Optional(3)
print(binarySearch([1, 3, 5, 7, 9, 11], 4) as Any)   // nil

For a million elements, an unsuccessful search takes 19 steps, where checking one by one would take a million. Sorting first costs more than one linear search (the standard library’s sort() is Θ(n log n)), so it pays off when you will search the same data many times.

Memoizing any function

Every memoized function so far repeated the same dictionary logic. A higher-order function can do it once. The recursive calls must go through the memoized version, so memoize passes the function its own memoized self as an argument:

func memoize<Input: Hashable, Output>(
    _ body: @escaping ((Input) -> Output, Input) -> Output
) -> (Input) -> Output {
    var cache: [Input: Output] = [:]
    func memoized(_ input: Input) -> Output {
        if let known = cache[input] {
            return known
        }
        let result = body(memoized, input)
        cache[input] = result
        return result
    }
    return memoized
}

let fib = memoize { (fib: (Int) -> Int, n: Int) -> Int in
    n < 2 ? n : fib(n - 1) + fib(n - 2)
}
print(fib(90))   // 2880067194370816120

The body reads just like the plain recursive definition, with the caching handled elsewhere: Lessons 4, 5, and 6 working together.

Choosing the data structure

The same question can have very different costs depending on where the data lives. contains on an array checks elements one by one, which is linear. On a Set or a dictionary’s keys it takes about the same time regardless of size, because the value’s hash says where to look. Replacing the pairwise loop at the top of this lesson with a set makes it linear:

func hasDuplicates(_ values: [Int]) -> Bool {
    var seen: Set<Int> = []
    for value in values {
        if seen.contains(value) {
            return true
        }
        seen.insert(value)
    }
    return false
}

print(hasDuplicates([3, 1, 4, 1]), hasDuplicates(Array(1...100_000)))   // true false

Lab 17: Efficiency

Q0: What would Swift print?

What would Swift print?

var steps = 0
for i in 0..<4 {
    for _ in 0..<i {
        steps += 1
    }
}
print(steps)

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

Show answer and explanation

Answer6

The inner loop runs 0, 1, 2, and 3 times: 6 steps. In general this is n(n − 1)/2, which grows quadratically.

What would Swift print?

var cache: [Int: Int] = [:]
var work = 0
func slowSquare(_ n: Int) -> Int {
    if let known = cache[n] {
        return known
    }
    work += 1
    cache[n] = n * n
    return n * n
}
let results = [3, 4, 3, 3, 4].map(slowSquare)
print(results, work)

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

Show answer and explanation

Answer[9, 16, 9, 9, 16] 2

Only the first 3 and the first 4 do any work; every repeat is a cache hit.

Q1: Faster partitions

Lesson 8’s countPartitions(100, 100) takes a very long time. Memoize it with a dictionary kept inside the function, keyed by the pair of arguments. An array [n, m] is Hashable, so it can be a key.

func countPartitions(_ n: Int, _ m: Int) -> Int {
    // your code here
}
Show solution
func countPartitions(_ n: Int, _ m: Int) -> Int {
    var memo: [[Int]: Int] = [:]

    func count(_ n: Int, _ m: Int) -> Int {
        if n == 0 {
            return 1
        } else if n < 0 || m == 0 {
            return 0
        }
        if let known = memo[[n, m]] {
            return known
        }
        let result = count(n - m, m) + count(n, m - 1)
        memo[[n, m]] = result
        return result
    }

    return count(n, m)
}

assert(countPartitions(6, 4) == 9)
assert(countPartitions(100, 100) == 190_569_292)

Only the lines touching memo are new; the recursion is unchanged. There are at most 100 × 100 distinct argument pairs, so the work is bounded by that instead of growing exponentially.

Q2: Orders of growth

Give the order of growth of each function in terms of n.

func a(_ n: Int) -> Int {
    var total = 0
    for i in 1...n {
        for _ in i...n {
            total += 1
        }
    }
    return total
}

func b(_ n: Int) -> Int {
    var k = n
    var steps = 0
    while k > 0 {
        k /= 3
        steps += 1
    }
    return steps
}

func c(_ n: Int) -> Int {
    n <= 1 ? 1 : c(n - 1) + c(n - 1)
}

assert(a(8) == 36)
assert(b(27) == 4)
assert(c(10) == 512)
Show solution
  • a is quadratic, Θ(n²). The inner loop runs n, then n − 1, …, then 1 times: n(n + 1) / 2 steps in total. The constant ½ does not change the order.
  • b is logarithmic, Θ(log n). Dividing by 3 each time reaches 0 after about log₃ n steps; the base of the logarithm does not matter.
  • c is exponential, Θ(2ⁿ). Each call makes two calls with an input only one smaller, doubling the work per level. Computing c(n - 1) once and doubling it would make it linear.

Q3: Two numbers that sum to a target

Write hasPairSum(_:target:), which returns true if two different elements of the array add up to target. Make it linear using a set.

func hasPairSum(_ values: [Int], target: Int) -> Bool {
    // your code here
}
Show solution
func hasPairSum(_ values: [Int], target: Int) -> Bool {
    var seen: Set<Int> = []
    for value in values {
        if seen.contains(target - value) {
            return true
        }
        seen.insert(value)
    }
    return false
}

assert(hasPairSum([3, 9, 5, 1], target: 10))    // 9 + 1
assert(!hasPairSum([3, 9, 5, 1], target: 7))
assert(!hasPairSum([5], target: 10))            // needs two different elements
assert(hasPairSum([5, 5], target: 10))

For each value, the question “have I already seen the number that completes it?” is one set lookup. Checking every pair would be quadratic.

Q4: Binary search, recursively

Write binarySearch(_:_:) recursively, with a helper that takes the current low and high positions. Return the index of target in a sorted array, or nil.

Show solution
func binarySearch(_ sorted: [Int], _ target: Int) -> Int? {
    func search(_ low: Int, _ high: Int) -> Int? {
        if low > high {
            return nil
        }
        let middle = (low + high) / 2
        if sorted[middle] == target {
            return middle
        }
        return sorted[middle] < target ? search(middle + 1, high) : search(low, middle - 1)
    }
    return search(0, sorted.count - 1)
}

let sorted = [1, 3, 5, 7, 9, 11]
assert(binarySearch(sorted, 7) == 3)
assert(binarySearch(sorted, 1) == 0)
assert(binarySearch(sorted, 11) == 5)
assert(binarySearch(sorted, 4) == nil)
assert(binarySearch([], 1) == nil)

Each call discards half of the remaining range, so the depth of the recursion is logarithmic, and the call stack stays small.

Q5 (optional): Longest common subsequence

The longest common subsequence of two strings is the longest sequence of characters that appears in both in the same order, not necessarily next to each other. For "ABCBDAB" and "BDCABA" it has length 4 (for example, "BCBA"). Write lcsLength(_:_:) with memoized tree recursion.

Show solution
func lcsLength(_ a: String, _ b: String) -> Int {
    let x = Array(a)
    let y = Array(b)
    var memo: [[Int]: Int] = [:]

    func length(_ i: Int, _ j: Int) -> Int {
        if i == x.count || j == y.count {
            return 0
        }
        if let known = memo[[i, j]] {
            return known
        }
        let result = x[i] == y[j]
            ? 1 + length(i + 1, j + 1)
            : max(length(i + 1, j), length(i, j + 1))
        memo[[i, j]] = result
        return result
    }

    return length(0, 0)
}

assert(lcsLength("ABCBDAB", "BDCABA") == 4)
assert(lcsLength("swift", "shift") == 4)   // "sift"
assert(lcsLength("", "abc") == 0)

If the first characters match, they start the best subsequence. If not, one of them is not part of it, so try dropping each and keep the better result. Without the memo this is exponential; with it there are only x.count × y.count distinct subproblems.

What’s next

That ends Unit 2. Unit 3 starts with algebraic data types and pattern matching, the Swift counterpart of CS61A’s functional programming weeks.