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

BSTMap

Implement a complete ordered map as a binary search tree: put, get, contains, remove with Hibbard deletion, removeAll, count, keys in order through Sequence, and a randomized test against Dictionary.

This homework goes with Lesson 38, like CS61B’s BSTMap homework. You will build a complete ordered map, one problem at a time, and test it against Swift’s own Dictionary. Put everything in hw15.swift.

The map you build follows this protocol, CS61B’s Map61B in Swift:

protocol Map61B<Key, Value> {
    associatedtype Key: Comparable
    associatedtype Value
    var count: Int { get }
    mutating func put(_ key: Key, _ value: Value)
    func get(_ key: Key) -> Value?
    func containsKey(_ key: Key) -> Bool
    mutating func remove(_ key: Key) -> Value?
    mutating func removeAll()
}

Q1: Putting and getting

Write BSTMap<Key: Comparable, Value> as a class with a private nested node class, and implement count, put, get, and containsKey. put on an existing key replaces its value without changing count.

Show solution
final class BSTMap<Key: Comparable, Value> {
    private final class Node {
        let key: Key
        var value: Value
        var left: Node?
        var right: Node?
        init(_ key: Key, _ value: Value) {
            self.key = key
            self.value = value
        }
    }

    private var root: Node?
    private(set) var count = 0

    func put(_ key: Key, _ value: Value) {
        root = put(root, key, value)
    }

    private func put(_ node: Node?, _ key: Key, _ value: Value) -> Node {
        guard let node else {
            count += 1
            return Node(key, value)
        }
        if key < node.key { node.left = put(node.left, key, value) }
        else if key > node.key { node.right = put(node.right, key, value) }
        else { node.value = value }
        return node
    }

    func get(_ key: Key) -> Value? {
        var node = root
        while let current = node {
            if key < current.key { node = current.left }
            else if key > current.key { node = current.right }
            else { return current.value }
        }
        return nil
    }

    func containsKey(_ key: Key) -> Bool {
        get(key) != nil
    }
}

let map = BSTMap<String, Int>()
map.put("hi", 1)
map.put("hello", 2)
map.put("hi", 3)
assert(map.count == 2 && map.get("hi") == 3 && map.get("hey") == nil)
assert(map.containsKey("hello") && !map.containsKey("hey"))

containsKey through get is correct here because values are not optional. For a map whose values could themselves be nil, it would need its own search.

Q2: Keys in order

Make BSTMap a Sequence of (key: Key, value: Value) pairs, in increasing key order, with an iterator that uses an explicit stack instead of recursion, so it produces one pair at a time.

Show solution
final class BSTMap<Key: Comparable, Value> {
    fileprivate final class Node {
        let key: Key
        var value: Value
        var left: Node?
        var right: Node?
        init(_ key: Key, _ value: Value) {
            self.key = key
            self.value = value
        }
    }

    fileprivate var root: Node?
    private(set) var count = 0

    func put(_ key: Key, _ value: Value) {
        root = put(root, key, value)
    }

    private func put(_ node: Node?, _ key: Key, _ value: Value) -> Node {
        guard let node else { count += 1; return Node(key, value) }
        if key < node.key { node.left = put(node.left, key, value) }
        else if key > node.key { node.right = put(node.right, key, value) }
        else { node.value = value }
        return node
    }
}

extension BSTMap: Sequence {
    struct Iterator: IteratorProtocol {
        private var stack: [Node] = []

        fileprivate init(root: Node?) {
            pushLeftPath(from: root)
        }

        private mutating func pushLeftPath(from node: Node?) {
            var node = node
            while let current = node {
                stack.append(current)
                node = current.left
            }
        }

        mutating func next() -> (key: Key, value: Value)? {
            guard let node = stack.popLast() else { return nil }
            pushLeftPath(from: node.right)
            return (node.key, node.value)
        }
    }

    func makeIterator() -> Iterator {
        Iterator(root: root)
    }
}

