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

Measuring how cost grows: timing with ContinuousClock and doubling experiments, counting operations, the four simplifications, and the definitions of big Theta and big O.

CS61B
Asymptotics I · Textbook Ch. 11
Swift book
Control Flow
Documentation
ContinuousClock

Unit 4 built data structures and said, informally, which operations were fast. Unit 5 makes that precise. Lesson 18 introduced orders of growth with a table; this lesson, following CS61B’s asymptotics lectures, explains where the table comes from, how to derive an order of growth from code, and what the notation Θ(N²) actually claims.

CS61B distinguishes two costs of a program: the programming cost, how long it takes people to write and change it, and the execution cost, how much time and memory it uses when it runs. Unit 4 cared about both. This unit is about the second.

Two ways to find duplicates

Here are two functions that decide whether a sorted array contains a repeated value, CS61B’s running example:

/// Compares every pair.
func dup1(_ values: [Int]) -> Bool {
    for i in 0..<values.count {
        for j in (i + 1)..<values.count where values[i] == values[j] {
            return true
        }
    }
    return false
}

/// In a sorted array, equal values are next to each other.
func dup2(_ values: [Int]) -> Bool {
    for i in 0..<(values.count - 1) where values[i] == values[i + 1] {
        return true
    }
    return false
}

let sorted = [-3, -1, 2, 4, 4, 8, 10, 12]
print(dup1(sorted), dup2(sorted), dup1([1, 2, 3]), dup2([1, 2, 3]))   // true true false false

dup2 is clearly better. The question is how to say by how much, in a way that does not depend on the computer.

Measuring

The direct approach is to time them. ContinuousClock measures elapsed time, and its measure method times a closure:

let clock = ContinuousClock()
let values = Array(0..<40_000)          // no duplicates: the worst case
let elapsed = clock.measure {
    _ = dup1(values)
}
print(elapsed)

Timing is only meaningful with an optimized build (swiftc -O, or swift build -c release), since debug builds check and slow down everything, and only when repeated a few times, keeping the fastest run. On the computer this lesson was written on, the results were:

N (items) dup1 dup2
10,000 21 ms 0.005 ms
20,000 61 ms 0.008 ms
40,000 240 ms 0.016 ms
80,000 962 ms 0.032 ms

The absolute numbers depend on the machine. The ratios do not: each time N doubles, dup1 takes about four times as long, and dup2 about twice as long. This doubling experiment is a practical way to estimate how a function’s cost grows: if doubling the input multiplies the time by 2ᵏ, the cost grows roughly like Nᵏ.

Timing has real limits, though. Results vary with load, caches, and the compiler; small inputs are dominated by noise; and it only tells you about the inputs you tried.

Counting operations

The alternative is to count, from the code, how many times each operation runs, as a function of the input size N. For dup1 in the worst case, when there are no duplicates:

Operation Count
outer loop steps N
values[i] == values[j] comparisons (N − 1) + (N − 2) + … + 1 + 0 = N(N − 1) / 2
array accesses 2 × N(N − 1) / 2 = N² − N

For dup2, the comparisons number N − 1, and the array accesses 2N − 2.

Counting is exact and machine-independent, but tedious, and the exact counts contain detail nobody needs. What matters about N(N − 1)/2 is that it grows like N²; what matters about N − 1 is that it grows like N.

What would Swift print?

var comparisons = 0
let n = 6
for i in 0..<n {
    for _ in (i + 1)..<n {
        comparisons += 1
    }
}
print(comparisons, n * (n - 1) / 2)

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

Show answer and explanation

Answer15 15

Counting the inner loop’s steps directly gives 5 + 4 + 3 + 2 + 1 + 0 = 15, which is N(N − 1)/2 for N = 6: every pair of positions, once.

Four simplifications

CS61B reduces an exact count to its essence in four steps:

  1. Consider only the worst case. When the running time depends on the input, analyze the input that makes the most work: for dup1, an array with no duplicates. (Best and average cases are useful too, but must then be said explicitly.)
  2. Pick a representative operation, the cost model, instead of counting everything. For dup1, the comparisons: every other operation runs a proportional number of times.
  3. Ignore lower-order terms. N(N − 1)/2 = N²/2 − N/2, and for large N the N/2 hardly matters: at a million, it is less than a millionth of the total.
  4. Ignore multiplicative constants. N²/2 and N² grow the same way; the ½ depends on details like which operation we counted, and on the machine.

What is left is the order of growth: N² for dup1, N for dup2. Exactly the doubling ratios from the timing table: 2² = 4 and 2¹ = 2.

Big Theta

The notation packages those simplifications into a definition. A function R(N) is Θ(f(N)), read “big Theta of f of N”, if there are positive constants k₁ and k₂ such that

