Review II
Exam-style review of search trees, heaps, graphs, shortest paths, hashing, and tries, in the spirit of CS61B’s second midterm review.
CS61B assigns a review homework before its second midterm. This one covers Lessons 38 to 50. As with Review I, try each problem on paper with a time limit first.
Q1: What would Swift print?
What would Swift print?
var heap = [1, 4, 2, 7, 5, 3]
heap.append(0)
var i = heap.count - 1
while i > 0 && heap[i] < heap[(i - 1) / 2] {
heap.swapAt(i, (i - 1) / 2)
i = (i - 1) / 2
}
print(heap)Show answer and explanation
Answer[0, 4, 1, 7, 5, 3, 2]
0 is added at position 6, whose parent is position 2 (holding 2). It swaps with 2, then with the root, 1: two swaps, up the height of the tree.
Q2: Heap or search tree?
Write kthSmallestSoFar(_:k:), which reads a stream of numbers and, after each one,
reports the k-th smallest seen so far (or nil until there are k), in O(log k) per
number. Explain why a max-heap of size k is enough.
Show solution
struct MaxHeap {
private(set) var items: [Int] = []
var top: Int? { items.first }
var count: Int { items.count }
mutating func push(_ x: Int) {
items.append(x)
var i = items.count - 1
while i > 0 && items[i] > items[(i - 1) / 2] {
items.swapAt(i, (i - 1) / 2)
i = (i - 1) / 2
}
}
mutating func replaceTop(_ x: Int) {
items[0] = x
var i = 0
while true {
let (l, r) = (2 * i + 1, 2 * i + 2)
var m = i
if l < items.count && items[l] > items[m] { m = l }
if r < items.count && items[r] > items[m] { m = r }
if m == i { return }
items.swapAt(i, m)
i = m
}
}
}
func kthSmallestSoFar(_ stream: [Int], k: Int) -> [Int?] {
var heap = MaxHeap()
return stream.map { x in
if heap.count < k {
heap.push(x)
} else if x < heap.top! {
heap.replaceTop(x)
}
return heap.count == k ? heap.top : nil
}
}
assert(kthSmallestSoFar([5, 1, 8, 3, 2, 9], k: 2) == [nil, 5, 5, 3, 2, 2])The heap holds the k smallest numbers seen so far; its maximum is exactly the k-th smallest. A new number only matters if it is smaller than that maximum, in which case it replaces it. The heap never grows past k, so each step is O(log k).
Q3: Shortest paths with a twist
In a grid, moving onto a . costs 1 and onto a ~ (mud) costs 5; # is a wall. Find
the cheapest cost from the top-left to the bottom-right corner with Dijkstra’s algorithm.
Show solution
func cheapest(_ grid: [String]) -> Int? {
let cells = grid.map(Array.init)
let (rows, columns) = (cells.count, cells[0].count)
var cost = Array(repeating: Array(repeating: Int.max, count: columns), count: rows)
cost[0][0] = 0
var frontier = [(0, 0, 0)] // (cost, row, column)
while let i = frontier.indices.min(by: { frontier[$0].0 < frontier[$1].0 }) {
let (c, r, col) = frontier.remove(at: i)
if c > cost[r][col] { continue } // an outdated entry
if (r, col) == (rows - 1, columns - 1) { return c }
for (dr, dc) in [(-1, 0), (1, 0), (0, -1), (0, 1)] {
let (nr, nc) = (r + dr, col + dc)
guard (0..<rows).contains(nr), (0..<columns).contains(nc), cells[nr][nc] != "#" else { continue }
let next = c + (cells[nr][nc] == "~" ? 5 : 1)
if next < cost[nr][nc] {
cost[nr][nc] = next
frontier.append((next, nr, nc))
}
}
}
return nil
}
assert(cheapest(["..~.",
".#~.",
"...."]) == 5) // around the mud
assert(cheapest([".~",
"~."]) == 6) // through the mud: no other way
assert(cheapest([".#", "#."]) == nil)BFS would count steps and walk straight through the mud; weights need Dijkstra. The grid is an implicit graph (Lesson 43): neighbors are computed, never stored.
Q4: Hash table resizing
A hash set with separate chaining starts with 4 buckets and doubles when the load factor would exceed 1. After inserting 1 through 20, in order, how many buckets does it have, and how many items were rehashed in total?
Show solution
Resizes happen when inserting the 5th item (4 → 8 buckets, rehashing 4 items), the 9th (8 → 16, rehashing 8), and the 17th (16 → 32, rehashing 16). The table ends with 32 buckets, and 28 items were rehashed: fewer than twice the number of insertions, as the geometric argument promises.
var buckets = 4
var count = 0
var rehashed = 0
for _ in 1...20 {
if count + 1 > buckets {
rehashed += count
buckets *= 2
}
count += 1
}
assert(buckets == 32 && rehashed == 28)Q5: Tries and BSTs
A set of strings must support insert, contains, and “how many strings start with
this prefix?”. Compare a trie with subtree counts and a balanced BST of strings for the
prefix query, for N strings of length L and a prefix of length P.
Show solution
- Trie with counts (Lesson 50’s lab): walk P characters and read the count: Θ(P), independent of N.
- Balanced BST: the strings with the prefix form a contiguous range in sorted order. Find its two ends with two searches, each O(log N) string comparisons of up to P characters, and count the keys between them with rank queries (Homework 15), giving O(P log N).
The trie is faster for this query, and the BST is more compact and also answers general range queries, such as all strings between “cat” and “dog”.