Exercises
Fourteen problems covering the whole course: parallelism, online algorithms, matrices and linear programs, the FFT, number-theoretic algorithms, string matching and NP-completeness. Try each one on paper first. Every problem has a short Answer to check yourself against and a full Solution; several solutions include a program that confirms the result, which you can edit and run.
Tip: For a reduction, write down both directions of the "if and only if" before believing it, and test it on small instances by brute force, as the lessons did. For an amortized bound, name the potential first.
| # | Exercise | Practises |
|---|---|---|
| 1 | The parallel maximum | work, span, Brent's bound |
| 2 | A racy maximum | determinacy races |
| 3 | Buying skis on day 3 | competitive ratio |
| 4 | Move-to-front by hand | list update |
| 5 | An LU decomposition by hand | LU decomposition |
| 6 | A two-variable LP | LP formulation, vertices |
| 7 | Squaring with a 4-point DFT | DFT, inverse DFT |
| 8 | Euclid and an inverse | Lamé, extended Euclid |
| 9 | square and multiply | |
| 10 | Rabin-Karp with | rolling hash, spurious hits |
| 11 | A prefix function | KMP |
| 12 | A suffix array | suffix arrays |
| 13 | Three colours to four | reductions |
| 14 | The approximation's worst case | vertex cover 2-approximation |
Exercise 1: The parallel maximum
A fork-join program computes the maximum of numbers with the same recursion as P-SUM (split strand, two halves in parallel, combine strand; unit strands). For give the work, the span and the parallelism, and the lower bound and Brent's upper bound for a greedy schedule on 8 processors.
Answer
, , parallelism . On 8 processors: .
Solution
The structure is that of P-SUM with "add" replaced by "max", so and (Work, Span and Parallelism). The work law gives , the span law , and Brent's bound (Greedy Scheduling and Brent's Bound).
Exercise 2: A racy maximum
What is wrong with this loop, and how is it fixed?
best = -infinity
parallel for i = 0 to n - 1
if A[i] > best
best = A[i]Answer
Logically parallel iterations read and write best: a determinacy race. Use a reduction tree (each half computes its own maximum, then combine), as in Exercise 1.
Solution
Two iterations may both read the old best, both find their value larger, and write in either order, so a smaller value can overwrite a larger one. For example with best and iterations holding 7 and 5: both pass the test, 7 is written, then 5 overwrites it. The outcome depends on the schedule. The race-free version gives each subtree its own result and combines them after the sync, with work and span (Parallel Loops and Determinacy Races).
Exercise 3: Buying skis on day 3
Buying costs , renting 1 per day. What is the worst ratio of the strategy "buy on day 3", and which season length causes it? How does it compare with the break-even strategy?
Answer
, for a season of 3 days. The break-even strategy (buy on day 5) has worst ratio .
Solution
If the season lasts days the strategy pays ; OPT pays , smallest at , giving . For it pays the same as OPT. See Ski Rental: Rent or Buy?.
B, j = 5, 3
worst = max(((D if D < j else j - 1 + B) / min(D, B), D) for D in range(1, 30))
print(f"buy on day {j}: worst ratio {worst[0]:.3f} at D = {worst[1]}; break-even: {2 - 1 / B}")buy on day 3: worst ratio 2.333 at D = 3; break-even: 1.8
Exercise 4: Move-to-front by hand
The list is a b c d. Serve the requests c c a d b with move-to-front. What is the total cost, and what is the final list?
Answer
Cost ; final list b d a c.
Solution
c at position 3 (list becomes c a b d), c at 1, a at 2 (a c b d), d at 4 (d a c b), b at 4 (b d a c). See List Update and Move-to-Front.
Exercise 5: An LU decomposition by hand
Factor
as and use it to solve .
Answer
, , , .
Solution
The multipliers for column 0 are and ; the Schur complement is , whose multiplier is 3 and whose last pivot is . Forward substitution: , , . Back substitution: , , . See LU Decomposition and Triangular Solves.
Exercise 6: A two-variable LP
Maximize subject to , , . List the vertices of the feasible region and find the optimum.
Answer
Vertices , , , ; the optimum is with value 5.
Solution
The two constraint lines meet where and : , . The objective at the vertices is . See Formulating Linear Programs.
from itertools import combinations
from fractions import Fraction as F
cons = [(1, 1, 4), (1, 3, 6), (-1, 0, 0), (0, -1, 0)]
pts = set()
for (a, b, e), (c, d, f) in combinations(cons, 2):
det = a * d - b * c
if det:
p = (F(e * d - b * f, det), F(a * f - e * c, det))
if all(u * p[0] + v * p[1] <= r for u, v, r in cons):
pts.add(p)
for p in sorted(pts):
print(f"({p[0]}, {p[1]}): {p[0] + 2 * p[1]}")(0, 0): 0
(0, 2): 4
(3, 1): 5
(4, 0): 4
Exercise 7: Squaring with a 4-point DFT
Compute of by hand (with ), square the values pointwise, and apply the inverse DFT to recover the coefficients of .
Answer
; squares ; inverse DFT , that is .
Solution
with : , , , . Squares: , , , . The inverse is : , , , . See The Inverse FFT and Fast Polynomial Multiplication.
Exercise 8: Euclid and an inverse
How many division steps does Euclid's algorithm take on , and why is that the maximum for numbers of this size? Find the inverse of 7 modulo 40 with extended Euclid.
Answer
9 steps: , the smallest pair needing 9 steps. The inverse of 7 mod 40 is 23.
Solution
Every quotient is 1 until the end, so the pairs run down the Fibonacci numbers; by Lamé's theorem any pair needing 9 steps has (Euclid's Algorithm and Its Running Time). For the inverse: , , ; back-substituting, , so . Check: .
Exercise 9:
Compute by left-to-right square and multiply, and count the modular multiplications (starting with after the leading bit).
Answer
12, with 5 multiplications (3 squarings and 2 multiplications by 3).
Solution
. Start with (). Bit 1: square to , multiply to (). Bit 0: square (). Bit 1: square , multiply (). See Modular Exponentiation and Its Bit Cost.
Exercise 10: Rabin-Karp with
Search for the pattern 26 in the digit text 3141592653 with Rabin-Karp, and . Which shifts are hits, and which of them are spurious?
Answer
The pattern hash is . Hits at shifts 3, 4, 5 and 6; shifts 3 (15), 4 (59) and 5 (92) are spurious, shift 6 is the match.
Solution
The window values are , with residues mod 11. See Rabin-Karp and Rolling Hashes.
Exercise 11: A prefix function
Compute the prefix function of abcabcab and the shortest period of the string.
Answer
; the shortest period is (abc).
Solution
From position 3 on, every character extends the match with the start of the string by one. The last value 5 says abcab is both a prefix and a suffix, so shifting by 3 maps the string onto itself. See The Knuth-Morris-Pratt Algorithm.
Exercise 12: A suffix array
Write down the suffix array and the LCP array of cabcab.
Answer
and .
Solution
Sorted suffixes: ab (4), abcab (1), b (5), bcab (2), cab (3), cabcab (0). Neighbours share ab (2), nothing, b (1), nothing, cab (3). See Suffix Arrays: An Introduction.
T = "cabcab"
sa = sorted(range(len(T)), key=lambda i: T[i:])
def lcp(a, b):
k = 0
while k < min(len(a), len(b)) and a[k] == b[k]:
k += 1
return k
print("SA =", sa, " LCP =", [0] + [lcp(T[sa[r - 1]:], T[sa[r]:]) for r in range(1, len(sa))])SA = [4, 1, 5, 2, 3, 0] LCP = [0, 2, 0, 1, 0, 3]
Exercise 13: Three colours to four
3-COLOR (can the vertices be coloured with 3 colours so that adjacent vertices differ?) is NP-complete. Show that 4-COLOR is NP-complete.
Answer
4-COLOR is in NP (the colouring is a certificate), and by adding one new vertex adjacent to every vertex.
Solution
Let be plus a vertex joined to all vertices of . If is 3-colourable, give the fourth colour. If is 4-colourable, 's colour appears on no other vertex (all are adjacent to ), so uses only the other three. The construction takes linear time. Note the direction: the known hard problem 3-COLOR is reduced to the new problem (Polynomial-Time Reductions).
Exercise 14: The approximation's worst case
Run APPROX-VERTEX-COVER, always picking the first remaining edge, on the path with edges listed in order. Compare with an optimal cover.
Answer
It picks , , and returns all 6 vertices; an optimal cover such as has 3. The ratio is exactly 2.
Solution
After picking the edge is removed, and so on. The three picked edges form a matching, so every cover needs at least 3 vertices: the bound in the proof is tight here. See Coping with NP-Hardness.
Test yourself
A computation has and . Which number of processors is the largest for which perfect linear speedup is not ruled out?
- 8
- 14
- 64
- 190
What is ?
- 3
- 10
- 12
- 15
To show that 4-COLOR is NP-hard from 3-COLOR, which reduction is needed?
- 4-COLOR 3-COLOR
- 3-COLOR 4-COLOR
- Either
- None: 4-COLOR is in P