k₁ · f(N) ≤ R(N) ≤ k₂ · f(N)

for all sufficiently large N. In words: R is eventually squeezed between two multiples of f. Examples:

R(N) Order of growth
N³ + 3N⁴ Θ(N⁴)
1/N + N³ Θ(N³)
1/N + 5 Θ(1)
N·eᴺ + N Θ(N·eᴺ)
40 sin(N) + 4N² Θ(N²)

To check the first: for N ≥ 1, N³ ≤ N⁴, so 3N⁴ ≤ N³ + 3N⁴ ≤ 4N⁴. The constants k₁ = 3 and k₂ = 4 work. Big Theta says nothing about small N and nothing about constant factors, only about the shape of the growth.

So “dup1 takes Θ(N²) time in the worst case” is a precise claim: past some size, its running time is between two fixed multiples of N².

Big O

Big O keeps only the upper half of the definition: R(N) ∈ O(f(N)) if R(N) ≤ k₂ · f(N) for large N. It means “grows no faster than f”. Since an upper bound need not be tight, N² ∈ O(N²), but also N² ∈ O(N³), and dup2 ∈ O(N²) is true but unhelpful.

In everyday speech, programmers often say “O(N)” when they mean Θ(N). This course uses Θ when the bound is tight, and O when only an upper bound is known or meant, as in “every sort in the standard library is O(N log N)”. Lesson 37 adds the lower-bound counterpart, big Omega.

Put the lines in order

Put the lines in order so the program prints 10.

  1. var n = 1024
  2. n /= 2
  3. steps += 1
  4. while n > 1 {
  5. var steps = 0
  6. print(steps)
  7. }

Show the correct program
var steps = 0
var n = 1024
while n > 1 {
    n /= 2
    steps += 1
}
print(steps)

Lab 33: Asymptotics

Q0: What would Swift print?

What would Swift print?

var count = 0
let n = 8
for i in 0..<n {
    for _ in 0..<i * i {
        count += 1
    }
}
print(count)

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

Show answer and explanation

Answer140

The inner loop runs 0, 1, 4, 9, …, 49 times: the sum of squares up to 7², which is 140. In general this is about N³/3, so the function is Θ(N³).

What would Swift print?

