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

Amortized analysis and the limits of big O

Lower bounds with big Omega, why bounds and cases are different questions, amortized cost with the accounting method, and hidden costs in Swift that turn linear code quadratic.

CS61B
Asymptotics III · Textbook Ch. 13
Documentation
Array

Two lessons of asymptotics have given us Θ and O and a method for loops and recursion. This lesson, like CS61B’s third asymptotics lecture, is about using the notation correctly: the lower-bound notation that completes the set, the difference between a bound and a case, the cost of operations that are usually cheap and occasionally expensive, and the places where Swift code hides work that no loop shows.

Big Omega

Big O is an upper bound. Big Omega is the matching lower bound: R(N) is Ω(f(N)) if R(N) ≥ k₁ · f(N) for some positive k₁ and all large N. It means “grows at least as fast as f”.

Θ is exactly both at once: R(N) ∈ Θ(f(N)) if and only if R(N) ∈ O(f(N)) and R(N) ∈ Ω(f(N)).

Claim True?
N² ∈ O(N³) yes: N² grows no faster than N³
N² ∈ Ω(N) yes: N² grows at least as fast as N
N² ∈ Θ(N³) no: it is not Ω(N³)
2ᴺ ∈ Ω(N¹⁰⁰⁰) yes, eventually

Lower bounds are how one proves that a problem is hard: Lesson 56 shows that every comparison sort takes Ω(N log N) comparisons in the worst case, so no cleverness can beat merge sort by more than a constant factor.

Bounds are not cases

A common confusion is to think that O means “worst case” and Ω means “best case”. They are separate ideas. A case is a choice of input: the best case, the worst case, or an average over some distribution. A bound is a statement about a function. You can give any kind of bound on any case.

Take Lesson 34’s dup1, which returns as soon as it finds a repeat:

  • In the best case, the first two items are equal, and it takes Θ(1) time.
  • In the worst case, there are no repeats, and it takes Θ(N²) time.
  • Over all inputs, its running time is O(N²) and Ω(1), and there is no single Θ that describes it, because the cases grow differently.

So “dup1 is O(N²)” is true, and so is “dup1’s worst case is Θ(N²)”, which is more informative. When the cases differ, say which one you mean.

What would Swift print?

func find(_ target: Int, in values: [Int]) -> Int {
    var steps = 0
    for value in values {
        steps += 1
        if value == target { break }
    }
    return steps
}
let values = Array(1...1000)
print(find(1, in: values), find(1000, in: values), find(0, in: values))

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

Show answer and explanation

Answer1 1000 1000

A linear search is Θ(1) in its best case and Θ(N) in its worst, which includes searching for something that is not there. Overall it is O(N) and Ω(1).

Amortized cost

Lesson 30’s array list doubles its storage when full. Most calls to addLast take constant time, but the one that triggers a resize copies every item: in the worst case, a single call is Θ(N). Yet a million calls take Θ(N) time in total, not Θ(N²). Saying “addLast is Θ(N)” would be true of the worst single call and badly misleading about any real program.

Amortized analysis bounds the total cost of a sequence of operations, and divides it among them. An operation has amortized cost c if any sequence of n operations costs at most c · n in total. For doubling, Lesson 30 showed that n adds cause fewer than 2n copies, so with one write per add, the total is under 3n: amortized constant time.

The accounting method

CS61B explains the same result with a bank account, which gives a way to analyze structures where the total is less obvious. Charge each operation a fixed amortized cost, possibly more than it actually costs. The surplus goes into the account and pays for expensive operations later. If the balance never goes negative, the amortized costs, added up, are an upper bound on the true total.

For the array list, charge 3 for each addLast: 1 pays for writing the item, and 2 are saved. When the storage doubles from capacity C to 2C, it copies C items. Since the previous resize, at capacity C/2, there have been C/2 adds, which saved 2 · C/2 = C: exactly enough to pay for the copies.

var balance = 0
var capacity = 1
var count = 0
var lowest = 0

for _ in 0..<1_000_000 {
    balance += 3                 // the amortized cost of addLast
    if count == capacity {
        balance -= count         // pay for copying every item
        capacity *= 2
    }
    balance -= 1                 // pay for writing the new item
    count += 1
    lowest = min(lowest, balance)
}
print(lowest >= 0, balance)   // true 951425

The balance never goes negative over a million adds, so 3 per operation is a valid amortized cost, and adding N items is Θ(N) in total.

