Final review
Exam-style review of the last third of the course: heaps, shortest paths, minimum spanning trees, hashing, sorting and its lower bound, radix sorts, and compression.
CS61B ends with a review homework before the final. This one covers the whole second half of the course, with an emphasis on Lessons 45 to 58. Try every problem on paper before opening its solution.
Q1: What would Swift print?
What would Swift print?
let edges = [(0, 1, 4), (0, 2, 1), (1, 2, 2), (1, 3, 5), (2, 3, 8), (3, 4, 3), (2, 4, 9)]
var inTree: Set<Int> = [0]
var order: [Int] = []
var total = 0
while inTree.count < 5 {
let e = edges.filter { inTree.contains($0.0) != inTree.contains($0.1) }
.min { $0.2 < $1.2 }!
let v = inTree.contains(e.0) ? e.1 : e.0
inTree.insert(v)
order.append(v)
total += e.2
}
print(order, total)Show answer and explanation
Answer[2, 1, 3, 4] 11
This is Prim’s algorithm, written simply: each step adds the cheapest edge crossing the cut between the tree and the rest. From 0 it takes 0–2 (1), then 2–1 (2), then 1–3 (5), the cheapest way to reach 3, and finally 3–4 (3). The total is 1 + 2 + 5 + 3 = 11.
Q2: Kruskal on the same graph
Run Kruskal’s algorithm on the graph of Q1. List the weights of the edges it adds, in order, and name each edge it skips before finishing, with the reason.
Show solution
Sorted by weight: 0–2 (1), 1–2 (2), 3–4 (3), 0–1 (4), 1–3 (5), 2–3 (8), 2–4 (9).
- Adds 1, 2, and 3.
- Skips 0–1 (4): 0 and 1 are already connected through 2, so it would close a cycle.
- Adds 5 (1–3), joining 2 with 4. All five vertices are connected; the remaining edges are skipped for the same reason.
The added weights are 1, 2, 3, 5, total 11: the same tree as Prim’s, as it must be, because all the weights are distinct and the MST is then unique.
let edges = [(0, 1, 4), (0, 2, 1), (1, 2, 2), (1, 3, 5), (2, 3, 8), (3, 4, 3), (2, 4, 9)]
var parent = Array(0..<5)
func find(_ x: Int) -> Int {
var x = x
while parent[x] != x { x = parent[x] }
return x
}
var added: [Int] = []
for (u, v, w) in edges.sorted(by: { $0.2 < $1.2 }) {
let (a, b) = (find(u), find(v))
if a != b {
parent[a] = b
added.append(w)
}
}
assert(added == [1, 2, 3, 5])Q3: Huffman coding
Characters appear with these frequencies: a 45, b 13, c 12, d 16, e 9, f 5. Build a Huffman code. How many bits does each character get, and how many bits does the whole text of 100 characters take? How does that compare with a fixed-length code?
Show solution
Merging the two smallest trees each time: e + f = 14; c + b = 25; 14 + d = 30; 25 + 30 = 55; a + 55 = 100. The code lengths are a: 1, b, c, d: 3, and e, f: 4. The text takes 45·1 + (13 + 12 + 16)·3 + (9 + 5)·4 = 224 bits. A fixed-length code needs 3 bits for 6 characters: 300 bits. Huffman saves a quarter.
let frequency: [Character: Int] = ["a": 45, "b": 13, "c": 12, "d": 16, "e": 9, "f": 5]
var trees: [(weight: Int, characters: [Character])] = frequency.map { ($0.value, [$0.key]) }
var length: [Character: Int] = [:]
while trees.count > 1 {
trees.sort { $0.weight < $1.weight }
let (x, y) = (trees.removeFirst(), trees.removeFirst())
for c in x.characters + y.characters { length[c, default: 0] += 1 } // one level deeper
trees.append((x.weight + y.weight, x.characters + y.characters))
}
assert(length == ["a": 1, "b": 3, "c": 3, "d": 3, "e": 4, "f": 4])
assert(frequency.reduce(0) { $0 + $1.value * length[$1.key]! } == 224)Q4: Choosing algorithms
For each task, name the algorithm or data structure and its running time.
- The 100 largest of 10⁹ numbers arriving one at a time, with little memory.
- Shortest driving routes between two cities in a road network, with a good estimate of the remaining distance.
- The order to take courses given their prerequisites.
- Removing duplicates from 10⁷ strings.
- Sorting 10⁸ 32-bit integers.
- Cheapest set of cables connecting all the buildings on a campus.
Show solution
- A min-heap of size 100: keep the 100 largest so far, replacing the minimum when a larger number arrives. Θ(N log 100) time and Θ(100) memory.
- A* with the straight-line distance as heuristic (Lesson 45): Dijkstra’s O((V + E) log V) at worst, usually far fewer vertices explored.
- Topological sort (Lesson 47): Θ(V + E); it also detects a cycle, which makes the courses impossible.
- A hash set: expected Θ(N L) for N strings of length L.
- LSD radix sort on bytes: 4 passes, Θ(4(N + 256)) = Θ(N).
- A minimum spanning tree, with Kruskal or Prim: Θ(E log E) or Θ(E log V).
Q5: True or false?
- Dijkstra’s algorithm works with negative edge weights if no cycle is negative.
- Every comparison sort takes Ω(N log N) time on every input.
- The heaviest edge in a cycle is never in any minimum spanning tree, if weights are distinct.
- A hash table’s worst-case lookup is Θ(N).
- No lossless compression algorithm can shrink every file.
- Heapsort is stable.
Show solution
- False. Dijkstra finalizes a vertex when it leaves the queue; a negative edge discovered later could still make its path shorter. (Bellman-Ford handles negative weights.)
- False. The bound is for the worst case. Insertion sort takes Θ(N) on a sorted input.
- True. That is the cycle property: replacing it with another edge of the cycle always gives a lighter spanning tree.
- True. If every key hashes to the same bucket, a lookup scans all of them. The expected Θ(1) depends on a good spread.
- True. There are 2ᴺ files of N bits and only 2ᴺ − 1 shorter ones, so some file must stay the same length or grow (Lesson 58’s counting argument).
- False. Moving the maximum to the end jumps it past equal items. For example,
heapifying
[1a, 1b]keeps 1a at the root, which is then moved to the end:[1b, 1a].
Q6: Exam-level: the shortest path tree
A graph has a shortest path tree from s computed with Dijkstra. Then every edge weight is doubled. Is the tree still a shortest path tree? What if 1 is added to every weight instead?
Show solution
- Doubling: yes. Every path’s length doubles, so the order of all path lengths is unchanged, and the shortest ones stay the shortest.
- Adding 1: not necessarily. A path with k edges grows by k, so paths with many edges are penalized. Counterexample: the path s–a–t with weights 1 and 1 (length 2) and a direct edge s–t with weight 2.5. Before, s–a–t wins, 2 against 2.5. After adding 1, s–a–t has length 4 and s–t has 3.5, so the direct edge wins and the tree changes.