Exercises
Fifteen problems covering the whole course, from correctness proofs to probabilistic analysis. Try each one on paper first. Every problem has a short Answer to check yourself against and a full Solution; some solutions include a program that confirms the result by counting, which you can edit and run.
Tip: When a problem asks for a bound or a count, test the smallest cases by hand () before you generalise. Most wrong formulas are already wrong at .
| # | Exercise | Practises |
|---|---|---|
| 1 | An invariant for FIND-MAX |
loop invariants |
| 2 | Linear search that may fail | invariants with an early exit |
| 3 | Counting 1-bits recursively | induction on a recursive procedure |
| 4 | Three nested loops | exact step counting |
| 5 | Bubble sort with an early exit | best and worst case |
| 6 | A proof with constants | the definition of |
| 7 | True or false | , , and exponentials |
| 8 | Order these functions | comparing growth rates |
| 9 | From code to recurrence | writing and solving a recurrence |
| 10 | Four master-theorem problems | the master theorem |
| 11 | Substitution with a lower-order term | the substitution method |
| 12 | How often does the maximum change? | indicator random variables |
| 13 | A shuffle that looks fine | random permutations |
| 14 | Colliding hash values | the birthday paradox |
| 15 | Rolling every face | the coupon collector |
Exercise 1: An invariant for FIND-MAX
FIND-MAX from the Introduction sets best = a[0] and then, for to , replaces best by when is larger. State a loop invariant and prove the procedure correct.
Answer
At the start of the iteration for , best .
Solution
Initialization: before , best . Maintenance: if best , the body sets best to the larger of that and , which is . Termination: the loop ends with , so best , the maximum of the whole array. The loop runs times, so it terminates.
Exercise 2: Linear search that may fail
LINEAR-SEARCH(a, x) checks in turn, returns the first index with , and returns if the loop finishes. Give an invariant that proves both possible results correct.
Answer
At the start of the iteration for : does not occur in .
Solution
Initially is empty, so does not occur in it. If the iteration for does not return, then , so does not occur in either. If it returns , then and by the invariant no earlier position holds , so is the first occurrence. If the loop ends normally, and the invariant says does not occur in , so is correct.
Exercise 3: Counting 1-bits recursively
ONES(n) returns if , and otherwise $(n \bmod 2) + $ ONES. Prove by induction that it returns the number of 1-bits in the binary representation of , and count its calls.
Answer
Correct by strong induction on ; for it makes calls in total (one per bit, plus the final call with ).
Solution
Base case: has no 1-bits. For , the lowest bit of is , and the remaining bits form , which by the induction hypothesis ONES counts correctly. The sum is the number of 1-bits of . The arguments are one per binary digit, of them, and then one more call with . See Proving Recursive Algorithms Correct by Induction.
In C++, the program below checks ONES against std::popcount and counts the calls:
#include <bit>
#include <cstdio>
#include <initializer_list>
int ones(unsigned n, int& calls) {
calls++;
if (n == 0) return 0;
return n % 2 + ones(n / 2, calls);
}
int main() {
for (unsigned n : {1u, 2u, 7u, 8u, 100u, 1000u, 4294967295u}) {
int calls = 0;
int result = ones(n, calls);
// std::popcount counts the 1-bits directly; std::bit_width(n) is floor(lg n) + 1
std::printf("n = %10u: ONES = %2d, popcount = %2d, calls = %2d, floor(lg n) + 2 = %2d\n",
n, result, std::popcount(n), calls, (int)std::bit_width(n) + 1);
}
}n = 1: ONES = 1, popcount = 1, calls = 2, floor(lg n) + 2 = 2
n = 2: ONES = 1, popcount = 1, calls = 3, floor(lg n) + 2 = 3
n = 7: ONES = 3, popcount = 3, calls = 4, floor(lg n) + 2 = 4
n = 8: ONES = 1, popcount = 1, calls = 5, floor(lg n) + 2 = 5
n = 100: ONES = 3, popcount = 3, calls = 8, floor(lg n) + 2 = 8
n = 1000: ONES = 6, popcount = 6, calls = 11, floor(lg n) + 2 = 11
n = 4294967295: ONES = 32, popcount = 32, calls = 33, floor(lg n) + 2 = 33
Exercise 4: Three nested loops
How many times does the innermost line run, as an exact function of ?
1 for i = 0 to n - 1
2 for j = i + 1 to n - 1
3 for k = j + 1 to n - 1
4 count = count + 1Answer
, which is .
Solution
Each execution of line 4 corresponds to exactly one triple of indices from , and every such triple occurs once. The number of 3-element subsets of an -element set is . The program confirms it.
from math import comb
def triple_count(n):
count = 0
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
count += 1
return count
for n in [0, 1, 2, 3, 4, 10, 30]:
print(f"n = {n:>2}: counted {triple_count(n):>5}, n(n-1)(n-2)/6 = {n * (n - 1) * (n - 2) // 6:>5}, C(n, 3) = {comb(n, 3)}")n = 0: counted 0, n(n-1)(n-2)/6 = 0, C(n, 3) = 0
n = 1: counted 0, n(n-1)(n-2)/6 = 0, C(n, 3) = 0
n = 2: counted 0, n(n-1)(n-2)/6 = 0, C(n, 3) = 0
n = 3: counted 1, n(n-1)(n-2)/6 = 1, C(n, 3) = 1
n = 4: counted 4, n(n-1)(n-2)/6 = 4, C(n, 3) = 4
n = 10: counted 120, n(n-1)(n-2)/6 = 120, C(n, 3) = 120
n = 30: counted 4060, n(n-1)(n-2)/6 = 4060, C(n, 3) = 4060
Exercise 5: Bubble sort with an early exit
Bubble sort makes passes over the array, swapping adjacent out-of-order pairs; pass (for ) compares positions to , and the algorithm stops after the first pass that makes no swap. Count the comparisons in the best and worst case.
Answer
Best case (already sorted): comparisons. Worst case (reversed): .
Solution
On sorted input the first pass makes comparisons and no swaps, so the algorithm stops. On reversed input every pass swaps, so all passes run, with comparisons: in total. The best case is and the worst , like insertion sort; see Worst, Best and Average Case.
Exercise 6: A Theta proof with constants
Prove by giving explicit constants and .
Answer
, , .
Solution
Upper bound: for , , so . Lower bound: is equivalent to , which holds for (at the left side is , and it increases from there), but fails at . So for all . See O, Omega and Theta.
Exercise 7: True or false
(a) . (b) . (c) . (d) . (e) .
Answer
(a) true, (b) false, (c) true, (d) true, (e) false.
Solution
(a) , a constant multiple. (b) , so no constant bounds the ratio. (c) . (d) . (e) , so is , which rules out . See Little o, Little omega and Limits.
Exercise 8: Order these functions
Sort by order of growth, slowest first: , , , , , , , , .
Answer
, , , , , , , , .
Solution
The iterated logarithm is the slowest-growing function here. Any power of is for every , so , and for the same reason . Writing shows it is superpolynomial but , since . Finally . See Comparing Growth Rates.
Exercise 9: From code to recurrence
The procedure below does units of work and then recurses on three halves of its input (the first half, the second half and the middle half). Write its recurrence and solve it.
WORK(a) // n = length of a
1 if n <= 1
2 return
3 scan all n elements once // n units of work
4 h = floor(n / 2), q = floor(n / 4)
5 WORK(a[0:h])
6 WORK(a[h:n])
7 WORK(a[q:q + h])Answer
, so . Charging one unit for a call that stops at once, , and for a power of 2 the exact solution is .
Solution
Three subproblems of size and linear extra work give , , . Since grows polynomially faster than , case 1 of the master theorem gives . For , , and the exact formula satisfies the recurrence: . The program counts the work.
def work(a):
n = len(a)
if n <= 1:
return 1
total = n # one pass over the input
h, q = n // 2, n // 4
total += work(a[:h]) + work(a[h:]) + work(a[q:q + h])
return total
for k in range(0, 11, 2):
n = 2 ** k
print(f"n = {n:>5}: counted {work(list(range(n))):>7}, formula 3*3^k - 2n = {3 * 3**k - 2 * n:>7}")n = 1: counted 1, formula 3*3^k - 2n = 1
n = 4: counted 19, formula 3*3^k - 2n = 19
n = 16: counted 211, formula 3*3^k - 2n = 211
n = 64: counted 2059, formula 3*3^k - 2n = 2059
n = 256: counted 19171, formula 3*3^k - 2n = 19171
n = 1024: counted 175099, formula 3*3^k - 2n = 175099
In C++, the three sub-arrays can be std::span views, so the recursion copies nothing:
#include <cstdio>
#include <numeric>
#include <span>
#include <vector>
// a span is a view of part of an array: the three recursive calls copy nothing
long work(std::span<const int> a) {
long n = (long)a.size();
if (n <= 1) return 1;
long total = n; // one pass over the input
std::size_t h = n / 2, q = n / 4;
total += work(a.first(h)) + work(a.subspan(h)) + work(a.subspan(q, h));
return total;
}
int main() {
long pow3 = 1; // 3^k
for (int k = 0; k <= 10; k += 2, pow3 *= 9) {
long n = 1L << k;
std::vector<int> a(n);
std::iota(a.begin(), a.end(), 0);
std::printf("n = %5ld: counted %7ld, formula 3*3^k - 2n = %7ld\n",
n, work(a), 3 * pow3 - 2 * n);
}
}n = 1: counted 1, formula 3*3^k - 2n = 1
n = 4: counted 19, formula 3*3^k - 2n = 19
n = 16: counted 211, formula 3*3^k - 2n = 211
n = 64: counted 2059, formula 3*3^k - 2n = 2059
n = 256: counted 19171, formula 3*3^k - 2n = 19171
n = 1024: counted 175099, formula 3*3^k - 2n = 175099
Exercise 10: Four master-theorem problems
Solve: (a) , (b) , (c) , (d) .
Answer
(a) , (b) , (c) , (d) .
Solution
(a) : case 2. (b) : case 2. (c) is polynomially smaller than , and the regularity condition holds because with : case 3. (d) and : the extended case 2 with gives . Note that (d) is not case 3, because is not polynomially larger than .
Exercise 11: Substitution with a lower-order term
For a power of 2, and . Show that the guess fails in the inductive step, and fix it.
Answer
Use with ; , works, and in fact exactly.
Solution
With the step gives , which is not for any : the induction does not close, even though the bound is true. Subtract a lower-order term: assuming ,
whenever . The base case needs , so , . See The Substitution Method.
Exercise 12: How often does the maximum change?
Run FIND-MAX on a uniformly random permutation of distinct values. What is the expected number of times the line best = a[i] executes?
Answer
, which is about .
Solution
Let be the indicator that is larger than everything before it, for . In a random permutation each of the first values is equally likely to be the largest of them, so . By linearity, the expected count is . This is the hiring problem in disguise. The program checks it over every permutation.
from itertools import permutations
from fractions import Fraction
def updates(a):
best, count = a[0], 0
for x in a[1:]:
if x > best:
best, count = x, count + 1
return count
for n in range(1, 8):
perms = list(permutations(range(n)))
avg = Fraction(sum(updates(p) for p in perms), len(perms))
h = sum(Fraction(1, k) for k in range(1, n + 1))
print(f"n = {n}: average {str(avg):>7} H_n - 1 = {str(h - 1):>7}")n = 1: average 0 H_n - 1 = 0
n = 2: average 1/2 H_n - 1 = 1/2
n = 3: average 5/6 H_n - 1 = 5/6
n = 4: average 13/12 H_n - 1 = 13/12
n = 5: average 77/60 H_n - 1 = 77/60
n = 6: average 29/20 H_n - 1 = 29/20
n = 7: average 223/140 H_n - 1 = 223/140
Exercise 13: A shuffle that looks fine
A programmer shuffles by swapping with for a uniformly random in , for each . Is every permutation equally likely? Decide without simulation.
Answer
No. The procedure makes equally likely sequences of choices, and for the number is not divisible by , so the permutations cannot each receive the same share.
Solution
For there are choice sequences but permutations, and is not an integer. Some permutation must get more sequences than another. Restricting to gives sequences, one per permutation, which is the correct Fisher-Yates shuffle from Random Permutations. The program counts the outcomes of all 27 sequences exactly.
from itertools import product
from collections import Counter
n = 3
outcomes = Counter()
for choices in product(range(n), repeat=n):
a = list("ABC")
for i, j in enumerate(choices):
a[i], a[j] = a[j], a[i]
outcomes["".join(a)] += 1
for perm, count in sorted(outcomes.items()):
print(perm, f"{count}/27")ABC 4/27
ACB 5/27
BAC 5/27
BCA 5/27
CAB 4/27
CBA 4/27
In C++, each of the 27 choice sequences is read off the base-3 digits of a number from 0 to 26:
#include <cstdio>
#include <map>
#include <string>
#include <utility>
int main() {
const int n = 3;
std::map<std::string, int> outcomes;
// every choice sequence (j_0, j_1, j_2) with each j in 0..2: 27 of them
for (int code = 0; code < 27; code++) {
std::string a = "ABC";
int c = code;
for (int i = 0; i < n; i++) {
int j = c % n; // the i-th digit of code in base 3
c /= n;
std::swap(a[i], a[j]);
}
outcomes[a]++;
}
for (const auto& [perm, count] : outcomes)
std::printf("%s %d/27\n", perm.c_str(), count);
}ABC 4/27
ACB 5/27
BAC 5/27
BCA 5/27
CAB 4/27
CBA 4/27
Exercise 14: Colliding hash values
A hash function produces uniformly random 32-bit values. About how many values must you generate before the probability that two are equal reaches ?
Answer
About ; the exact threshold is values.
Solution
With possible values and draws, the probability of no collision is . Setting this to gives , about 77,163. Only around values, not , are needed. See The Birthday Paradox.
Exercise 15: Rolling every face
What is the expected number of rolls of a fair six-sided die until every face has appeared at least once?
Answer
.
Solution
Split the rolls into phases: phase starts when faces have been seen and ends at the next new face. A roll gives a new face with probability , so phase lasts rolls on average (a geometric distribution). Summing for gives . A seeded simulation agrees.
import random
from fractions import Fraction
exact = 6 * sum(Fraction(1, k) for k in range(1, 7))
rng = random.Random(7)
trials, total = 100_000, 0
for _ in range(trials):
seen, rolls = set(), 0
while len(seen) < 6:
seen.add(rng.randint(1, 6))
rolls += 1
total += rolls
print(f"exact: {exact} = {float(exact)}")
print(f"simulated over {trials:,} trials: {total / trials:.3f}")exact: 147/10 = 14.7
simulated over 100,000 trials: 14.701
The same argument gives for faces; see Balls into Bins.
Test yourself
Which constants prove ?
- , ,
- , ,
- , ,
- No constants exist
Why is not covered by case 3 of the master theorem?
- Because
- Because is larger than but not by a polynomial factor
- Because the regularity condition always fails
- Because must be a polynomial
In the naive shuffle with uniform in , why can the result not be uniform for ?
- Because it makes too few swaps
- Because equally likely choice sequences cannot be split evenly among permutations
- Because the random generator is seeded
- Because a swap of an element with itself is not allowed
What is the expected number of rolls of a fair die until all six faces have appeared?
- 6
- 36