let map = BSTMap<Int, String>()
for (k, v) in [(5, "e"), (2, "b"), (8, "h"), (1, "a"), (3, "c")] {
    map.put(k, v)
}
assert(map.map(\.key) == [1, 2, 3, 5, 8])
assert(map.map(\.value).joined() == "abceh")
assert(map.first { $0.key > 4 }!.value == "e")

The stack holds the path of nodes whose left subtrees are being visited. Each next takes the top node, then pushes the leftmost path of its right subtree. Every node is pushed and popped once, so a full traversal is Θ(N), and the stack never holds more than the tree’s height.

Q3: Removing

Add remove(_:), which removes a key and returns its value, using Hibbard deletion with the successor, and removeAll().

Show solution
final class BSTMap<Key: Comparable, Value> {
    private final class Node {
        let key: Key
        var value: Value
        var left: Node?
        var right: Node?
        init(_ key: Key, _ value: Value) {
            self.key = key
            self.value = value
        }
    }

    private var root: Node?
    private(set) var count = 0

    func put(_ key: Key, _ value: Value) { root = put(root, key, value) }

    private func put(_ node: Node?, _ key: Key, _ value: Value) -> Node {
        guard let node else { count += 1; return Node(key, value) }
        if key < node.key { node.left = put(node.left, key, value) }
        else if key > node.key { node.right = put(node.right, key, value) }
        else { node.value = value }
        return node
    }

    func get(_ key: Key) -> Value? {
        var node = root
        while let current = node {
            if key < current.key { node = current.left }
            else if key > current.key { node = current.right }
            else { return current.value }
        }
        return nil
    }

    @discardableResult
    func remove(_ key: Key) -> Value? {
        guard let value = get(key) else { return nil }
        root = remove(root, key)
        count -= 1
        return value
    }

    private func remove(_ node: Node?, _ key: Key) -> Node? {
        guard let node else { return nil }
        if key < node.key { node.left = remove(node.left, key); return node }
        if key > node.key { node.right = remove(node.right, key); return node }
        guard let left = node.left else { return node.right }
        guard let right = node.right else { return left }
        var successor = right
        while let smaller = successor.left { successor = smaller }
        successor.right = remove(right, successor.key)
        successor.left = left
        return successor
    }

    func removeAll() {
        root = nil
        count = 0
    }

    var keys: [Key] {
        var result: [Key] = []
        func visit(_ node: Node?) {
            guard let node else { return }
            visit(node.left); result.append(node.key); visit(node.right)
        }
        visit(root)
        return result
    }
}

let map = BSTMap<Int, Int>()
for k in [50, 30, 70, 20, 40, 60, 80] { map.put(k, k * 10) }
assert(map.remove(30) == 300 && map.remove(50) == 500 && map.remove(99) == nil)
assert(map.keys == [20, 40, 60, 70, 80] && map.count == 5)
map.removeAll()
assert(map.count == 0 && map.get(20) == nil)

Looking the key up first makes the count easy to keep right: it only changes when the key was there. removeAll simply drops the root; ARC frees every node, since nothing else refers to them.

Q4: Testing against Dictionary

Write a randomized test that performs 20,000 random put, get, and remove operations on a BSTMap and on a [Int: Int] dictionary, checking after each that they agree, and at the end that the map’s keys are the dictionary’s keys, sorted.

Show solution
final class BSTMap<Key: Comparable, Value> {
    private final class Node {
        let key: Key
        var value: Value
        var left: Node?
        var right: Node?
        init(_ key: Key, _ value: Value) { self.key = key; self.value = value }
    }
    private var root: Node?
    private(set) var count = 0

