Asymptotic analysis
A theory homework: derive orders of growth for tricky loops and recursions, check each by counting, solve recurrences, prove a bound, and compare Θ, O, and Ω claims.
This homework goes with Lessons 34 to 37, like CS61B’s asymptotics homework. For each function, work out the answer on paper first, then check it by counting, as the solutions do. Several functions here are designed so that the first guess is wrong.
Each problem uses this counter:
var count = 0
func work() { count += 1 }
Q1: A tripling loop
func p1(_ n: Int) {
var i = 1
while i < n {
for _ in 0..<i { work() }
i *= 3
}
}
Show solution
Θ(N). The inner loop runs 1, 3, 9, … times, up to the largest power of 3 below N: a geometric sum, less than 1.5 times its last term. For N = 729 = 3⁶, the powers below it are 1 to 243, which add up to 364.
var count = 0
func work() { count += 1 }
func p1(_ n: Int) {
var i = 1
while i < n {
for _ in 0..<i { work() }
i *= 3
}
}
p1(729)
assert(count == (729 - 1) / 2)Q2: A shrinking inner loop
func p2(_ n: Int) {
for i in 1...n {
var j = n
while j > i {
work()
j /= 2
}
}
}
Show solution
Θ(N), although it looks like N log N. For each i, the inner loop halves j
from N until it is at most i: about log₂(N / i) steps. For most i that is small:
half the values of i are above N / 2 and take at most one step, a quarter take at
most two, and so on. The total is roughly log₂(N / 1) + log₂(N / 2) + … +
log₂(N / N), which is about 1.44 N; rounding each count up to a whole number of
halvings adds up to one more step per i, and the measured total is close to 2N.
var count = 0
func work() { count += 1 }
func p2(_ n: Int) {
for i in 1...n {
var j = n
while j > i {
work()
j /= 2
}
}
}
var counts: [Int] = []
for n in [1_000, 2_000, 4_000, 8_000] {
count = 0
p2(n)
counts.append(count)
}
let ratios = zip(counts, counts.dropFirst()).map { Double($1) / Double($0) }
assert(ratios.allSatisfy { abs($0 - 2) < 0.05 }) // doubling: linear
assert(counts.allSatisfy { $0 < 2 * 8_000 })The doubling ratios settle at 2, the fingerprint of linear growth. The upper bound N log N is true, but not tight.
Q3: Two recursions
Give recurrences and orders of growth for both, and check them.
func p3(_ n: Int) {
if n <= 1 { work(); return }
p3(n - 1)
for _ in 0..<n { work() }
}
func p4(_ n: Int) {
if n <= 1 { return }
for _ in 0..<n { work() }
p4(n / 3)
p4(n / 3)
p4(n / 3)
}
Show solution
p3: T(N) = T(N − 1) + N, so N + (N − 1) + … + 2 + 1: Θ(N²).p4: T(N) = 3T(N/3) + N. Each level of the tree does N work in total and there are log₃ N levels: Θ(N log N), like merge sort but splitting in three.
var count = 0
func work() { count += 1 }
func p3(_ n: Int) {
if n <= 1 { work(); return }
p3(n - 1)
for _ in 0..<n { work() }
}
func p4(_ n: Int) {
if n <= 1 { return }
for _ in 0..<n { work() }
p4(n / 3)
p4(n / 3)
p4(n / 3)
}
count = 0; p3(729); assert(count == 729 * 730 / 2)
count = 0; p4(729); assert(count == 729 * 6) // 729 = 3⁶: six levelsQ4: Proving a bound
Prove that 3N² − 10N + 5 ∈ Θ(N²) by giving k₁, k₂, and N₀, and check the inequality for every N from N₀ to 100,000.
Show solution
For the upper bound, 3N² − 10N + 5 ≤ 3N² + 5 ≤ 4N² once N² ≥ 5, so for N ≥ 3. For the lower bound, 3N² − 10N + 5 ≥ 2N² when N² ≥ 10N − 5, which holds for N ≥ 10. So k₁ = 2, k₂ = 4, N₀ = 10.
func r(_ n: Int) -> Int { 3 * n * n - 10 * n + 5 }
for n in 10...100_000 {
assert(2 * n * n <= r(n) && r(n) <= 4 * n * n)
}
assert(r(3) < 2 * 3 * 3) // the lower bound fails for small N, as it mayBig Theta only speaks about large N. For small N the function can even be negative (r(2) = −3), and the bound is still true.
Q5: True or false
- N² ∈ O(2ᴺ).
- log(N!) ∈ Θ(N log N).
- If f ∈ O(g) and g ∈ O(h), then f ∈ O(h).
- If f ∈ Θ(g), then 2^f ∈ Θ(2^g).
- The worst case of merge sort is Θ(N log N), and its best case is Θ(N).
Show solution
- True. Every polynomial is eventually below every exponential.
- True. log(N!) ≤ log(Nᴺ) = N log N, and log(N!) ≥ log((N/2)^(N/2)) = (N/2) log(N/2), which is Ω(N log N). Lesson 56 uses this to bound sorting.
- True. Multiply the constants: f ≤ k₁g ≤ k₁k₂h.
- False. f = 2N and g = N are Θ of each other, but 2^(2N) = 4ᴺ is not Θ(2ᴺ).
- False. Merge sort always splits and merges completely: its best case is also Θ(N log N), though it makes fewer comparisons on sorted input.
Q6 (optional): Worst and best cases
This function is a “lazy” duplicate finder. Give its best-case and worst-case orders of growth, and an input of each kind.
func firstRepeat(_ values: [Int]) -> Int? {
var seen: [Int] = []
for value in values {
if seen.contains(value) { return value }
seen.append(value)
}
return nil
}
Show solution
- Best case, Θ(1): the first two items are equal, such as
[7, 7, …]. - Worst case, Θ(N²): no repeats, so every item is checked against every earlier one: 0 + 1 + … + (N − 1) comparisons.
var comparisons = 0
func firstRepeat(_ values: [Int]) -> Int? {
var seen: [Int] = []
for value in values {
for s in seen {
comparisons += 1
if s == value { return value }
}
seen.append(value)
}
return nil
}
comparisons = 0
assert(firstRepeat([7, 7] + Array(0..<1_000)) == 7 && comparisons == 1)
comparisons = 0
assert(firstRepeat(Array(0..<1_000)) == nil && comparisons == 1_000 * 999 / 2)With a Set for seen, the worst case becomes Θ(N), since each check takes
constant time on average.