TExcelTAD

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 1+x1 + x with a 4-point DFT DFT, inverse DFT
8 Euclid and an inverse Lamé, extended Euclid
9 313 mod 173^{13} \bmod 17 square and multiply
10 Rabin-Karp with q=11q = 11 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 nn numbers with the same recursion as P-SUM (split strand, two halves in parallel, combine strand; unit strands). For n=64n = 64 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

T1=190T_1 = 190, T∞=13T_\infty = 13, parallelism 190/13≈14.6190/13 \approx 14.6. On 8 processors: max⁡(190/8,13)=23.75≤T8≤190/8+13=36.75\max(190/8, 13) = 23.75 \le T_8 \le 190/8 + 13 = 36.75.

Solution

The structure is that of P-SUM with "add" replaced by "max", so W(n)=3n−2=190W(n) = 3n - 2 = 190 and S(n)=2⌈lg⁡n⌉+1=13S(n) = 2\lceil \lg n \rceil + 1 = 13 (Work, Span and Parallelism). The work law gives T8≥190/8=23.75T_8 \ge 190/8 = 23.75, the span law T8≥13T_8 \ge 13, and Brent's bound T8≤23.75+13T_8 \le 23.75 + 13 (Greedy Scheduling and Brent's Bound).

Exercise 2: A racy maximum

What is wrong with this loop, and how is it fixed?

text
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 =0= 0 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 Θ(n)\Theta(n) and span Θ(lg⁡n)\Theta(\lg n) (Parallel Loops and Determinacy Races).

Exercise 3: Buying skis on day 3

Buying costs B=5B = 5, 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

7/3≈2.337/3 \approx 2.33, for a season of 3 days. The break-even strategy (buy on day 5) has worst ratio 2−1/5=1.82 - 1/5 = 1.8.

Solution

If the season lasts D≥3D \ge 3 days the strategy pays 2+5=72 + 5 = 7; OPT pays min⁡(D,5)\min(D, 5), smallest at D=3D = 3, giving 7/37/3. For D<3D < 3 it pays the same as OPT. See Ski Rental: Rent or Buy?.

python · try it yourself
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 3+1+2+4+4=143 + 1 + 2 + 4 + 4 = 14; 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

A=(211433879)A = \begin{pmatrix} 2 & 1 & 1 \\ 4 & 3 & 3 \\ 8 & 7 & 9 \end{pmatrix}

as A=LUA = LU and use it to solve Ax=(4,10,24)TAx = (4, 10, 24)^T.

Answer

L=(100210431)L = \begin{pmatrix} 1 & 0 & 0 \\ 2 & 1 & 0 \\ 4 & 3 & 1 \end{pmatrix}, U=(211011002)U = \begin{pmatrix} 2 & 1 & 1 \\ 0 & 1 & 1 \\ 0 & 0 & 2 \end{pmatrix}, y=(4,2,2)y = (4, 2, 2), x=(1,1,1)x = (1, 1, 1).

Solution

The multipliers for column 0 are 4/2=24/2 = 2 and 8/2=48/2 = 4; the Schur complement is (3−23−27−49−4)=(1135)\begin{pmatrix} 3 - 2 & 3 - 2 \\ 7 - 4 & 9 - 4 \end{pmatrix} = \begin{pmatrix} 1 & 1 \\ 3 & 5 \end{pmatrix}, whose multiplier is 3 and whose last pivot is 5−3=25 - 3 = 2. Forward substitution: y0=4y_0 = 4, y1=10−8=2y_1 = 10 - 8 = 2, y2=24−16−6=2y_2 = 24 - 16 - 6 = 2. Back substitution: x2=1x_2 = 1, x1=2−1=1x_1 = 2 - 1 = 1, x0=(4−1−1)/2=1x_0 = (4 - 1 - 1)/2 = 1. See LU Decomposition and Triangular Solves.

Exercise 6: A two-variable LP

Maximize x+2yx + 2y subject to x+y≤4x + y \le 4, x+3y≤6x + 3y \le 6, x,y≥0x, y \ge 0. List the vertices of the feasible region and find the optimum.

Answer

Vertices (0,0)(0, 0), (4,0)(4, 0), (3,1)(3, 1), (0,2)(0, 2); the optimum is (3,1)(3, 1) with value 5.

Solution

The two constraint lines meet where x+y=4x + y = 4 and x+3y=6x + 3y = 6: y=1y = 1, x=3x = 3. The objective at the vertices is 0,4,5,40, 4, 5, 4. See Formulating Linear Programs.

python · try it yourself
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 1+x1 + x with a 4-point DFT

Compute DFT4\mathrm{DFT}_4 of (1,1,0,0)(1, 1, 0, 0) by hand (with ω4=i\omega_4 = i), square the values pointwise, and apply the inverse DFT to recover the coefficients of (1+x)2(1 + x)^2.

Answer

y=(2,1+i,0,1−i)y = (2, 1 + i, 0, 1 - i); squares (4,2i,0,−2i)(4, 2i, 0, -2i); inverse DFT (1,2,1,0)(1, 2, 1, 0), that is 1+2x+x21 + 2x + x^2.

Solution