var count = 0
var i = 1
while i < 100 {
    for _ in 0..<i {
        count += 1
    }
    i *= 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

Answer127

The inner loop runs 1, 2, 4, …, 64 times, which adds up to 127. A geometric sum is dominated by its last term, so although there are two loops, the total is Θ(N) for a bound of N.

Q1: Count, then simplify

For each function, write the exact number of times work() runs as a formula in N, then its order of growth. Check your formulas by counting.

func a(_ n: Int) { for i in 0..<n { for j in 0..<n where j < i { work() } } }
func b(_ n: Int) { for _ in 0..<n { work() }; for _ in 0..<n { work() } }
func c(_ n: Int) { for i in 0..<n { for _ in 0..<(n / 2) { work() }; if i % 2 == 0 { work() } } }
Show solution
var calls = 0
func work() { calls += 1 }

func a(_ n: Int) { for i in 0..<n { for j in 0..<n where j < i { work() } } }
func b(_ n: Int) { for _ in 0..<n { work() }; for _ in 0..<n { work() } }
func c(_ n: Int) { for i in 0..<n { for _ in 0..<(n / 2) { work() }; if i % 2 == 0 { work() } } }

for n in [4, 10, 100] {
    calls = 0; a(n); assert(calls == n * (n - 1) / 2)
    calls = 0; b(n); assert(calls == 2 * n)
    calls = 0; c(n); assert(calls == n * (n / 2) + (n + 1) / 2)
}
  • a: N(N − 1)/2, so Θ(N²). The where clause filters, but the inner loop still examines N values of j each time: the loop itself is Θ(N²) even before counting work.
  • b: 2N, so Θ(N). Loops one after another add; only nested loops multiply.
  • c: N·⌊N/2⌋ + ⌈N/2⌉, so Θ(N²). The extra work on even steps is a lower-order term.

Q2: A doubling experiment

Write doublingRatios(sizes:run:), which times a function on inputs of each size (keeping the fastest of three runs) and returns the ratios between consecutive timings. Use it to estimate the exponent for dup1 and dup2. Run it as an optimized build: swiftc -O lab.swift && ./lab.

Show solution
func doublingRatios(sizes: [Int], run: (Int) -> Void) -> [Double] {
    let clock = ContinuousClock()
    let times = sizes.map { n in
        (0..<3).map { _ in clock.measure { run(n) } }.min()!
    }
    return zip(times, times.dropFirst()).map { $1 / $0 }
}

func dup1(_ values: [Int]) -> Bool {
    for i in 0..<values.count {
        for j in (i + 1)..<values.count where values[i] == values[j] {
            return true
        }
    }
    return false
}

let ratios = doublingRatios(sizes: [1_000, 2_000, 4_000]) { n in
    _ = dup1(Array(0..<n))
}
assert(ratios.count == 2 && ratios.allSatisfy { $0 > 0 })
print(ratios.map { String(Int(($0 * 10).rounded())) })   // for dup1, about 40 (a ratio near 4)

Dividing two Durations gives a Double. For dup1, ratios near 4 mean an exponent of log₂ 4 = 2. The first ratios are often off, because small inputs are dominated by fixed costs; trust the ratios at the largest sizes. In a debug build the ratios still approach 4, but every time is several times larger.

Q3: Identify the order

Give the order of growth of each expression.

  1. 3N² + 1000N + 10⁹
  2. N log N + 100N
  3. 2ᴺ + N¹⁰⁰
  4. (N + 1)(N − 1) / N
  5. log(N²)
Show solution
  1. Θ(N²). The constant 10⁹ is huge, but constant.
  2. Θ(N log N). log N eventually exceeds 100, so N log N dominates 100N.
  3. Θ(2ᴺ). Every exponential eventually beats every polynomial, even N¹⁰⁰.
  4. Θ(N). It equals N − 1/N.
  5. Θ(log N). log(N²) = 2 log N, and constants are ignored. For the same reason, the base of a logarithm never matters in Θ.

Q4: Without sorting

dup2 needs a sorted array. Write dup3, which works on any array in Θ(N) expected time using a Set, and give the order of growth of sorting first and then calling dup2.

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

func dup2(_ values: [Int]) -> Bool {
    for i in 0..<max(values.count - 1, 0) where values[i] == values[i + 1] {
        return true
    }
    return false
}

assert(dup3([5, 1, 4, 1]) && !dup3([3, 2, 1]) && !dup3([]))
assert(dup2([5, 1, 4, 1].sorted()) == dup3([5, 1, 4, 1]))

Sorting takes Θ(N log N) (Lessons 54 to 56 prove that no comparison sort does better), so sort-then-scan is Θ(N log N) overall: the sort dominates the Θ(N) scan. The set version is Θ(N) expected, because each set insertion takes constant time on average, which Lesson 48 explains. The guard in dup2 also fixes a crash: 0..<-1 for an empty array.

Q5: Finding the constants

Show that R(N) = 4N² + 3N + 2 is Θ(N²) by finding constants k₁, k₂, and N₀ such that k₁N² ≤ R(N) ≤ k₂N² for all N ≥ N₀. Then check your constants with a loop.

Show solution

For N ≥ 1, 3N ≤ 3N² and 2 ≤ 2N², so R(N) ≤ 4N² + 3N² + 2N² = 9N². And R(N) ≥ 4N² always. So k₁ = 4, k₂ = 9, and N₀ = 1 work.

func r(_ n: Double) -> Double { 4 * n * n + 3 * n + 2 }

for n in stride(from: 1.0, through: 10_000, by: 1) {
    assert(4 * n * n <= r(n) && r(n) <= 9 * n * n)
}

A loop cannot prove the bound for every N, but it catches a wrong constant quickly, which is the same role tests play for code.

Q6 (optional): Estimating the exponent

Given timings at sizes that are not powers of two, the exponent k in T(N) ≈ c·Nᵏ can be estimated from any two points: k = log(T₂/T₁) / log(N₂/N₁). Write estimateExponent(_:) that takes (size, seconds) pairs and returns the estimate from the two largest sizes. Test it on synthetic data.

Show solution
import Foundation

func estimateExponent(_ samples: [(size: Double, seconds: Double)]) -> Double {
    let points = samples.sorted { $0.size < $1.size }.suffix(2)
    let (a, b) = (points.first!, points.last!)
    return log(b.seconds / a.seconds) / log(b.size / a.size)
}

let quadratic = [1_000.0, 3_000, 9_000].map { (size: $0, seconds: 2e-9 * $0 * $0) }
let linear = [1_000.0, 5_000].map { (size: $0, seconds: 7e-8 * $0) }
assert(abs(estimateExponent(quadratic) - 2) < 0.01)
assert(abs(estimateExponent(linear) - 1) < 0.01)

log comes from Foundation, which is available wherever Swift runs. The constants 2e-9 and 7e-8 cancel in the ratio, which is exactly why the exponent can be estimated without knowing them. Estimating from the two largest sizes follows the advice from Q2: small inputs are dominated by fixed costs.

What’s next

Next lesson: disjoint sets, a data structure whose three versions have very different orders of growth, and the subject of Project 8.