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

Tries and prefix operations

Storing strings character by character: the trie, lookups in time proportional to the key’s length, ways to store children, prefix queries such as keys with a prefix and longest prefix, and autocomplete.

CS61B
Tries · Textbook Ch. 26
Documentation
String

When the keys are strings, a general-purpose map treats each key as an opaque value to hash or compare. But strings have structure: many share beginnings, “car”, “card”, “care”, “cart”. A trie, CS61B’s last search structure, is built around that structure, and it answers questions about prefixes that hash tables cannot, such as “every word starting with car”.

Tries

A trie (from retrieval, pronounced “try”) stores strings character by character. Each node has children, one for each character that can come next, and a flag saying whether the path from the root to this node spells a stored key:

(root)
└─ c
   └─ a
      ├─ r ★
      │  ├─ d ★
      │  ├─ e ★
      │  └─ t ★
      └─ t ★

Here ★ marks nodes whose path is a key: “car”, “cat”, “card”, “care”, and “cart”. The five words share the path c–a, and the prefix “car” is stored once.

final class Trie {
    private final class Node {
        var children: [Character: Node] = [:]
        var isKey = false
    }

    private let root = Node()
    private(set) var count = 0

    func insert(_ word: String) {
        var node = root
        for character in word {
            if let next = node.children[character] {
                node = next
            } else {
                let next = Node()
                node.children[character] = next
                node = next
            }
        }
        if !node.isKey {
            node.isKey = true
            count += 1
        }
    }

    private func node(for prefix: String) -> Node? {
        var node = root
        for character in prefix {
            guard let next = node.children[character] else { return nil }
            node = next
        }
        return node
    }

    func contains(_ word: String) -> Bool {
        node(for: word)?.isKey ?? false
    }

    func keys(withPrefix prefix: String) -> [String] {
        guard let start = node(for: prefix) else { return [] }
        var result: [String] = []
        func collect(_ node: Node, _ path: String) {
            if node.isKey { result.append(path) }
            for (character, child) in node.children.sorted(by: { $0.key < $1.key }) {
                collect(child, path + String(character))
            }
        }
        collect(start, prefix)
        return result
    }
}

let trie = Trie()
for word in ["car", "cat", "card", "care", "cart", "dog"] {
    trie.insert(word)
}
print(trie.contains("car"), trie.contains("ca"), trie.keys(withPrefix: "car"), trie.count)
// true false ["car", "card", "care", "cart"] 6

contains("ca") is false: the path exists, but no key ends there. That is the job of the isKey flag.

What it costs

Looking up a key of length L follows L links, one per character, and then checks a flag. That is Θ(L), and it does not depend on N, the number of keys stored. A hash table also spends Θ(L) hashing the key, and a search tree spends Θ(log N) comparisons, each of which may read up to L characters; for strings, the trie is often the fastest, and it never needs to hash or compare whole keys.

The price is memory: a node per character of every key, minus shared prefixes, each with a structure for its children. How the children are stored is a real choice:

Children stored as Lookup of one child Memory per node
an array indexed by character code (CS61B’s DataIndexedCharMap) Θ(1) one slot per possible character, even if unused
a hash table, as here Θ(1) on average proportional to the actual children
a search tree O(log R), for R possible characters proportional to the actual children

An array of 128 slots per node is fast for ASCII keys but wasteful when nodes have one or two children, which most do. A dictionary adapts to Unicode keys, which Swift strings make natural: a Character can be “é” or a flag emoji.

What would Swift print?

var nodes = 1
var children: [String: Set<Character>] = [:]
for word in ["tea", "ten", "to", "team"] {
    var prefix = ""
    for c in word {
        if children[prefix, default: []].insert(c).inserted {
            nodes += 1
        }
        prefix.append(c)
    }
}
print(nodes)

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

Show answer and explanation

Answer7

Count the nodes of the trie: the root, then one for each distinct prefix: t, te, tea, ten, to, and team. Shared prefixes are stored once: “team” adds only one node, after “tea”. That is 1 + 6 = 7 nodes for 13 characters in the four words.

Prefix operations

A trie answers questions about prefixes by walking to the prefix’s node and looking below it:

  • Keys with a prefix, as above: walk to the prefix, then collect every key in that subtree. The cost is the prefix’s length plus the size of the answer.
  • Longest prefix of a string that is a key: walk along the string as far as possible, remembering the last node whose flag was set. A router uses this to choose the most specific route for an address; a tokenizer, to find the longest keyword at the start of the input.