yk=A(ik)y_k = A(i^k) with A(x)=1+xA(x) = 1 + x: A(1)=2A(1) = 2, A(i)=1+iA(i) = 1 + i, A(−1)=0A(-1) = 0, A(−i)=1−iA(-i) = 1 - i. Squares: 44, (1+i)2=2i(1 + i)^2 = 2i, 00, (1−i)2=−2i(1 - i)^2 = -2i. The inverse is aj=14∑kyki−kja_j = \frac{1}{4}\sum_k y_k i^{-kj}: a0=(4+2i−2i)/4=1a_0 = (4 + 2i - 2i)/4 = 1, a1=(4+2i⋅(−i)+(−2i)⋅i)/4=(4+2+2)/4=2a_1 = (4 + 2i \cdot (-i) + (-2i) \cdot i)/4 = (4 + 2 + 2)/4 = 2, a2=(4+2i⋅(−1)+(−2i)(−1))/4=1a_2 = (4 + 2i \cdot (-1) + (-2i)(-1))/4 = 1, a3=(4+2i⋅i+(−2i)(−i))/4=(4−2−2)/4=0a_3 = (4 + 2i \cdot i + (-2i)(-i))/4 = (4 - 2 - 2)/4 = 0. See The Inverse FFT and Fast Polynomial Multiplication.

Exercise 8: Euclid and an inverse

How many division steps does Euclid's algorithm take on (89,55)(89, 55), and why is that the maximum for numbers of this size? Find the inverse of 7 modulo 40 with extended Euclid.

Answer

9 steps: (89,55)=(F11,F10)(89, 55) = (F_{11}, F_{10}), 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 a≥F11=89a \ge F_{11} = 89 (Euclid's Algorithm and Its Running Time). For the inverse: 40=5⋅7+540 = 5 \cdot 7 + 5, 7=1⋅5+27 = 1 \cdot 5 + 2, 5=2⋅2+15 = 2 \cdot 2 + 1; back-substituting, 1=5−2⋅2=5−2(7−5)=3⋅5−2⋅7=3(40−5⋅7)−2⋅7=3⋅40−17⋅71 = 5 - 2 \cdot 2 = 5 - 2(7 - 5) = 3 \cdot 5 - 2 \cdot 7 = 3(40 - 5 \cdot 7) - 2 \cdot 7 = 3 \cdot 40 - 17 \cdot 7, so 7−1≡−17≡23(mod40)7^{-1} \equiv -17 \equiv 23 \pmod{40}. Check: 7⋅23=161=4⋅40+17 \cdot 23 = 161 = 4 \cdot 40 + 1.

Exercise 9: 313 mod 173^{13} \bmod 17

Compute 313 mod 173^{13} \bmod 17 by left-to-right square and multiply, and count the modular multiplications (starting with d=3d = 3 after the leading bit).

Answer

12, with 5 multiplications (3 squarings and 2 multiplications by 3).

Solution

13=1101213 = 1101_2. Start with d=3d = 3 (c=1c = 1). Bit 1: square to 99, multiply to 27≡1027 \equiv 10 (c=3c = 3). Bit 0: square 100≡15100 \equiv 15 (c=6c = 6). Bit 1: square 225≡4225 \equiv 4, multiply 1212 (c=13c = 13). See Modular Exponentiation and Its Bit Cost.

Exercise 10: Rabin-Karp with q=11q = 11

Search for the pattern 26 in the digit text 3141592653 with Rabin-Karp, d=10d = 10 and q=11q = 11. Which shifts are hits, and which of them are spurious?

Answer

The pattern hash is 26 mod 11=426 \bmod 11 = 4. 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 31,14,41,15,59,92,26,65,5331, 14, 41, 15, 59, 92, 26, 65, 53, with residues 9,3,8,4,4,4,4,10,99, 3, 8, 4, 4, 4, 4, 10, 9 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

π=(0,0,0,1,2,3,4,5)\pi = (0, 0, 0, 1, 2, 3, 4, 5); the shortest period is 8−5=38 - 5 = 3 (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

SA=(4,1,5,2,3,0)SA = (4, 1, 5, 2, 3, 0) and LCP=(0,2,0,1,0,3)LCP = (0, 2, 0, 1, 0, 3).

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.

python · try it yourself
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 3-COLOR≤P4-COLOR\text{3-COLOR} \le_P \text{4-COLOR} by adding one new vertex adjacent to every vertex.

Solution

Let G′G' be GG plus a vertex zz joined to all vertices of GG. If GG is 3-colourable, give zz the fourth colour. If G′G' is 4-colourable, zz's colour appears on no other vertex (all are adjacent to zz), so GG 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 0−1−2−3−4−50 - 1 - 2 - 3 - 4 - 5 with edges listed in order. Compare with an optimal cover.

Answer

It picks (0,1)(0, 1), (2,3)(2, 3), (4,5)(4, 5) and returns all 6 vertices; an optimal cover such as {1,3,4}\{1, 3, 4\} has 3. The ratio is exactly 2.

Solution

After picking (0,1)(0, 1) the edge (1,2)(1, 2) 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 T1=190T_1 = 190 and T∞=13T_\infty = 13. Which number of processors is the largest for which perfect linear speedup is not ruled out?

  1. 8
  2. 14
  3. 64
  4. 190

What is 313 mod 173^{13} \bmod 17?

  1. 3
  2. 10
  3. 12
  4. 15

To show that 4-COLOR is NP-hard from 3-COLOR, which reduction is needed?

  1. 4-COLOR ≤P\le_P 3-COLOR
  2. 3-COLOR ≤P\le_P 4-COLOR
  3. Either
  4. None: 4-COLOR is in P