Salta al contenuto
Note per Studenti Algorithms in Engineering - Mock Exam 2 Report

Algorithms in Engineering - Mock Exam 2

Questa pagina non ha ancora la versione ripasso: qui sotto c'è il testo completo.

In questa pagina 13

Mock exam built on the model of the written exams of the equivalent Italian course (Algoritmi per l'Ingegneria, UniPD), not an official paper. The official format is a written test in two parts: Part 1 is a closed-answer questionnaire on the basics of the course, Part 2 consists of problems (design and analysis of an algorithm, proof of a property). The Part 1 sheets of the real exams are not public, so the number of questions, the points and the duration below are a proposal: Part 1 has 10 quizzes of 1 point each (10 points, four options, exactly one correct), Part 2 has two exercises of 11 points each (22 points), for a total of 32 points in 2 hours and 30 minutes. No material is allowed.

The problems are new: they are not translations of the real exams and do not repeat the exercises of the notes. Every algorithm of the solutions was run against a brute-force implementation on thousands of random inputs and every operation count was checked by an instrumented implementation. Pseudocode uses the conventions of the notes (<- for assignment, { ... } for comments).

Topics. Quizzes: recurrences and the general formula, Master Theorem, call trees, hybrid algorithms, Strassen, greedy algorithms (activity selection, shortest-first scheduling), Huffman codes. Exercise 1: dynamic programming (optimal substructure, table, memoization, reconstruction, exact cost). Exercise 2: polynomial product and exponentiation with the FFT, properties of the DFT.

PART 1 (10 quizzes, 1 point each, only the answer is required)

Quiz 1

Let T(1)=1T(1) = 1 and T(n)=2 T(n/2)+n2T(n) = 2\,T(n/2) + n^2 for n=2k>1n = 2^k > 1. What is T(16)T(16)?

  • (A) 480
  • (B) 496
  • (C) 512
  • (D) 528
Show the result

(B) T(16)=496T(16) = 496.

Show the full solution

Use the general formula of Recurrence Relations - Recursion Tree and General FormulaThe recurrence tree has the shape of the call tree of the worst instance and T(n) is the sum of the works of its nodes. For the family T(n) = s(n) T(f(n)) + w(n) with base T0 for n <= n0, counting nodes per level with the iterates of f and the level f*(n,n0) gives the closed formula T(n) = sum over levels of [product of s] w + [product of s] T0, proved by induction and applied to merge sort, Hanoi and square-root recurrences.Recurrence Relations - Recursion Tree and General Formula →. The tree has log⁡216=4\log_2 16 = 4 internal levels; at level ℓ\ell there are 2ℓ2^\ell nodes, each of work (16/2ℓ)2(16/2^\ell)^2, so the level costs 2ℓ⋅256/4ℓ=256/2ℓ2^\ell \cdot 256/4^\ell = 256/2^\ell:

256+128+64+32=480.256 + 128 + 64 + 32 = 480.

The 1616 leaves cost T(1)=1T(1) = 1 each: 1616. Total 480+16=496480 + 16 = 496. Check by iterating: T(2)=2+4=6T(2) = 2 + 4 = 6, T(4)=12+16=28T(4) = 12 + 16 = 28, T(8)=56+64=120T(8) = 56 + 64 = 120, T(16)=240+256=496T(16) = 240 + 256 = 496. In closed form T(n)=2n2−nT(n) = 2n^2 - n.

Typical mistakes: forgetting the leaves (480, which is the answer if T(1)=0T(1) = 0); summing the work as n2n^2 at every level (512); a wrong sign in 2n2±n2n^2 \pm n (528).

Quiz 2

Which of the following recurrences, with T(1)=1T(1) = 1 and nn a power of the base of the argument, cannot be classified by the Master Theorem as stated in the course?

  • (A) T(n)=9 T(n/3)+n2T(n) = 9\,T(n/3) + n^2
  • (B) T(n)=8 T(n/2)+n2T(n) = 8\,T(n/2) + n^2
  • (C) T(n)=T(n/2)+nT(n) = T(n/2) + n
  • (D) T(n)=2 T(n/2)+nlog⁡2nT(n) = 2\,T(n/2) + n \log_2 n
Show the result

(D).

Show the full solution

Compare w(n)w(n) with the threshold nlog⁡ban^{\log_b a} (Master TheoremThe Master Theorem for T(n) = aT(n/b) + w(n) compares w(n) with the threshold n^(log_b a). Case 1 (w polynomially smaller): Theta(n^(log_b a)); case 2 (same order): Theta(n^(log_b a) log n); case 3 (polynomially larger and regular): Theta(w(n)). Full proof from the levels of the tree, extended version with floors and ceilings, a table of applications, and the misuse when no case applies (w = n log n).Master Theorem →).

  • (A) a=9a = 9, b=3b = 3, threshold n2n^2, w=n2=Θ(n2)w = n^2 = \Theta(n^2): Case 2, Θ(n2log⁡n)\Theta(n^2 \log n).
  • (B) a=8a = 8, b=2b = 2, threshold n3n^3, w=n2=O(n3−ε)w = n^2 = O(n^{3 - \varepsilon}): Case 1, Θ(n3)\Theta(n^3).
  • (C) a=1a = 1, b=2b = 2, threshold n0=1n^0 = 1, w=n=Ω(n0+ε)w = n = \Omega(n^{0 + \varepsilon}) and 1⋅(n/2)=12n1 \cdot (n/2) = \frac12 n (regularity with c=12c = \frac12): Case 3, Θ(n)\Theta(n).
  • (D) a=2a = 2, b=2b = 2, threshold nn, w=nlog⁡2nw = n \log_2 n is larger than nn but only by a logarithmic factor: nlog⁡n≠Ω(n1+ε)n \log n \ne \Omega(n^{1 + \varepsilon}) for every ε>0\varepsilon > 0, so Case 3 fails, and it is not Θ(n)\Theta(n) either. The theorem does not apply (the true order is Θ(nlog⁡2n)\Theta(n \log^2 n), found with the general formula).

Typical mistake: applying Case 3 to (D) and answering Θ(nlog⁡n)\Theta(n \log n), which is wrong.

Quiz 3

An algorithm MAX3 finds the maximum of an array of n=3kn = 3^k elements by splitting it into three equal parts, solving them recursively and combining the three maxima with 22 comparisons between elements; a single element is returned with no comparison. How many comparisons does MAX3 perform on n=27n = 27 elements?

  • (A) 26
  • (B) 27
  • (C) 39
  • (D) 54
Show the result

(A) 26.

Show the full solution

The recurrence is T(1)=0T(1) = 0, T(n)=3 T(n/3)+2T(n) = 3\,T(n/3) + 2: T(3)=2T(3) = 2, T(9)=3⋅2+2=8T(9) = 3 \cdot 2 + 2 = 8, T(27)=3⋅8+2=26T(27) = 3 \cdot 8 + 2 = 26. The call tree (Divide and Conquer - Paradigm and Call TreeA divide-and-conquer algorithm comes from a substructure property (threshold n0, Divide and Conquer functions) with strictly smaller subinstances; the call tree describes the execution, and D&C has no memory (equal subinstances are recomputed). Complete example: MAX of an array, with correctness by induction, the recurrence, and the exact count n-1 via the theorem on full binary trees.Divide and Conquer - Paradigm and Call Tree →) is a full ternary tree with 2727 leaves; if II is the number of internal nodes, counting edges gives 3I=I+27−13I = I + 27 - 1, so I=13I = 13 and the comparisons are 2⋅13=26=n−12 \cdot 13 = 26 = n - 1, the same as for the binary split: any way of splitting needs n−1n - 1 comparisons.

Typical mistakes: 39=3⋅1339 = 3 \cdot 13 (three comparisons per internal node); 54=2⋅2754 = 2 \cdot 27 (one conquer per leaf); 2727 (counting leaves).

Quiz 4

The hybrid algorithm H_MUL runs Strassen's recursion on n×nn \times n matrices down to size n0n_0 and uses the iterative product (cost 2n3−n22n^3 - n^2) on the blocks of size n0n_0. Counting scalar operations, what is its cost for n=16n = 16 and n0=4n_0 = 4?

  • (A) 7872
  • (B) 15271
  • (C) 8656
  • (D) 10192
Show the result

(C) 8656.

Show the full solution

Hybrid AlgorithmsHybridization combines two algorithms for the same problem so the result has the asymptotics of the better one and, if possible, lower constants. Choosing the algorithm only by the starting size (STUPID_HYBRID) does not help; changing the base case of the recursion (H_MUL: iterative product for n <= n0 at every leaf of Strassen's tree) gives cost n^(log2 7)(2n0+5)/n0^(log2 7 - 2) - 6n^2, minimal for n0 = 8 with leading constant about 3.92.Hybrid Algorithms →: T(n,n0)=2n3−n2T(n, n_0) = 2n^3 - n^2 for n≤n0n \le n_0 and 7 T(n/2,n0)+92n27\,T(n/2, n_0) + \frac92 n^2 otherwise. Then

T(4)=2⋅64−16=112,T(8)=7⋅112+92⋅64=1072,T(16)=7⋅1072+92⋅256=8656.T(4) = 2 \cdot 64 - 16 = 112, \quad T(8) = 7 \cdot 112 + \tfrac92 \cdot 64 = 1072, \quad T(16) = 7 \cdot 1072 + \tfrac92 \cdot 256 = 8656.

With the closed form: m=log⁡2(16/4)=2m = \log_2(16/4) = 2, T=7m(2n03+5n02)−6n2=49⋅208−1536=8656T = 7^m(2n_0^3 + 5n_0^2) - 6n^2 = 49 \cdot 208 - 1536 = 8656.

The other options are other thresholds or algorithms: (A) 78727872 is n0=8n_0 = 8; (B) 1527115271 is pure Strassen (n0=1n_0 = 1); (D) 10192=49⋅20810192 = 49 \cdot 208 forgets the term −6n2-6n^2.

Quiz 5

Which statement about Strassen's algorithm (Strassen's AlgorithmStrassen computes the n x n product with 7 recursive calls instead of 8, using 10 matrix additions in Divide and 8 in Conquer: T(n) = 7T(n/2) + (9/2)n^2, Theta(n^(log2 7)) with exact solution 7n^(log2 7) - 6n^2. Its leading constant 7 is more than three times that of the iterative algorithm (2), so Strassen beats it only from n = 655 (from 1024 for powers of two).Strassen's Algorithm →) is true?

  • (A) It uses fewer scalar operations than the iterative product for every n≥2n \ge 2.
  • (B) Its recurrence T(n)=7 T(n/2)+92n2T(n) = 7\,T(n/2) + \frac92 n^2 falls in Case 1 of the Master Theorem, so the leaves dominate and T(n)=Θ(nlog⁡27)T(n) = \Theta(n^{\log_2 7}).
  • (C) The seven products are correct only if the entries of the matrices commute.
  • (D) The Divide phase performs 1818 additions and the Conquer phase none.
Show the result

(B).

Show the full solution

(B) is true: a=7a = 7, b=2b = 2, threshold nlog⁡27≈n2.81n^{\log_2 7} \approx n^{2.81} and w=92n2=O(nlog⁡27−ε)w = \frac92 n^2 = O(n^{\log_2 7 - \varepsilon}), so Case 1 (Master TheoremThe Master Theorem for T(n) = aT(n/b) + w(n) compares w(n) with the threshold n^(log_b a). Case 1 (w polynomially smaller): Theta(n^(log_b a)); case 2 (same order): Theta(n^(log_b a) log n); case 3 (polynomially larger and regular): Theta(w(n)). Full proof from the levels of the tree, extended version with floors and ceilings, a table of applications, and the misuse when no case applies (w = n log n).Master Theorem →); the 7k7^k leaves carry the cost.

(A) is false: T(n)=7nlog⁡27−6n2T(n) = 7n^{\log_2 7} - 6n^2 against 2n3−n22n^3 - n^2: for n=2n = 2 it is 2525 against 1212, for n=8n = 8 it is 20172017 against 960960; Strassen wins only from n=1024n = 1024 among powers of two. (C) is false: the identities were verified keeping the order of the factors, they hold for non-commutative products, as needed for blocks. (D) is false: 1010 additions/subtractions in Divide and 88 in Conquer (total 1818).

Quiz 6

How many scalar multiplications does Strassen's algorithm (recursion down to 1×11 \times 1 matrices) perform for n=16n = 16?

  • (A) 343
  • (B) 2744
  • (C) 4096
  • (D) 2401
Show the result

(D) 24012401.

Show the full solution

Quiz 7

Activities a1,…,a8a_1, \dots, a_8 occupy the half-open intervals [0,3)[0,3), [2,4)[2,4), [1,5)[1,5), [4,7)[4,7), [5,8)[5,8), [6,10)[6,10), [8,11)[8,11), [9,12)[9,12) (already sorted by finish time). Which set does the earliest-finish greedy algorithm IT_GREEDY_SEL return?

  • (A) {a1,a4,a7}\{a_1, a_4, a_7\}
  • (B) {a1,a4,a8}\{a_1, a_4, a_8\}
  • (C) {a2,a5,a8}\{a_2, a_5, a_8\}
  • (D) {a1,a5,a8}\{a_1, a_5, a_8\}
Show the result

(A) {a1,a4,a7}\{a_1, a_4, a_7\} (three activities, the maximum).

Show the full solution

The algorithm picks a1a_1 and then scans, keeping the last chosen activity gg and choosing aia_i when si≥fgs_i \ge f_g (Greedy Paradigm and Activity Selectionthe greedy paradigm makes the locally best choice immediately, cleans up the instance and solves the single residual subinstance (tail recursion, hence a loop); the code is easy and correctness is not, requiring the greedy choice property and optimal substructure; case study activity selection with the earliest-finish rule, full proof, Theta(n) after sorting, and counterexamples for wrong greedy rules.Greedy Paradigm and Activity Selection →):

ii interval test si≥fgs_i \ge f_g outcome gg
1 [0,3)[0,3) initial choice chosen 1 (f=3f = 3)
2 [2,4)[2,4) 2≥32 \ge 3 no discarded 1
3 [1,5)[1,5) 1≥31 \ge 3 no discarded 1
4 [4,7)[4,7) 4≥34 \ge 3 yes chosen 4 (f=7f = 7)
5 [5,8)[5,8) 5≥75 \ge 7 no discarded 4
6 [6,10)[6,10) 6≥76 \ge 7 no discarded 4
7 [8,11)[8,11) 8≥78 \ge 7 yes chosen 7 (f=11f = 11)
8 [9,12)[9,12) 9≥119 \ge 11 no discarded 7

The scan performs n−1=7n - 1 = 7 comparisons. Options (B), (C), (D) are also mutually compatible sets of three activities (so also optimal) but they are not the output of the algorithm, which is deterministic: the question asks for the set it returns.

Quiz 8

Five jobs with execution times t=(7,2,5,3,1)t = (7, 2, 5, 3, 1) run on one machine. The waiting time of a job is the sum of the times of the jobs executed before it. What is the minimum possible cumulative waiting time TsumT_{sum}?

  • (A) 47
  • (B) 39
  • (C) 21
  • (D) 51
Show the result

(C) 2121.

Show the full solution

By the shortest-job-first property (Greedy Exercises - CD Tracks, Shortest-First Scheduling and Boxinghow to set up and prove a greedy exercise (greedy choice, clean-up, algorithm, greedy choice property by exchange, optimal substructure by contradiction, induction) applied to three problems with empty clean-up: CD tracks (fill the first CD, Theta(n)), shortest-first scheduling (sort by duration, SJF holds for every optimum, O(n log n)) and (2,1)-boxing (pair the heaviest with the lightest, Theta(n)).Greedy Exercises - CD Tracks, Shortest-First Scheduling and Boxing →) an optimal schedule runs the jobs in non-decreasing order of time: 1,2,3,5,71, 2, 3, 5, 7. The waiting times are 0,1,3,6,110, 1, 3, 6, 11, with sum 2121 (formula ∑j=1n−1(n−j) tπ(j)=4⋅1+3⋅2+2⋅3+1⋅5=21\sum_{j=1}^{n-1}(n-j)\,t_{\pi(j)} = 4 \cdot 1 + 3 \cdot 2 + 2 \cdot 3 + 1 \cdot 5 = 21).

The other options: (A) 4747 is the order in which the jobs are given (0+7+9+14+170 + 7 + 9 + 14 + 17); (B) 3939 is the sum of the completion times of the sorted order (1+3+6+11+181 + 3 + 6 + 11 + 18), a different quantity; (D) 5151 is the worst order, longest job first. The result was also confirmed by trying all 5!=1205! = 120 orders.

Quiz 9

A file uses seven characters with frequencies (in hundredths) 5,7,10,13,15,20,305, 7, 10, 13, 15, 20, 30. What is the average codeword length, in bits per character, of a Huffman code?

  • (A) 2.60
  • (B) 2.62
  • (C) 2.70
  • (D) 3.00
Show the result

(B) 2.622.62 bits per character.

Show the full solution

Run the algorithm of Huffman Codescharacter-by-character compression needs an injective variable-length code, which prefix codes guarantee; a prefix code is a binary trie with one leaf per character of cost B(T) = sum of f(c) d_T(c), the optimal trie is full with n-1 internal nodes, Huffman repeatedly merges the two lowest-frequency trees using a priority queue (2n-1 extractions, O(n log n)), and optimality follows from the greedy choice (two rarest characters are deepest sibling leaves, by exchange) and substructure B(T) = B(T') + f(x) + f(y).Huffman Codes → merging the two smallest weights:

step merged new weight queue after
1 5+75 + 7 12 10,12,13,15,20,3010, 12, 13, 15, 20, 30
2 10+1210 + 12 22 13,15,20,22,3013, 15, 20, 22, 30
3 13+1513 + 15 28 20,22,28,3020, 22, 28, 30
4 20+2220 + 22 42 28,30,4228, 30, 42
5 28+3028 + 30 58 42,5842, 58
6 42+5842 + 58 100 100100

The cost is the sum of the weights of the internal nodes: 12+22+28+42+58+100=26212 + 22 + 28 + 42 + 58 + 100 = 262 hundredths, i.e. 2.622.62. Check with the depths: 3030 and 2020 at depth 22; 15,13,1015, 13, 10 at depth 33; 7,57, 5 at depth 44: 0.30⋅2+0.20⋅2+0.15⋅3+0.13⋅3+0.10⋅3+0.07⋅4+0.05⋅4=2.620.30 \cdot 2 + 0.20 \cdot 2 + 0.15 \cdot 3 + 0.13 \cdot 3 + 0.10 \cdot 3 + 0.07 \cdot 4 + 0.05 \cdot 4 = 2.62. The fixed-length code needs 33 bits (D). The entropy of the source is about 2.59552.5955, a lower bound that a code with integer lengths cannot reach here: option (A) would be below the optimum 2.622.62.

Quiz 10

How many extractions of the minimum from the priority queue does HUFFMAN perform on an alphabet of n=20n = 20 characters (counting the extraction in the final return)?

  • (A) 38
  • (B) 40
  • (C) 78
  • (D) 39
Show the result

(D) 3939.

Show the full solution

The loop has n−1=19n - 1 = 19 iterations with 22 extractions each (3838), plus 11 extraction in the return: 2n−1=392n - 1 = 39 (Huffman Codescharacter-by-character compression needs an injective variable-length code, which prefix codes guarantee; a prefix code is a binary trie with one leaf per character of cost B(T) = sum of f(c) d_T(c), the optimal trie is full with n-1 internal nodes, Huffman repeatedly merges the two lowest-frequency trees using a priority queue (2n-1 extractions, O(n log n)), and optimality follows from the greedy choice (two rarest characters are deepest sibling leaves, by exchange) and substructure B(T) = B(T') + f(x) + f(y).Huffman Codes →). The insertions are also n+(n−1)=39n + (n - 1) = 39. Option (A) forgets the return; (B) counts 2n2n; (C) is 39+3939 + 39, extractions plus insertions.

PART 2 (2 exercises, 11 points each)

Exercise 1 (points 11)

Signal matching. A template X=⟨x1,…,xm⟩X = \langle x_1, \dots, x_m \rangle of integers must be matched against a measured signal Y=⟨y1,…,yn⟩Y = \langle y_1, \dots, y_n \rangle of integers, with 1≤m≤n1 \le m \le n. A matching is a strictly increasing sequence of indices 1≤j1<j2<⋯<jm≤n1 \le j_1 < j_2 < \dots < j_m \le n: every template value is used exactly once, in order, and the measurements that are not chosen are skipped. Its score is ∑k=1mxk yjk.\sum_{k=1}^{m} x_k\, y_{j_k}. The goal is the maximum score over all matchings. Values can be negative, so every template value must really be matched.

Example. For X=⟨2,−1,3⟩X = \langle 2, -1, 3 \rangle and Y=⟨1,4,−2,3,−3,2⟩Y = \langle 1, 4, -2, 3, -3, 2 \rangle the matching (j1,j2,j3)=(2,3,4)(j_1, j_2, j_3) = (2, 3, 4) has score 2⋅4+(−1)(−2)+3⋅3=192 \cdot 4 + (-1)(-2) + 3 \cdot 3 = 19, which is the maximum.

For 0≤i≤m0 \le i \le m and 0≤j≤n0 \le j \le n let D(i,j)D(i, j) be the maximum score of a matching of the prefix Xi=⟨x1,…,xi⟩X_i = \langle x_1, \dots, x_i \rangle into the prefix Yj=⟨y1,…,yj⟩Y_j = \langle y_1, \dots, y_j \rangle, with D(i,j)=−∞D(i, j) = -\infty if no matching exists (that is, if i>ji > j). The answer is D(m,n)D(m, n). Cost model: products, sums and comparisons between integers cost 11; assignments, index computations and the fixed values ±∞\pm\infty cost 00.

  • (a) [3 points] Prove an optimal substructure property for D(i,j)D(i, j) and derive the recurrence, with the base cases.
  • (b) [3 points] Write the bottom-up pseudocode that computes D(m,n)D(m, n) and the matching, filling only the cells that are needed, and apply it to the example (show the table and rebuild the matching).
  • (c) [2 points] Write the memoized version (state the sentinel and why it is correct). For the example, how many internal nodes and how many calls does the call tree of the memoized algorithm have?
  • (d) [3 points] Determine the exact number of products, sums and comparisons of the algorithm of (b) as a function of mm and nn, and compare with the enumeration of all (nm)\binom{n}{m} matchings. Give the values for the example. How many calls does the reconstruction make?
Show the result

(a) D(0,j)=0D(0, j) = 0; D(i,j)=−∞D(i, j) = -\infty for 1≤i1 \le i and j<ij < i; for 1≤i≤j1 \le i \le j: D(i,j)=max⁡{ D(i,j−1), D(i−1,j−1)+xiyj }D(i, j) = \max\{\,D(i, j-1),\ D(i-1, j-1) + x_i y_j\,\} (for j=ij = i only the second term is finite).

(b) D(3,6)=19D(3, 6) = 19, matching (1,2),(2,3),(3,4)(1,2), (2,3), (3,4) (that is x1↔y2x_1 \leftrightarrow y_2, x2↔y3x_2 \leftrightarrow y_3, x3↔y4x_3 \leftrightarrow y_4). Last row of the table: D(3,⋅)=(−∞,−∞,−∞,−8,19,19,19)D(3, \cdot) = (-\infty, -\infty, -\infty, -8, 19, 19, 19). Only the cells with i≤j≤n−m+ii \le j \le n - m + i are computed: m(n−m+1)=12m(n-m+1) = 12 cells.

(c) Sentinel +∞+\infty. For the example: 1212 internal nodes and 2525 calls (1313 of them are table reads or base cases).

(d) Products m(n−m+1)m(n-m+1), sums m(n−m+1)m(n-m+1), comparisons m(n−m)m(n-m); total 3m(n−m)+2m3m(n-m) + 2m. For the example 1212 products, 1212 sums, 99 comparisons (3333 operations); the enumeration has (63)=20\binom{6}{3} = 20 matchings of 33 products and 22 sums each (100100 operations plus the comparisons). Reconstruction: at most nn calls with i≥1i \ge 1 plus the final call with i=0i = 0, since jj decreases at every call; 66 calls in the example (55 working calls and the final one).

Show the full solution

(a) Optimal substructure and recurrence

The subproblems are the pairs of prefixes (Xi,Yj)(X_i, Y_j), (m+1)(n+1)(m+1)(n+1) of them, as in the Longest Common Subsequencethe longest common subsequence of X (m symbols) and Y (n symbols) is found by dynamic programming on pairs of prefixes with l(i,j) = 0 if i = 0 or j = 0, 1 + l(i-1,j-1) if x_i = y_j, max of the two neighbours otherwise; bottom-up costs mn comparisons, reconstruction O(m+n), pure divide and conquer costs C(m+n,m) - 1 internal nodes, and space drops to Theta(min{m,n}) if only the length is needed.Longest Common Subsequence → (Dynamic Programming - Paradigm and Memoizationdynamic programming improves on divide and conquer by storing the solutions of repeated subinstances in a table; Fibonacci shows the gap (F_n - 1 additions recursively, n - 1 with a table), memoization is recursion plus a global table, and optimization problems follow a five-step scheme built on optimal substructure and cut-and-paste.Dynamic Programming - Paradigm and Memoization → explains the scheme).

Base cases.

  • i=0i = 0: the empty template has the empty matching, with score 00, for every jj: D(0,j)=0D(0, j) = 0.
  • i>ji > j (including j=0j = 0 with i≥1i \ge 1): ii strictly increasing indices cannot fit in j<ij < i positions: no matching, D(i,j)=−∞D(i, j) = -\infty.

Substructure. Let 1≤i≤j1 \le i \le j and let M=(j1<⋯<ji≤j)M = (j_1 < \dots < j_i \le j) be an optimal matching of (Xi,Yj)(X_i, Y_j), of score D(i,j)D(i, j). The last index jij_i is either smaller than jj or equal to jj.

  1. ji<jj_i < j (the measurement yjy_j is skipped). Then MM is a matching of (Xi,Yj−1)(X_i, Y_{j-1}) and it is optimal for it. By contradiction (cut-and-paste): if there were a matching M′M' of (Xi,Yj−1)(X_i, Y_{j-1}) with a higher score, M′M' would also be a matching of (Xi,Yj)(X_i, Y_j) (its indices are ≤j−1≤j\le j - 1 \le j) with a score higher than that of MM, which is optimal: impossible. So D(i,j)=D(i,j−1)D(i, j) = D(i, j-1).
  2. ji=jj_i = j (the value xix_i is matched with yjy_j). Removing the last pair, M−=(j1<⋯<ji−1≤j−1)M^- = (j_1 < \dots < j_{i-1} \le j - 1) is a matching of (Xi−1,Yj−1)(X_{i-1}, Y_{j-1}) of score D(i,j)−xiyjD(i, j) - x_i y_j, and it is optimal: if M′M' were better for (Xi−1,Yj−1)(X_{i-1}, Y_{j-1}), then M′M' followed by the pair (i,j)(i, j) would be a matching of (Xi,Yj)(X_i, Y_j) (all the indices of M′M' are ≤j−1<j\le j - 1 < j, so they stay increasing) of score score(M′)+xiyj>D(i,j)\text{score}(M') + x_i y_j > D(i, j): contradiction. So D(i,j)=D(i−1,j−1)+xiyjD(i, j) = D(i-1, j-1) + x_i y_j.

Conversely, each of the two quantities is the score of a feasible matching of (Xi,Yj)(X_i, Y_j) whenever it is finite (case 1 needs j−1≥ij - 1 \ge i; case 2 always works for j≥ij \ge i since D(i−1,j−1)D(i-1, j-1) is finite). Hence D(i,j)D(i, j) is the larger of the two:

D(i,j)={0i=0−∞i≥1, j<iD(i−1,j−1)+xiyji≥1, j=imax⁡{ D(i,j−1), D(i−1,j−1)+xiyj }i≥1, j>i.D(i, j) = \begin{cases} 0 & i = 0 \\ -\infty & i \ge 1,\ j < i \\ D(i-1, j-1) + x_i y_j & i \ge 1,\ j = i \\ \max\{\, D(i, j-1),\ D(i-1, j-1) + x_i y_j \,\} & i \ge 1,\ j > i. \end{cases}

For j=ij = i the formula of the last line would also be correct (because D(i,i−1)=−∞D(i, i-1) = -\infty and max⁡{−∞,z}=z\max\{-\infty, z\} = z), but the third line saves a comparison.

Why not plain divide and conquer. The call (i,j)(i, j) spawns (i,j−1)(i, j-1) and (i−1,j−1)(i-1, j-1), which in turn both reach (i−1,j−2)(i-1, j-2), and so on: the same subinstances appear many times and the recursion tree is exponential, while there are only (m+1)(n+1)(m+1)(n+1) distinct subinstances. This is the situation where a table pays off.

(b) Bottom-up algorithm, table and reconstruction

Which cells are needed. The dependencies (i,j)→(i,j−1)(i, j) \to (i, j-1) and (i−1,j−1)(i-1, j-1) never increase the difference j−ij - i. From (m,n)(m, n) only cells with j−i≤n−mj - i \le n - m are reached; cells with j<ij < i are the base case −∞-\infty. So only the band i≤j≤n−m+ii \le j \le n - m + i is computed, n−m+1n - m + 1 cells per row (m(n−m+1)m(n-m+1) in total) instead of mnmn. Row ii depends on row i−1i - 1 and on itself at smaller jj: filling by increasing ii and, inside a row, increasing jj respects the dependencies. The dependencies of (i,j)(i, j) in the band are in the band: (i,j−1)(i, j-1) has j−1≥ij - 1 \ge i and (i−1,j−1)(i-1, j-1) satisfies i−1≤j−1≤n−m+i−1i - 1 \le j - 1 \le n - m + i - 1.

MATCH(X, Y)                                  { 1 <= m <= n }
  m <- |X|; n <- |Y|
  for j <- 0 to n do D[0, j] <- 0            { base: empty template }
  for i <- 1 to m do
    for j <- i to n - m + i do               { band: i <= j <= n - m + i }
      d <- D[i-1, j-1] + X[i] * Y[j]         { match x_i with y_j }
      if j = i then
        D[i, j] <- d;  B[i, j] <- 'match'
      else if d >= D[i, j-1] then
        D[i, j] <- d;  B[i, j] <- 'match'
      else
        D[i, j] <- D[i, j-1];  B[i, j] <- 'skip'
  return D[m, n]

PRINT_MATCH(B, i, j)                         { first call: PRINT_MATCH(B, m, n) }
  if i = 0 then return
  if B[i, j] = 'match' then
    PRINT_MATCH(B, i-1, j-1)
    print (i, j)                             { x_i is matched with y_j }
  else
    PRINT_MATCH(B, i, j-1)

Only the arrow ('match' or 'skip') is stored, not the whole matching: it is the minimum information needed to rebuild the optimum (step 2′2' of the scheme).

Correctness. By induction on ii (and on jj inside the row): the cells of row 00 are the base case; for a cell of the band the values read, D[i−1,j−1]D[i-1, j-1] and D[i,j−1]D[i, j-1], are already correct by the induction hypothesis and the code evaluates the recurrence of (a). The reconstruction follows the arrows from (m,n)(m, n) back to row 00 and prints the pairs in increasing order of index, because the recursive call comes before the print.

The example. X=⟨2,−1,3⟩X = \langle 2, -1, 3 \rangle, Y=⟨1,4,−2,3,−3,2⟩Y = \langle 1, 4, -2, 3, -3, 2 \rangle, m=3m = 3, n=6n = 6, band width n−m+1=4n - m + 1 = 4. In each cell: value and arrow (↖\nwarrow = match, ←\leftarrow = skip); a dot marks a cell outside the band, never computed.

j=0j=0 1 2 3 4 5 6
i=0i=0 0 0 0 0 0 0 0
i=1i=1 (x=2x=2) −∞-\infty 2 ↖\nwarrow 8 ↖\nwarrow 8 ←\leftarrow 8 ←\leftarrow . .
i=2i=2 (x=−1x=-1) −∞-\infty −∞-\infty -2 ↖\nwarrow 10 ↖\nwarrow 10 ←\leftarrow 11 ↖\nwarrow .
i=3i=3 (x=3x=3) −∞-\infty −∞-\infty −∞-\infty -8 ↖\nwarrow 19 ↖\nwarrow 19 ←\leftarrow 19 ←\leftarrow

Cells by hand:

  • D(1,1)=D(0,0)+2⋅1=2D(1,1) = D(0,0) + 2 \cdot 1 = 2 (j=ij = i: only the match). D(1,2)D(1,2): y2=4y_2 = 4, d=0+2⋅4=8d = 0 + 2 \cdot 4 = 8 against D(1,1)=2D(1,1) = 2: match, 88. D(1,3)D(1,3): y3=−2y_3 = -2, d=0−4=−4<D(1,2)=8d = 0 - 4 = -4 < D(1,2) = 8: skip, 88. D(1,4)D(1,4): d=6<8d = 6 < 8: skip.
  • D(2,2)=D(1,1)+(−1)⋅4=−2D(2,2) = D(1,1) + (-1)\cdot 4 = -2. D(2,3)D(2,3): d=D(1,2)+(−1)(−2)=8+2=10d = D(1,2) + (-1)(-2) = 8 + 2 = 10 against D(2,2)=−2D(2,2) = -2: match. D(2,4)D(2,4): y4=3y_4 = 3, d=D(1,3)−3=5<10d = D(1,3) - 3 = 5 < 10: skip. D(2,5)D(2,5): y5=−3y_5 = -3, d=D(1,4)+3=11>10d = D(1,4) + 3 = 11 > 10: match.
  • D(3,3)=D(2,2)+3⋅(−2)=−8D(3,3) = D(2,2) + 3 \cdot (-2) = -8. D(3,4)D(3,4): d=D(2,3)+3⋅3=19d = D(2,3) + 3 \cdot 3 = 19 against −8-8: match. D(3,5)D(3,5): d=D(2,4)+3⋅(−3)=1<19d = D(2,4) + 3 \cdot (-3) = 1 < 19: skip. D(3,6)D(3,6): y6=2y_6 = 2, d=D(2,5)+6=17<19d = D(2,5) + 6 = 17 < 19: skip.

Result: D(3,6)=19D(3, 6) = 19. Reconstruction (bold cells): (3,6)(3,6) skip →(3,5)\to (3,5) skip →(3,4)\to (3,4) match, pair (3,4)(3,4), →(2,3)\to (2,3) match, pair (2,3)(2,3), →(1,2)\to (1,2) match, pair (1,2)(1,2), →(0,1)\to (0,1) stop. Read in increasing order: (1,2),(2,3),(3,4)(1,2), (2,3), (3,4), that is 2⋅4+(−1)(−2)+3⋅3=192 \cdot 4 + (-1)(-2) + 3 \cdot 3 = 19. The second best matching has score 1717 (it uses y5y_5 and y6y_6 for x2x_2 and x3x_3: 8+3+68 + 3 + 6). In case of ties the >= prefers the match; the score does not change.

(c) Memoization

Keep the recursion of the substructure and add a global table with a sentinel for "not yet computed". The scores are finite integers (possibly negative, arbitrarily large in modulus), so no finite value is safe, and −∞-\infty is already used for the infeasible cells. The sentinel is +∞+\infty: the recurrence can never produce it (Dynamic Programming - Paradigm and Memoizationdynamic programming improves on divide and conquer by storing the solutions of repeated subinstances in a table; Fibonacci shows the gap (F_n - 1 additions recursively, n - 1 with a table), memoization is recursion plus a global table, and optimization problems follow a five-step scheme built on optimal substructure and cut-and-paste.Dynamic Programming - Paradigm and Memoization →: the sentinel is part of correctness).

INIT_MATCH(X, Y)
  m <- |X|; n <- |Y|
  for j <- 0 to n do D[0, j] <- 0
  for i <- 1 to m do
    for j <- 0 to i-1 do D[i, j] <- -inf      { infeasible: j < i }
    for j <- i to n do D[i, j] <- +inf        { +inf = still to compute }
  return REC_MATCH(X, Y, m, n)

REC_MATCH(X, Y, i, j)
  if D[i, j] = +inf then
    a <- REC_MATCH(X, Y, i, j-1)
    b <- REC_MATCH(X, Y, i-1, j-1) + X[i] * Y[j]
    D[i, j] <- max(a, b)
  return D[i, j]

When j=ij = i the first call returns −∞-\infty immediately (cell (i,i−1)(i, i-1)) and the second is finite, so the result is correct: −∞-\infty is only ever compared, never added to a product.

Cost: analyse the tree, not the recurrence. The recurrence cannot be used for the cost: it would count every node of the full tree, while here many nodes are table reads. A cell (i,j)(i, j) with 1≤i≤j≤n−m+i1 \le i \le j \le n - m + i is an internal node exactly once (the first time it is reached; every other occurrence is a table read); the cells of row 00 and of the region j<ij < i are leaves. Every cell of the band is reachable from (m,n)(m, n): to reach (i,j)(i, j) do m−im - i matches and (n−m)−(j−i)≥0(n - m) - (j - i) \ge 0 skips in any order. So the internal nodes are the m(n−m+1)m(n-m+1) cells of the band: 3⋅4=123 \cdot 4 = 12 for the example. Each internal node makes 22 calls, so the tree has 1+2⋅12=251 + 2 \cdot 12 = 25 nodes, of which 1313 are leaves (base cases and table reads). The memoized algorithm computes the same 1212 cells as the bottom-up one, in the order of the recursion.

(d) Exact cost and comparison

For each of the m(n−m+1)m(n - m + 1) cells of the band the algorithm computes dd: one product and one sum. A comparison is performed only when j>ij > i, that is for n−mn - m cells of each row (the cells j=i+1,…,n−m+ij = i + 1, \dots, n - m + i):

products=sums=m(n−m+1),comparisons=m(n−m),total 3m(n−m)+2m.\text{products} = \text{sums} = m(n-m+1), \qquad \text{comparisons} = m(n-m), \qquad \text{total } 3m(n-m) + 2m.

Example: m=3m = 3, n=6n = 6: 1212 products, 1212 sums, 99 comparisons, 3333 operations. The cost is Θ(m(n−m+1))\Theta(m(n-m+1)), at most quadratic in nn (maximum around m=n/2m = n/2, about n2/4n^2/4 cells).

Enumeration. There are (nm)\binom{n}{m} increasing sequences of indices, each scored with mm products and m−1m - 1 sums, plus the comparisons to find the maximum: for n=2mn = 2m the number (2mm)∼4m/πm\binom{2m}{m} \sim 4^m / \sqrt{\pi m} is exponential. For the example (63)=20\binom{6}{3} = 20 matchings × (3+2)=100\times\ (3 + 2) = 100 operations plus 1919 comparisons, three times more than 3333 already for such a small case, and the gap explodes with mm and nn.

Reconstruction. Each call of PRINT_MATCH decreases jj by 11 (match: (i−1,j−1)(i-1, j-1); skip: (i,j−1)(i, j-1)), and the recursion ends when i=0i = 0, so there are at most nn calls with i≥1i \ge 1 plus the final call with i=0i = 0: O(n)O(n). In the example the calls are (3,6),(3,5),(3,4),(2,3),(1,2)(3,6), (3,5), (3,4), (2,3), (1,2) and the final one (0,1)(0,1): 66 calls in total.

Extra: space. If only the score is needed, row ii depends only on row i−1i - 1: two rows of n−m+1n - m + 1 cells suffice. The reconstruction needs the whole table BB.

python
from math import inf

def match(X, Y):
    m, n = len(X), len(Y)
    D = [[-inf] * (n + 1) for _ in range(m + 1)]
    B = [[None] * (n + 1) for _ in range(m + 1)]
    D[0] = [0] * (n + 1)                          # base: empty template
    for i in range(1, m + 1):
        for j in range(i, n - m + i + 1):         # band i <= j <= n-m+i
            d = D[i - 1][j - 1] + X[i - 1] * Y[j - 1]
            if j == i or d >= D[i][j - 1]:
                D[i][j], B[i][j] = d, 'match'
            else:
                D[i][j], B[i][j] = D[i][j - 1], 'skip'
    pairs, i, j = [], m, n                        # reconstruction
    while i > 0:
        if B[i][j] == 'match':
            pairs.append((i, j)); i -= 1; j -= 1
        else:
            j -= 1
    return D[m][n], pairs[::-1]

assert match([2, -1, 3], [1, 4, -2, 3, -3, 2]) == (19, [(1, 2), (2, 3), (3, 4)])

Verification (run for real). The bottom-up code, the memoized code and the reconstruction were compared with the brute force over all (nm)\binom{n}{m} matchings on 2000020000 random instances (1≤m≤61 \le m \le 6, m≤n≤9m \le n \le 9, entries in [−6,6][-6, 6]): the scores always coincide, the rebuilt matching is increasing and has exactly the optimal score, the operation counters are exactly m(n−m+1)m(n-m+1) products, m(n−m+1)m(n-m+1) sums and m(n−m)m(n-m) comparisons, and the internal nodes of the memoized tree never exceed m(n−m+1)m(n-m+1). For the example the code gives 1919 with matching (1,2),(2,3),(3,4)(1,2), (2,3), (3,4), the tables above, 1212 internal nodes and 2525 calls.

Typical mistakes. Initializing D(i,j)D(i, j) with 00 for i>ji > j (a matching that does not exist would get a score); computing the full m×nm \times n table and then reading cells outside the band; using 00 or −1-1 as memoization sentinel (scores can be negative); adding the product when skipping; looking for the best matching with a greedy rule (taking the largest products first breaks the order of the indices); forgetting that j=ij = i allows only the match.

Exercise 2 (points 11)

Pairs and triples with a given sum. Let a=⟨a0,…,an−1⟩a = \langle a_0, \dots, a_{n-1} \rangle be an array of n≥2n \ge 2 integers with 0≤ai<M0 \le a_i < M, where M=2kM = 2^k is a power of two (MM and nn of the same order of magnitude). Let cv=∣{i:ai=v}∣c_v = |\{i : a_i = v\}| be the number of occurrences of the value vv and let P(x)=∑v=0M−1cvxvP(x) = \sum_{v=0}^{M-1} c_v x^v. For an integer ss let N2(s)N_2(s) be the number of pairs of indices (i,j)(i, j) with 0≤i<j≤n−10 \le i < j \le n - 1 and ai+aj=sa_i + a_j = s. Enumerating the pairs costs n(n−1)/2n(n-1)/2 sums.

Cost model for the FFT: operations between complex scalars; the algorithms FFT, INV_FFT and LIN_CONV of the course can be used as black boxes with their exact costs, 2Nlog⁡2N2N\log_2 N for FFT of order NN, 2Nlog⁡2N+N2N\log_2 N + N for INV_FFT, 12nlog⁡2(2n)+4n12 n \log_2(2n) + 4n for LIN_CONV on two vectors of length nn.

  • (a) [4 points] Prove that N2(s)=qs−es2N_2(s) = \dfrac{q_s - e_s}{2}, where qsq_s is the coefficient of xsx^s in P(x)2P(x)^2 and es=cs/2e_s = c_{s/2} if ss is even and es=0e_s = 0 if ss is odd. Write an algorithm PAIRS(a,M,s)(a, M, s) that uses LIN_CONV and prove it correct. Apply it to a=⟨5,1,3,2,6,3,4⟩a = \langle 5, 1, 3, 2, 6, 3, 4 \rangle, M=8M = 8, with s=6s = 6 and s=7s = 7.
  • (b) [2 points] Determine the exact cost of PAIRS in terms of nn and MM (count the nn increments that build the vector cc as sums, and count the final subtraction and division), evaluate it on the example, and find the first value n=M=2kn = M = 2^k for which it is cheaper than the enumeration of the pairs.
  • (c) [2 points] Let N3(s)N_3(s) be the number of ordered triples (i,j,l)(i, j, l), not necessarily distinct, with ai+aj+al=sa_i + a_j + a_l = s. Show that N3(s)N_3(s) is the coefficient of xsx^s in P(x)3P(x)^3, write an algorithm that computes it by evaluating PP with the FFT, and give its exact cost as a function of MM. Compute N3(10)N_3(10) for the array of (a), and compare with computing P2⋅PP^2 \cdot P by two calls of LIN_CONV.
  • (d) [3 points] Let ω=ωn\omega = \omega_n be the principal nn-th root of unity, nn a power of two, and A=DFTn(a)A = \mathrm{DFT}_n(\mathbf a) for a∈Cn\mathbf a \in \mathbb{C}^n. For an integer tt let b\mathbf b be the cyclic shift of a\mathbf a by tt positions, bj=a(j−t) mod nb_j = a_{(j - t) \bmod n}. Prove that B=DFTn(b)B = \mathrm{DFT}_n(\mathbf b) satisfies Br=ωtrArB_r = \omega^{tr} A_r for 0≤r≤n−10 \le r \le n - 1. Given DFT4(3,4,5,6)=(18,−2−2i,−2,−2+2i)\mathrm{DFT}_4(3, 4, 5, 6) = (18, -2-2i, -2, -2+2i), compute DFT4(6,3,4,5)\mathrm{DFT}_4(6, 3, 4, 5) without running the transform, and write DFTn(et)\mathrm{DFT}_n(\mathbf e_t) for the vector et\mathbf e_t with 11 in position tt and 00 elsewhere.
Show the result

(a) N2(s)=(qs−es)/2N_2(s) = (q_s - e_s)/2. For the example c=(0,1,1,2,1,1,1,0)c = (0, 1, 1, 2, 1, 1, 1, 0); s=6s = 6: q6=8q_6 = 8, e6=c3=2e_6 = c_3 = 2, N2(6)=3N_2(6) = 3; s=7s = 7: q7=8q_7 = 8, e7=0e_7 = 0, N2(7)=4N_2(7) = 4.

(b) TPAIRS(n,M)=n+12Mlog⁡2(2M)+4M+2T_{\text{PAIRS}}(n, M) = n + 12M\log_2(2M) + 4M + 2. For the example (n=7n = 7, M=8M = 8): 7+416+2=4257 + 416 + 2 = 425 operations, against 2121 sums for the enumeration. For n=Mn = M the FFT version becomes cheaper from n=M=256n = M = 256 (2893028930 against 3264032640); at 128128 it is not (1293012930 against 81288128).

(c) N3(s)=[xs] P(x)3N_3(s) = [x^s]\,P(x)^3. With h=4Mh = 4M (first power of two ≥3M−2\ge 3M - 2, for M≥4M \ge 4): cost 4hlog⁡2h+3h=16M(k+2)+12M4h\log_2 h + 3h = 16M(k+2) + 12M. For the example (M=8M = 8, h=32h = 32): 736736 operations and N3(10)=48N_3(10) = 48. Two calls of LIN_CONV cost 416+1024=1440416 + 1024 = 1440.

(d) Br=ωtrArB_r = \omega^{tr} A_r. DFT4(6,3,4,5)=(18,2−2i,2,2+2i)\mathrm{DFT}_4(6, 3, 4, 5) = (18, 2-2i, 2, 2+2i). DFTn(et)=(ωtr)0≤r≤n−1=(1,ωt,ω2t,…,ω(n−1)t)\mathrm{DFT}_n(\mathbf e_t) = (\omega^{tr})_{0 \le r \le n-1} = (1, \omega^t, \omega^{2t}, \dots, \omega^{(n-1)t}).

Show the full solution

(a) The reduction to a polynomial product

Counting identity. Expanding the square of the sum over the array positions,

P(x)=∑v=0M−1cvxv=∑i=0n−1xai⟹P(x)2=∑i=0n−1∑j=0n−1xai+aj.P(x) = \sum_{v=0}^{M-1} c_v x^v = \sum_{i=0}^{n-1} x^{a_i} \quad\Longrightarrow\quad P(x)^2 = \sum_{i=0}^{n-1}\sum_{j=0}^{n-1} x^{a_i + a_j}.

(The second form holds because xaix^{a_i} is counted once for each ii and cvc_v is the number of ii with ai=va_i = v.) So the coefficient qsq_s of xsx^s is the number of ordered pairs (i,j)(i, j), 0≤i,j≤n−10 \le i, j \le n - 1 (equal indices allowed) with ai+aj=sa_i + a_j = s. Split them:

  • ordered pairs with i≠ji \ne j: each unordered pair {i,j}\{i, j\} appears twice, (i,j)(i, j) and (j,i)(j, i), both with the same sum: they are 2N2(s)2N_2(s);
  • pairs with i=ji = j: ai+ai=sa_i + a_i = s, i.e. ai=s/2a_i = s/2: there are cs/2c_{s/2} if ss is even, none if ss is odd: ese_s.

So qs=2N2(s)+esq_s = 2N_2(s) + e_s, that is N2(s)=(qs−es)/2N_2(s) = (q_s - e_s)/2. □\square

Algorithm. PP has degree bound MM (coefficients c0,…,cM−1c_0, \dots, c_{M-1}) and P2P^2 has bound 2M−12M - 1; LIN_CONV on two vectors of length MM (a power of two) pads to 2M2M and returns the product (Polynomials - Representations and ConvolutionA polynomial with degree bound n is represented by n coefficients or by n values at n distinct points (interpolation theorem, Vandermonde matrix). By coefficients the sum costs n and the product, the linear convolution, n^2 products and (n-1)^2 sums; by values the product costs only componentwise multiplication but needs at least 2n-1 points. General conversions cost too much: evaluation n times with Horner 2n(n-1), interpolation with Gauss-Jordan n^3 or Lagrange n^2. A special base is needed: the DFT.Polynomials - Representations and Convolution →, DFT and Roots of UnityThe DFT of order n evaluates a polynomial with degree bound n at the n n-th roots of unity, y_i = p(w^i) with w = e^{2 pi i/n}; it is the product by the Fourier matrix F_n, an invertible Vandermonde matrix. The roots form a multiplicative group and satisfy three lemmas: cancellation (w_{dn}^{dk} = w_n^k, w_n^{n/2} = -1), halving (the squares of the n roots are the n/2 roots of order n/2, each twice) and summation (the sum of the powers of w^k is n if k is a multiple of n, 0 otherwise). Linear convolution theorem: (c|0) = DFT^{-1}{2n}(DFT{2n}(a|0) times DFT_{2n}(b|0)).DFT and Roots of Unity →, Fast Fourier TransformThe FFT computes the DFT_n (n a power of two) by divide and conquer: split the coefficients by index parity, p(x) = p0(x^2) + x p1(x^2), and by the halving lemma two DFTs of order n/2 suffice; y_i = y0_i + w^i y1_i and y_{i+n/2} = y0_i - w^i y1_i. The recurrence T(n) = 2T(n/2) + 2n with T(1) = 0 has exact solution 2 n log2 n. The inverse has matrix F^{-1}_{ij} = w^{-ij}/n and is obtained with the FFT on negative powers (then dividing by n outside the recursion) or with a reversed DFT_n(y). LIN_CONV multiplies two polynomials with n coefficients in 12 n log2(2n) + 4n operations.Fast Fourier Transform →).

PAIRS(a, M, s)                               { 0 <= s <= 2M-2 }
  for v <- 0 to M-1 do c[v] <- 0
  for i <- 0 to n-1 do c[a[i]] <- c[a[i]] + 1      { n increments }
  q <- LIN_CONV(c, c)                              { q = coefficients of P^2 }
  if s is even then e <- c[s/2] else e <- 0
  return (q[s] - e) / 2

Correctness. The loops compute cvc_v exactly. By the linear convolution theorem LIN_CONV(c,c)(c, c) returns the coefficients of P2P^2 (padded with a zero), so q[s]=qsq[s] = q_s up to rounding errors of the floating point roots of unity: all the quantities are integers, so one rounds to the nearest integer. Then the formula above gives N2(s)N_2(s) (the division is exact because qs−es=2N2(s)q_s - e_s = 2N_2(s) is even). □\square

The example. a=⟨5,1,3,2,6,3,4⟩a = \langle 5, 1, 3, 2, 6, 3, 4 \rangle, M=8M = 8: c=(c0,…,c7)=(0,1,1,2,1,1,1,0)c = (c_0, \dots, c_7) = (0, 1, 1, 2, 1, 1, 1, 0), that is P(x)=x+x2+2x3+x4+x5+x6P(x) = x + x^2 + 2x^3 + x^4 + x^5 + x^6. The coefficients of P2P^2 are q=(0,0,1,2,5,6,8,8,7,6,3,2,1,0,0,0)q = (0, 0, 1, 2, 5, 6, 8, 8, 7, 6, 3, 2, 1, 0, 0, 0) (index 00 to 1515; the product has degree 1212). By hand, q6q_6 collects the ordered pairs of values (v,6−v)(v, 6 - v): (1,5)(1,5) and (5,1)(5,1) give 1⋅1+1⋅1=21 \cdot 1 + 1 \cdot 1 = 2, (2,4)(2,4) and (4,2)(4,2) give 22, (3,3)(3,3) gives c32=4c_3^2 = 4, (0,6)(0,6) and (6,0)(6,0) give 00: q6=8q_6 = 8. Since s=6s = 6 is even, e6=c3=2e_6 = c_3 = 2 (the two indices with value 33 paired with themselves). So N2(6)=(8−2)/2=3N_2(6) = (8 - 2)/2 = 3: the pairs of positions {0,1}\{0, 1\} (5+15 + 1), {2,5}\{2, 5\} (3+33 + 3), {3,6}\{3, 6\} (2+42 + 4). For s=7s = 7: q7=(1,6) ⁣: ⁣1+(6,1) ⁣: ⁣1+(2,5) ⁣: ⁣1+(5,2) ⁣: ⁣1+(3,4) ⁣: ⁣2+(4,3) ⁣: ⁣2=8q_7 = (1,6)\!:\!1 + (6,1)\!:\!1 + (2,5)\!:\!1 + (5,2)\!:\!1 + (3,4)\!:\!2 + (4,3)\!:\!2 = 8 and e7=0e_7 = 0 (77 is odd): N2(7)=4N_2(7) = 4: positions {0,3}\{0, 3\} (5+25 + 2), {1,4}\{1, 4\} (1+61 + 6), {2,6}\{2, 6\} and {5,6}\{5, 6\} (3+43 + 4).

Typical mistakes. Answering qs/2q_s/2 without removing the pairs (i,i)(i, i) when ss is even; using MM instead of 2M2M as order of the transform (cyclic wrap-around: coefficients of degree ≥M\ge M would be added to the low ones); using the number of distinct values instead of the occurrences cvc_v.

(b) Exact cost

  • building cc: nn increments (sums) =n= n (zeroing the vector and the indices cost 00);
  • LIN_CONV with n=Mn = M: 12Mlog⁡2(2M)+4M12M\log_2(2M) + 4M;
  • one subtraction and one division: 22.

TPAIRS(n,M)=n+12Mlog⁡2(2M)+4M+2=Θ(n+Mlog⁡M).T_{\text{PAIRS}}(n, M) = n + 12M\log_2(2M) + 4M + 2 = \Theta(n + M\log M).

Example: 7+12⋅8⋅4+32+2=7+384+32+2=4257 + 12 \cdot 8 \cdot 4 + 32 + 2 = 7 + 384 + 32 + 2 = 425 operations, against n(n−1)/2=21n(n-1)/2 = 21 sums for the enumeration: for such small sizes the direct method is far cheaper (lower constants, as in Hybrid AlgorithmsHybridization combines two algorithms for the same problem so the result has the asymptotics of the better one and, if possible, lower constants. Choosing the algorithm only by the starting size (STUPID_HYBRID) does not help; changing the base case of the recursion (H_MUL: iterative product for n <= n0 at every leaf of Strassen's tree) gives cost n^(log2 7)(2n0+5)/n0^(log2 7 - 2) - 6n^2, minimal for n0 = 8 with leading constant about 3.92.Hybrid Algorithms →).

Crossover for n=M=2kn = M = 2^k. Compare n(n−1)/2n(n-1)/2 with n+12n(k+1)+4n+2n + 12n(k+1) + 4n + 2:

kk n=Mn = M enumeration n(n−1)/2n(n-1)/2 FFT version cheaper
5 32 496 2466 enumeration
6 64 2016 5698 enumeration
7 128 8128 12930 enumeration
8 256 32640 28930 FFT
9 512 130816 64002 FFT

From n=M=256n = M = 256 the FFT version wins and the ratio grows: for n=M=220n = M = 2^{20} it is 12⋅220⋅21+4⋅220+220≈2.7⋅10812 \cdot 2^{20} \cdot 21 + 4 \cdot 2^{20} + 2^{20} \approx 2.7 \cdot 10^{8} against n(n−1)/2≈5.5⋅1011n(n-1)/2 \approx 5.5 \cdot 10^{11}. The comparison mixes complex operations and integer sums, as the model of the course does; the conclusion is on the order of growth.

(c) Triples through the power of the polynomial

Counting identity. As in (a), P(x)3=∑i,j,lxai+aj+alP(x)^3 = \sum_{i,j,l} x^{a_i + a_j + a_l}, so the coefficient of xsx^s is the number of ordered triples with sum ss: N3(s)=[xs] P(x)3N_3(s) = [x^s]\,P(x)^3. The degree bound of P3P^3 is 3(M−1)+1=3M−23(M-1) + 1 = 3M - 2 (0≤s≤3M−30 \le s \le 3M - 3).

Algorithm by values (approach 2 of Notable Transforms and Polynomial ExponentiationSome vector families have a known or cheaper DFT than the general FFT: the constant vector (a,...,a) has DFT (na,0,...,0), the vector (a,0,...,0) has DFT (a,...,a); an (n,k)-sparse vector has a DFT made of k copies of the DFT_{n/k} of its components at multiples of k, and SPARSE_FFT costs 2 (n/k) log2(n/k) with recurrence T(n,k) = T(n/2,k/2). For the power p(x)^k of a polynomial with n coefficients: either repeated squaring with LIN_CONV, O(nk log(nk)), or evaluate p with the FFT on h = 2^ceil(log2((n-1)k+1)) points, raise each value to the k, and invert, Theta(nk log(nk)).Notable Transforms and Polynomial Exponentiation →): evaluate PP on hh points with hh a power of two, h≥3M−2h \ge 3M - 2 (for M≥4M \ge 4, h=4Mh = 4M), cube each value, and interpolate. The cube of a value is the value of the cube, as long as the hh points determine P3P^3.

TRIPLES(c, M, s)                             { 0 <= s <= 3M-3, M >= 4 }
  h <- 4M                                    { first power of two >= 3M-2 }
  yp <- FFT((c | 0_{h-M}))                   { values of P on Omega_h }
  for i <- 0 to h-1 do
    yq[i] <- yp[i] * yp[i] * yp[i]           { 2 products }
  q <- INV_FFT(yq)                           { coefficients of P^3 }
  return q[s]

Correctness. DFTh\mathrm{DFT}_h of the padded vector gives P(ωhi)P(\omega_h^i); P(ωhi)3P(\omega_h^i)^3 are the values of P3P^3 on Ωh\Omega_h; P3P^3 has bound 3M−2≤h3M - 2 \le h, so hh points determine it uniquely and INV_FFT returns its coefficients (followed by zeros). The integers are recovered by rounding.

Cost. FFT of order hh: 2hlog⁡2h2h\log_2 h; the cubes: 2h2h; INV_FFT: 2hlog⁡2h+h2h\log_2 h + h. Total 4hlog⁡2h+3h4h\log_2 h + 3h and, with h=4Mh = 4M and log⁡2h=k+2\log_2 h = k + 2:

TTRIPLES(M)=16M(k+2)+12M=Θ(Mlog⁡M).T_{\text{TRIPLES}}(M) = 16M(k+2) + 12M = \Theta(M\log M).

The example. M=8M = 8, h=32h = 32: 16⋅8⋅5+96=73616 \cdot 8 \cdot 5 + 96 = 736. The coefficients of P3P^3 are (0,0,0,1,3,9,16,27,36,44,48,45,40,30,21,13,6,3,1,0,0,0,0)(0,0,0,1,3,9,16,27,36,44,48,45,40,30,21,13,6,3,1,0,0,0,0), hence N3(10)=48N_3(10) = 48. Check by hand: the multisets of values with sum 1010 are {1,3,6}\{1,3,6\}, {1,4,5}\{1,4,5\}, {2,2,6}\{2,2,6\}, {2,3,5}\{2,3,5\}, {2,4,4}\{2,4,4\}, {3,3,4}\{3,3,4\}; each contributes (number of orders of the values) times (product of the cvc_v): 6⋅2+6⋅1+3⋅1+6⋅2+3⋅1+3⋅4=12+6+3+12+3+12=486 \cdot 2 + 6 \cdot 1 + 3 \cdot 1 + 6 \cdot 2 + 3 \cdot 1 + 3 \cdot 4 = 12 + 6 + 3 + 12 + 3 + 12 = 48. A brute force over the 73=3437^3 = 343 ordered triples of positions confirms it.

Alternative with two calls of LIN_CONV. First P⋅PP \cdot P with vectors of length M=8M = 8: 12⋅8⋅4+32=41612 \cdot 8 \cdot 4 + 32 = 416 and a result of length 2M−1=152M - 1 = 15, padded to 1616; then P2⋅PP^2 \cdot P with both vectors padded to length 1616: 12⋅16⋅log⁡232+4⋅16=960+64=102412 \cdot 16 \cdot \log_2 32 + 4 \cdot 16 = 960 + 64 = 1024. Total 14401440, almost twice the 736736 of TRIPLES: the second product works on twice the size and repeats two forward transforms and one inverse that are not needed, while the method by values does one forward and one inverse transform only. In general it is ≈36Mlog⁡2M\approx 36M\log_2 M against ≈16Mlog⁡2M\approx 16M\log_2 M.

Typical mistakes. Taking h=2Mh = 2M (too small for P3P^3: the high-degree coefficients wrap around onto the low ones and N3(s)N_3(s) comes out wrong); cubing the coefficients instead of the values; forgetting that N3N_3 counts ordered triples with repetition (to count triples of distinct indices one must subtract the cases i=ji = j, j=lj = l, i=li = l and add back i=j=li = j = l).

(d) The shift property of the DFT

Proof. By definition,

Br=∑j=0n−1bj ωrj=∑j=0n−1a(j−t) mod n ωrj.B_r = \sum_{j=0}^{n-1} b_j\,\omega^{rj} = \sum_{j=0}^{n-1} a_{(j-t) \bmod n}\,\omega^{rj}.

Put l=(j−t) mod nl = (j - t) \bmod n. As jj runs over {0,…,n−1}\{0, \dots, n-1\}, ll runs over the same set, each value exactly once (the map j↦(j−t) mod nj \mapsto (j - t) \bmod n is a bijection of Zn\mathbb{Z}_n). Moreover j≡l+t(modn)j \equiv l + t \pmod n, and since ωn=1\omega^n = 1 the power ωrj\omega^{rj} depends only on j mod nj \bmod n: ωrj=ωr(l+t)\omega^{rj} = \omega^{r(l+t)}. Therefore

Br=∑l=0n−1al ωr(l+t)=ωtr∑l=0n−1al ωrl=ωtrAr.□B_r = \sum_{l=0}^{n-1} a_l\,\omega^{r(l+t)} = \omega^{tr}\sum_{l=0}^{n-1} a_l\,\omega^{rl} = \omega^{tr}A_r. \qquad \square

(The same is seen on polynomials: the shifted vector represents xtp(x)x^t p(x) reduced modulo xn−1x^n - 1, and at a root of unity xn=1x^n = 1, so the value at ωr\omega^r is multiplied by (ωr)t(\omega^r)^t. See DFT and Roots of UnityThe DFT of order n evaluates a polynomial with degree bound n at the n n-th roots of unity, y_i = p(w^i) with w = e^{2 pi i/n}; it is the product by the Fourier matrix F_n, an invertible Vandermonde matrix. The roots form a multiplicative group and satisfy three lemmas: cancellation (w_{dn}^{dk} = w_n^k, w_n^{n/2} = -1), halving (the squares of the n roots are the n/2 roots of order n/2, each twice) and summation (the sum of the powers of w^k is n if k is a multiple of n, 0 otherwise). Linear convolution theorem: (c|0) = DFT^{-1}{2n}(DFT{2n}(a|0) times DFT_{2n}(b|0)).DFT and Roots of Unity →.)

Numerical use. a=(3,4,5,6)\mathbf a = (3, 4, 5, 6) and b=(6,3,4,5)\mathbf b = (6, 3, 4, 5): bj=a(j−1) mod 4b_j = a_{(j-1) \bmod 4}, so t=1t = 1 (b0=a3=6b_0 = a_3 = 6, b1=a0=3b_1 = a_0 = 3, ...), ω=ω4=i\omega = \omega_4 = i (the imaginary unit) and, with rr as component index, Br=i rArB_r = i^{\,r} A_r for r=0,…,3r = 0, \dots, 3:

  • B0=A0=18B_0 = A_0 = 18;
  • B1=i⋅(−2−2i)=−2i+2=2−2iB_1 = i \cdot (-2 - 2i) = -2i + 2 = 2 - 2i;
  • B2=i2⋅(−2)=2B_2 = i^2 \cdot (-2) = 2;
  • B3=i3⋅(−2+2i)=(−i)(−2+2i)=2i+2=2+2iB_3 = i^3 \cdot (-2 + 2i) = (-i)(-2 + 2i) = 2i + 2 = 2 + 2i.

So DFT4(6,3,4,5)=(18,2−2i,2,2+2i)\mathrm{DFT}_4(6, 3, 4, 5) = (18, 2-2i, 2, 2+2i). Direct check of B1B_1: 6+3i+4i2+5i3=6+3i−4−5i=2−2i6 + 3i + 4i^2 + 5i^3 = 6 + 3i - 4 - 5i = 2 - 2i.

The vector et\mathbf e_t. et\mathbf e_t is e0=(1,0,…,0)\mathbf e_0 = (1, 0, \dots, 0) shifted by tt positions, and DFTn(e0)=(1,…,1)\mathrm{DFT}_n(\mathbf e_0) = (1, \dots, 1) (Notable Transforms and Polynomial ExponentiationSome vector families have a known or cheaper DFT than the general FFT: the constant vector (a,...,a) has DFT (na,0,...,0), the vector (a,0,...,0) has DFT (a,...,a); an (n,k)-sparse vector has a DFT made of k copies of the DFT_{n/k} of its components at multiples of k, and SPARSE_FFT costs 2 (n/k) log2(n/k) with recurrence T(n,k) = T(n/2,k/2). For the power p(x)^k of a polynomial with n coefficients: either repeated squaring with LIN_CONV, O(nk log(nk)), or evaluate p with the FFT on h = 2^ceil(log2((n-1)k+1)) points, raise each value to the k, and invert, Theta(nk log(nk)).Notable Transforms and Polynomial Exponentiation →). By the property, DFTn(et)r=ωtr⋅1\mathrm{DFT}_n(\mathbf e_t)_r = \omega^{tr} \cdot 1, that is column tt of the Fourier matrix FnF_n, as seen directly from yr=∑j(et)j ωrj=ωrty_r = \sum_j (\mathbf e_t)_j\,\omega^{rj} = \omega^{rt}.

Typical mistakes. Forgetting the reduction modulo nn of the index (the shift is cyclic, elements leaving on the right come back on the left); writing ω−ti\omega^{-ti} (the sign is ++ with the convention ωn=e+2πi/n\omega_n = e^{+2\pi i/n} of the course, and the shift is to the right for positive tt); using the property for a non-cyclic shift (padding with zeros) without changing the order of the transform.

Verification (run for real). FFT, INV_FFT, LIN_CONV were implemented with a counter of complex operations: the counts are exactly 2Nlog⁡2N2N\log_2 N, 2Nlog⁡2N+N2N\log_2 N + N and 12nlog⁡2(2n)+4n12n\log_2(2n) + 4n for n=1,…,128n = 1, \dots, 128. PAIRS and TRIPLES were compared with the brute force on 30003000 random instances (M∈{2,4,8,16}M \in \{2, 4, 8, 16\}, up to 1212 elements, every ss in the allowed range): all the counts coincide. For the example the code gives N2(6)=3N_2(6) = 3, N2(7)=4N_2(7) = 4, the vector qq and the coefficients of P3P^3 above, N3(10)=48N_3(10) = 48 and the cost 736736 of TRIPLES; the crossover table of (b) was computed with the formula. The shift property was checked on 300300 random complex vectors of order 1,2,4,81, 2, 4, 8 and random t∈[−9,9]t \in [-9, 9] (agreement to 10−910^{-9}); DFT4(3,4,5,6)\mathrm{DFT}_4(3,4,5,6) and DFT4(6,3,4,5)\mathrm{DFT}_4(6,3,4,5) were computed directly and coincide with the values above. A compact version with numpy (its transform uses the minus sign in the exponent, which does not matter for squaring the values of a real vector):

python
import numpy as np

def count_pairs(a, M, s):
    c = np.bincount(a, minlength=M)                 # c[v] = occurrences of v
    q = np.rint(np.fft.ifft(np.fft.fft(c, 2 * M) ** 2).real).astype(int)   # P^2
    e = c[s // 2] if s % 2 == 0 else 0
    return (q[s] - e) // 2

a = [5, 1, 3, 2, 6, 3, 4]
assert count_pairs(a, 8, 6) == 3 and count_pairs(a, 8, 7) == 4
Self-assessment grid
Exercise Points What must be there for full marks Typical mistakes
Quiz 1-10 10 (1 each) Correct letter, with the computation done in the draft: T(16)=496T(16) = 496; Master Theorem not applicable to 2T(n/2)+nlog⁡n2T(n/2) + n\log n; 2626 comparisons; 86568656; Strassen in Case 1; 24012401 products; {a1,a4,a7}\{a_1, a_4, a_7\}; 2121; 2.622.62; 3939 extractions Forgetting the leaves in a recurrence; applying Case 3 without a polynomial gap; confusing counts of operations and of calls; stopping Strassen at n0=8n_0 = 8 instead of 44; mixing waiting and completion times; summing weights of leaves instead of internal nodes
1(a) 3 Two cases for the last index, cut-and-paste in both, base cases 00 and −∞-\infty, recurrence with the special case j=ij = i Missing proof of optimality of the subsolutions; base case 00 for i>ji > j; forgetting the case yjy_j skipped
1(b) 3 Correct fill order, band i≤j≤n−m+ii \le j \le n - m + i justified, arrows, table with D(3,6)=19D(3,6) = 19 and matching (1,2),(2,3),(3,4)(1,2),(2,3),(3,4) Computing cells outside the band or reading uninitialised cells; reconstruction that prints in reverse order; storing whole matchings instead of arrows
1(c) 2 Pseudocode INIT/REC, sentinel +∞+\infty with the reason, count by internal nodes (1212 internal nodes, 2525 calls) Sentinel 00 or −1-1; analysing the memoized code with the recurrence of the full tree
1(d) 3 m(n−m+1)m(n-m+1) products and sums, m(n−m)m(n-m) comparisons, values 12,12,912, 12, 9; comparison with (nm)\binom{n}{m} matchings; O(n)O(n) reconstruction Counting a comparison also for j=ij = i; using mnmn instead of the band; no comparison with the exponential enumeration
2(a) 4 P2=∑xai+ajP^2 = \sum x^{a_i + a_j}, ordered pairs, correction ese_s for i=ji = j, division by 22, PAIRS with LIN_CONV, correctness, N2(6)=3N_2(6) = 3, N2(7)=4N_2(7) = 4 Missing the pairs (i,i)(i, i); order MM instead of 2M2M; not rounding
2(b) 2 n+12Mlog⁡2(2M)+4M+2n + 12M\log_2(2M) + 4M + 2, value 425425 on the example, crossover at n=M=256n = M = 256 Forgetting the construction of cc; confusing log⁡2M\log_2 M with log⁡2(2M)\log_2(2M); no crossover discussion
2(c) 2 N3=[xs]P3N_3 = [x^s]P^3, h=4Mh = 4M with the reason, cost 16M(k+2)+12M16M(k+2) + 12M, N3(10)=48N_3(10) = 48, comparison with two LIN_CONV (14401440) h=2Mh = 2M (wrap-around); cubing the coefficients; cost in n3n^3
2(d) 3 Change of index l=(j−t) mod nl = (j - t) \bmod n, bijection, ωn=1\omega^n = 1, Br=ωtrArB_r = \omega^{tr}A_r, DFT4(6,3,4,5)=(18,2−2i,2,2+2i)\mathrm{DFT}_4(6,3,4,5) = (18, 2-2i, 2, 2+2i), DFT(et)=(ωtr)\mathrm{DFT}(\mathbf e_t) = (\omega^{tr}) Forgetting the modulo nn; wrong sign of the exponent; shift not cyclic