func longestPrefix(of text: String) -> String {
    var node = root
    var longest = ""
    var path = ""
    for character in text {
        guard let next = node.children[character] else { break }
        path.append(character)
        node = next
        if node.isKey { longest = path }
    }
    return longest
}
// With car, card, care, cart stored: longestPrefix(of: "cardigan") is "card",
// and longestPrefix(of: "carbon") is "car".

A hash table has no notion of “keys that start with” and would have to examine every key. A search tree can find the range of keys between “car” and “cas”, which works too, with comparisons of whole strings.

Autocomplete

Typing “car” into a search box shows the most popular completions. With a weight on every key, how often it is searched, a trie finds them: walk to the prefix, then collect the keys below it and keep the k heaviest, with Lesson 41’s heap if the subtree is large. Search engines precompute more, storing in each node the best completions of its subtree, so a query costs only the walk to the prefix.

Put the lines in order

Put the lines in order so the program prints true false.

  1. let isPrefix = words.contains { $0.hasPrefix(prefix) }
  2. var words: Set<String> = ["car", "cart"]
  3. print(isPrefix, words.contains(prefix))
  4. let prefix = "ca"

Show the correct program
var words: Set<String> = ["car", "cart"]
let prefix = "ca"
let isPrefix = words.contains { $0.hasPrefix(prefix) }
print(isPrefix, words.contains(prefix))

Lab 49: Tries

Q0: What would Swift print?

What would Swift print?

final class Node {
    var children: [Character: Node] = [:]
    var isKey = false
}
let root = Node()
func insert(_ word: String) {
    var node = root
    for c in word {
        let next = node.children[c] ?? Node()
        node.children[c] = next
        node = next
    }
    node.isKey = true
}
for w in ["an", "and", "ant", "any"] { insert(w) }
let a = root.children["a"]!
let n = a.children["n"]!
print(root.children.count, a.isKey, n.isKey, n.children.count)

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

Show answer and explanation

Answer1 false true 3

Every word starts with “a”, so the root has one child. “a” alone is not a key, but “an” is. Below “an” are three children: d, t, and y.

Q1: Removing

Add remove(_:) to the lesson’s Trie: clear the key’s flag, then remove the nodes that no longer lead to any key, from the end of the word back toward the root. Check that removing “card” leaves “car” and “cart” in place and deletes the d node.

Show solution
final class Trie {
    private final class Node {
        var children: [Character: Node] = [:]
        var isKey = false
    }

    private let root = Node()
    private(set) var count = 0
    var nodeCount: Int {
        func size(_ n: Node) -> Int { 1 + n.children.values.map(size).reduce(0, +) }
        return size(root)
    }

    func insert(_ word: String) {
        var node = root
        for c in word {
            let next = node.children[c] ?? Node()
            node.children[c] = next
            node = next
        }
        if !node.isKey { node.isKey = true; count += 1 }
    }

    func contains(_ word: String) -> Bool {
        var node = root
        for c in word {
            guard let next = node.children[c] else { return false }
            node = next
        }
        return node.isKey
    }

    func remove(_ word: String) {
        var path: [(node: Node, character: Character)] = []
        var node = root
        for c in word {
            guard let next = node.children[c] else { return }
            path.append((node, c))
            node = next
        }
        guard node.isKey else { return }
        node.isKey = false
        count -= 1
        // Walk back up, removing nodes that are neither keys nor lead to keys.
        var current = node
        while let (parent, c) = path.popLast(), !current.isKey, current.children.isEmpty {
            parent.children[c] = nil
            current = parent
        }
    }
}

let trie = Trie()
for w in ["car", "card", "cart"] { trie.insert(w) }
let before = trie.nodeCount
trie.remove("card")
assert(!trie.contains("card") && trie.contains("car") && trie.contains("cart"))
assert(trie.nodeCount == before - 1 && trie.count == 2)
trie.remove("car")
assert(trie.nodeCount == before - 1)      // "car" still leads to "cart", so no nodes go

Removing a key only removes nodes that became useless: those with no children that are not keys themselves. The loop stops at the first node that is still needed.

Q2: Counting by prefix

Store in each node the number of keys in its subtree, so that count(withPrefix:) takes time proportional to the prefix’s length alone, not the number of matching keys.