The guarantee is about sequences. If each operation must finish within a deadline, such as in a game that has 16 milliseconds per frame, amortized constant time is not enough: the rare expensive call can still miss it.

Hidden costs

The loops in your code are not the only loops that run. Library functions do work too, and a function that looks like one step can take linear time. In Swift, the classic cases are:

String.count is Θ(N). A Swift string is stored as UTF-8, and a single character, such as “é” or a flag emoji, can take several bytes, so counting characters means reading the whole string. Calling count inside a loop over the string is quadratic. Keep the count in a variable, or iterate directly.

removeFirst() on an array is Θ(N). It shifts every remaining item left. Emptying an array from the front is therefore Θ(N²). Walk an index forward, use a deque (Projects 6 and 7), or reverse the array and use removeLast().

s = s + x builds a new string. It copies all of s each time, so building a string of N pieces this way is Θ(N²). s += x appends in place, in amortized constant time, as long as nothing else shares the string’s storage (Lesson 33).

contains on an array is Θ(N) (Lesson 18), so a loop that calls it is quadratic; a Set makes each lookup constant time.

Measured on the machine this lesson was written on, doubling N from 20,000 to 40,000 took s = s + "x" from 3.7 to 12.8 milliseconds, more than three times longer, while s += "x" went from 0.25 to 0.50: linear, and 25 times faster. Emptying an array with removeFirst() went from 21 to 107 milliseconds.

Put the lines in order