    func put(_ key: Key, _ value: Value) { root = put(root, key, value) }
    private func put(_ node: Node?, _ key: Key, _ value: Value) -> Node {
        guard let node else { count += 1; return Node(key, value) }
        if key < node.key { node.left = put(node.left, key, value) }
        else if key > node.key { node.right = put(node.right, key, value) }
        else { node.value = value }
        return node
    }
    func get(_ key: Key) -> Value? {
        var node = root
        while let c = node { if key < c.key { node = c.left } else if key > c.key { node = c.right } else { return c.value } }
        return nil
    }
    @discardableResult func remove(_ key: Key) -> Value? {
        guard let value = get(key) else { return nil }
        root = remove(root, key); count -= 1; return value
    }
    private func remove(_ node: Node?, _ key: Key) -> Node? {
        guard let node else { return nil }
        if key < node.key { node.left = remove(node.left, key); return node }
        if key > node.key { node.right = remove(node.right, key); return node }
        guard let left = node.left else { return node.right }
        guard let right = node.right else { return left }
        var s = right
        while let smaller = s.left { s = smaller }
        s.right = remove(right, s.key); s.left = left
        return s
    }
    var keys: [Key] {
        var result: [Key] = []
        func visit(_ n: Node?) { guard let n else { return }; visit(n.left); result.append(n.key); visit(n.right) }
        visit(root)
        return result
    }
}

let map = BSTMap<Int, Int>()
var reference: [Int: Int] = [:]
var generator = SystemRandomNumberGenerator()
for step in 0..<20_000 {
    let key = Int.random(in: 0..<500, using: &generator)
    switch Int.random(in: 0..<3, using: &generator) {
    case 0:
        map.put(key, step)
        reference[key] = step
    case 1:
        assert(map.get(key) == reference[key])
    default:
        assert(map.remove(key) == reference.removeValue(forKey: key))
    }
    assert(map.count == reference.count)
}
assert(map.keys == reference.keys.sorted())

Keys from a small range make collisions, replacements, and removals of present keys common, which is where bugs hide. The dictionary is the trusted reference; the map adds the one thing the dictionary lacks, sorted keys.

Q5 (optional): Order statistics

Store in each node the size of its subtree, keep it correct in put, and use it to write select(_:), the key of rank k (the k-th smallest, from 0), and rank(_:), the number of keys less than a given key, both in time proportional to the height.

Show solution
final class RankedMap<Key: Comparable> {
    private final class Node {
        let key: Key
        var left: Node?
        var right: Node?
        var size = 1
        init(_ key: Key) { self.key = key }
    }

    private var root: Node?

    private func size(_ node: Node?) -> Int { node?.size ?? 0 }

    func insert(_ key: Key) { root = insert(root, key) }

    private func insert(_ node: Node?, _ key: Key) -> Node {
        guard let node else { return Node(key) }
        if key < node.key { node.left = insert(node.left, key) }
        else if key > node.key { node.right = insert(node.right, key) }
        node.size = 1 + size(node.left) + size(node.right)
        return node
    }

    func select(_ k: Int) -> Key? {
        var node = root
        var k = k
        while let current = node {
            let leftSize = size(current.left)
            if k < leftSize { node = current.left }
            else if k > leftSize { k -= leftSize + 1; node = current.right }
            else { return current.key }
        }
        return nil
    }

    func rank(_ key: Key) -> Int {
        var node = root
        var rank = 0
        while let current = node {
            if key < current.key { node = current.left }
            else if key > current.key { rank += size(current.left) + 1; node = current.right }
            else { return rank + size(current.left) }
        }
        return rank
    }
}

let map = RankedMap<Int>()
for k in [50, 30, 70, 20, 40, 60, 80] { map.insert(k) }
assert((0..<7).map { map.select($0)! } == [20, 30, 40, 50, 60, 70, 80])
assert(map.rank(50) == 3 && map.rank(45) == 3 && map.rank(10) == 0 && map.rank(99) == 7)
assert(map.select(7) == nil)

A node’s left subtree holds exactly the keys smaller than it within its subtree, so its size says whether rank k is to the left, at the node, or to the right. Recomputing size on the way back up from put keeps every size correct with no extra walk.