Show solution
final class CountingTrie {
    private final class Node {
        var children: [Character: Node] = [:]
        var isKey = false
        var below = 0            // keys in this subtree, including this node
    }

    private let root = Node()

    func insert(_ word: String) {
        guard !contains(word) else { return }
        var node = root
        node.below += 1
        for c in word {
            let next = node.children[c] ?? Node()
            node.children[c] = next
            node = next
            node.below += 1
        }
        node.isKey = true
    }

    func contains(_ word: String) -> Bool {
        var node = root
        for c in word {
            guard let next = node.children[c] else { return false }
            node = next
        }
        return node.isKey
    }

    func count(withPrefix prefix: String) -> Int {
        var node = root
        for c in prefix {
            guard let next = node.children[c] else { return 0 }
            node = next
        }
        return node.below
    }
}

let trie = CountingTrie()
for w in ["car", "card", "care", "cart", "cat", "dog", "car"] { trie.insert(w) }
assert(trie.count(withPrefix: "car") == 4 && trie.count(withPrefix: "ca") == 5)
assert(trie.count(withPrefix: "") == 6 && trie.count(withPrefix: "x") == 0)

Inserting a duplicate must not change the counts, which is why insert checks first. Every node on the path of a new key gains one key below it.

Q3: Autocomplete

Given words with weights, write complete(_:k:), which returns the k heaviest keys starting with a prefix, heaviest first, with ties broken alphabetically.

Show solution
final class WeightedTrie {
    private final class Node {
        var children: [Character: Node] = [:]
        var weight: Int?            // nil: not a key
    }

    private let root = Node()

    func insert(_ word: String, weight: Int) {
        var node = root
        for c in word {
            let next = node.children[c] ?? Node()
            node.children[c] = next
            node = next
        }
        node.weight = weight
    }

    func complete(_ prefix: String, k: Int) -> [String] {
        var node = root
        for c in prefix {
            guard let next = node.children[c] else { return [] }
            node = next
        }
        var found: [(word: String, weight: Int)] = []
        func collect(_ node: Node, _ path: String) {
            if let w = node.weight { found.append((path, w)) }
            for (c, child) in node.children { collect(child, path + String(c)) }
        }
        collect(node, prefix)
        return found.sorted { $0.weight != $1.weight ? $0.weight > $1.weight : $0.word < $1.word }
            .prefix(k).map(\.word)
    }
}

let trie = WeightedTrie()
for (word, weight) in [("swift", 90), ("swiftui", 70), ("switch", 70), ("swim", 40), ("sword", 10)] {
    trie.insert(word, weight: weight)
}
assert(trie.complete("sw", k: 3) == ["swift", "swiftui", "switch"])
assert(trie.complete("swi", k: 10) == ["swift", "swiftui", "switch", "swim"])
assert(trie.complete("x", k: 3).isEmpty)

This collects every completion and sorts them, which is fine for small subtrees. For a search engine, where “s” may have millions of completions, each node would store its subtree’s top k, making every query as fast as the walk to the prefix.

Q4 (optional): Longest common prefix

Write longestCommonPrefix(_:) for a list of words using a trie: insert them all, then walk from the root while the current node has exactly one child and is not the end of a word.

Show solution
final class Node {
    var children: [Character: Node] = [:]
    var isKey = false
}

func longestCommonPrefix(_ words: [String]) -> String {
    guard !words.isEmpty else { return "" }
    let root = Node()
    for word in words {
        var node = root
        for c in word {
            let next = node.children[c] ?? Node()
            node.children[c] = next
            node = next
        }
        node.isKey = true
    }
    var prefix = ""
    var node = root
    while !node.isKey, node.children.count == 1, let (c, child) = node.children.first {
        prefix.append(c)
        node = child
    }
    return prefix
}

assert(longestCommonPrefix(["interview", "internet", "interval"]) == "inter")
assert(longestCommonPrefix(["swift", "swim"]) == "swi")
assert(longestCommonPrefix(["car", "cart"]) == "car")        // stops at the end of "car"
assert(longestCommonPrefix(["abc", "xyz"]) == "")

The walk stops at the first branch, where the words disagree, or at the end of a word, since a prefix cannot be longer than the shortest word.

What’s next

That finishes CS61B’s search structures. Next lesson: software engineering, and why large programs become hard to change.