Put the lines in order so the program prints 4.

  1. }
  2. for count in 0..<10 {
  3. print(resizes)
  4. resizes += 1
  5. if count == capacity {
  6. capacity *= 2
  7. }
  8. var capacity = 1
  9. var resizes = 0

Show the correct program
var capacity = 1
var resizes = 0
for count in 0..<10 {
    if count == capacity {
        capacity *= 2
        resizes += 1
    }
}
print(resizes)

Lab 36: Amortized analysis

Q0: What would Swift print?

What would Swift print?

var flips = 0
var bits = [Int](repeating: 0, count: 8)
for _ in 0..<16 {
    var i = 0
    while i < bits.count && bits[i] == 1 {
        bits[i] = 0
        flips += 1
        i += 1
    }
    if i < bits.count {
        bits[i] = 1
        flips += 1
    }
}
print(flips)

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

Show answer and explanation

Answer31

Incrementing a binary counter sixteen times flips the lowest bit 16 times, the next 8, then 4, 2, and 1: 31 flips, fewer than two per increment. One increment can flip many bits, but on average each flips fewer than two: amortized constant time.

Q1: True or false

For each claim, say whether it is true, and why.

  1. If a function is O(N), it is also O(N²).
  2. If a function is Θ(N²) in the worst case, it is Ω(N²) for every input.
  3. Merge sort is O(N log N) and Ω(N log N), so it is Θ(N log N).
  4. An operation with amortized constant cost never takes more than constant time.
  5. values.firstIndex(of: x) on an array of N items is Θ(N).
Show solution
  1. True. An upper bound can always be loosened.
  2. False. A worst case says nothing about other inputs; dup1 is Θ(N²) in its worst case and constant in its best.
  3. True, for every input: merge sort always splits and merges completely, so its best and worst cases are both Θ(N log N).
  4. False. Individual operations can be expensive, like a resize; only the average over any sequence is bounded.
  5. False as stated. Its worst case, when x is absent or last, is Θ(N), but it stops at the first match, so it is O(N) and Ω(1) overall.

Q2: Multipop

A stack supports push and multipop(k), which pops up to k items at once. A single multipop can take Θ(N) time. Show, with the accounting method and a simulation, that any sequence of N operations takes O(N) time in total.

Show solution

Charge 2 for each push: 1 pays for the push, and 1 is saved on the item. Every item can be popped at most once, and its saved 1 pays for that. multipop is charged 0 beyond a constant, and never needs more than the items it pops have saved. The total is at most 2N plus a constant per operation: O(N).

struct Stack {
    private(set) var items: [Int] = []
    private(set) var work = 0

    mutating func push(_ x: Int) {
        items.append(x)
        work += 1
    }

    mutating func multipop(_ k: Int) {
        work += 1                      // the call itself
        for _ in 0..<min(k, items.count) {
            items.removeLast()
            work += 1
        }
    }
}

var stack = Stack()
var generator = SystemRandomNumberGenerator()
let operations = 100_000
for _ in 0..<operations {
    if Bool.random(using: &generator) {
        stack.push(1)
    } else {
        stack.multipop(Int.random(in: 0...50, using: &generator))
    }
}
assert(stack.work <= 3 * operations)

The random mix does not matter: whatever the sequence, total pops never exceed total pushes. That argument, “each item pays for its own removal”, is the most reusable idea in amortized analysis.

Q3: Fixing hidden quadratics

Each function is correct but quadratic. Find the hidden linear-time operation in each, and rewrite it in linear time.

func vowelPositions(_ s: String) -> [Int] {
    var result: [Int] = []
    var i = 0
    while i < s.count {
        let c = s[s.index(s.startIndex, offsetBy: i)]
        if "aeiou".contains(c) { result.append(i) }
        i += 1
    }
    return result
}

func drain(_ values: [Int]) -> Int {
    var values = values
    var total = 0
    while !values.isEmpty {
        total += values.removeFirst()
    }
    return total
}
Show solution
func vowelPositions(_ s: String) -> [Int] {
    var result: [Int] = []
    for (i, c) in s.enumerated() where "aeiou".contains(c) {
        result.append(i)
    }
    return result
}

func drain(_ values: [Int]) -> Int {
    var total = 0
    for value in values {
        total += value
    }
    return total
}

assert(vowelPositions("swift is fun") == [2, 6, 10])
assert(drain(Array(1...100)) == 5050)

vowelPositions hid two linear operations per step: s.count, and index(_:offsetBy:), which walks from the start to reach position i. Iterating over the string visits each character once. drain shifted the whole array on every removeFirst(); it only ever needed to read the items in order. The check "aeiou".contains(c) scans five characters, which is constant.

Q4: Shrinking at the wrong moment

An array list doubles when full and halves when it is half full or less. Construct a sequence of operations that makes every single operation resize, and count the copies for 1,000 operations. Then show that halving at a quarter fixes it.

Show solution
func copies(shrinkBelow fraction: Int, operations: Int) -> Int {
    var capacity = 16
    var count = 16            // full
    var copied = 0
    for step in 0..<operations {
        if step % 2 == 0 {    // add
            if count == capacity {
                copied += count
                capacity *= 2
            }
            count += 1
        } else {              // remove
            count -= 1
            if capacity > 16 && count * fraction <= capacity {
                copied += count
                capacity /= 2
            }
        }
    }
    return copied
}

assert(copies(shrinkBelow: 2, operations: 1_000) == 1_000 * 16)
assert(copies(shrinkBelow: 4, operations: 1_000) == 16)

Starting full, one add doubles the capacity to 32 with 17 items, copying 16, and one remove leaves 16 items, exactly half of 32, so it halves again, copying 16: every single operation copies 16 items. With the quarter rule, after doubling to 32 the list must fall to 8 items before shrinking, so alternating adds and removes never triggers a second resize. (Lesson 30’s rule, “fewer than a quarter”, has the same property.) The gap between the grow and shrink thresholds is what makes the amortized analysis work.

Q5 (optional): A queue from two stacks

A queue can be built from two arrays used as stacks: push onto inbox; to dequeue, pop from outbox, and when outbox is empty, move everything from inbox to it, which reverses the order. Implement it, and argue that each operation is amortized constant time.

Show solution
struct TwoStackQueue<Element> {
    private var inbox: [Element] = []
    private var outbox: [Element] = []
    private(set) var moves = 0

    mutating func enqueue(_ item: Element) {
        inbox.append(item)
    }

    mutating func dequeue() -> Element? {
        if outbox.isEmpty {
            while let item = inbox.popLast() {
                outbox.append(item)
                moves += 1
            }
        }
        return outbox.popLast()
    }
}

var queue = TwoStackQueue<Int>()
var reference: [Int] = []
var generator = SystemRandomNumberGenerator()
for n in 0..<10_000 {
    if Int.random(in: 0..<3, using: &generator) < 2 {
        queue.enqueue(n)
        reference.append(n)
    } else {
        assert(queue.dequeue() == (reference.isEmpty ? nil : reference.removeFirst()))
    }
}
assert(queue.moves <= 10_000)

Each item is moved from inbox to outbox at most once in its life, so the total number of moves is at most the number of enqueues: the same “each item pays for itself” argument as multipop. One dequeue can move thousands of items, but the average is constant. (The test uses removeFirst() on the reference array, which is Θ(N); for a test that only needs to be correct, clarity wins.)

What’s next

That completes the analysis tools. Next lesson: sets and maps, and the binary search tree, the first structure to make lookups faster than linear.