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 and for . What is ?
- (A) 480
- (B) 496
- (C) 512
- (D) 528
Show the result
(B) .
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 internal levels; at level there are nodes, each of work , so the level costs :
The leaves cost each: . Total . Check by iterating: , , , . In closed form .
Typical mistakes: forgetting the leaves (480, which is the answer if ); summing the work as at every level (512); a wrong sign in (528).
Quiz 2
Which of the following recurrences, with and a power of the base of the argument, cannot be classified by the Master Theorem as stated in the course?
- (A)
- (B)
- (C)
- (D)
Show the result
(D).
Show the full solution
- (A) , , threshold , : Case 2, .
- (B) , , threshold , : Case 1, .
- (C) , , threshold , and (regularity with ): Case 3, .
- (D) , , threshold , is larger than but only by a logarithmic factor: for every , so Case 3 fails, and it is not either. The theorem does not apply (the true order is , found with the general formula).
Typical mistake: applying Case 3 to (D) and answering , which is wrong.
Quiz 3
An algorithm MAX3 finds the maximum of an array of elements by splitting it into three equal parts, solving them recursively and combining the three maxima with comparisons between elements; a single element is returned with no comparison. How many comparisons does MAX3 perform on elements?
- (A) 26
- (B) 27
- (C) 39
- (D) 54
Show the result
(A) 26.
Show the full solution
The recurrence is , : , , . 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 leaves; if is the number of internal nodes, counting edges gives , so and the comparisons are , the same as for the binary split: any way of splitting needs comparisons.
Typical mistakes: (three comparisons per internal node); (one conquer per leaf); (counting leaves).
Quiz 4
The hybrid algorithm H_MUL runs Strassen's recursion on matrices down to size and uses the iterative product (cost ) on the blocks of size . Counting scalar operations, what is its cost for and ?
- (A) 7872
- (B) 15271
- (C) 8656
- (D) 10192
Show the result
(C) 8656.
Show the full solution
With the closed form: , .
The other options are other thresholds or algorithms: (A) is ; (B) is pure Strassen (); (D) forgets the term .
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 .
- (B) Its recurrence falls in Case 1 of the Master Theorem, so the leaves dominate and .
- (C) The seven products are correct only if the entries of the matrices commute.
- (D) The Divide phase performs additions and the Conquer phase none.
Show the result
(B).
Show the full solution
(B) is true: , , threshold and , 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 leaves carry the cost.
(A) is false: against : for it is against , for it is against ; Strassen wins only from 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: additions/subtractions in Divide and in Conquer (total ).
Quiz 6
How many scalar multiplications does Strassen's algorithm (recursion down to matrices) perform for ?
- (A) 343
- (B) 2744
- (C) 4096
- (D) 2401
Show the result
(D) .
Show the full solution
Each call on size makes recursive calls on size and no multiplication by itself (the additions are not products): the multiplications are the leaves. For : . The iterative (and recursive block) product performs (option C); is ; is a distractor. See 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 → and Matrix Multiplication - Iterative and Recursive Block ProductCost model on n x n matrices (scalar operations, size n or N = n^2); sum in n^2 operations (optimal); iterative row-by-column product with exact cost 2n^3 - n^2; the fractal property of the block product proved on indices; recursive algorithm RMUL with T(n) = 8T(n/2) + n^2, Theta(n^3) and exact solution 2n^3 - n^2: it performs the same operations as the iterative one.Matrix Multiplication - Iterative and Recursive Block Product →.
Quiz 7
Activities occupy the half-open intervals , , , , , , , (already sorted by finish time). Which set does the earliest-finish greedy algorithm IT_GREEDY_SEL return?
- (A)
- (B)
- (C)
- (D)
Show the result
(A) (three activities, the maximum).
Show the full solution
The algorithm picks and then scans, keeping the last chosen activity and choosing when (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 →):
| interval | test | outcome | ||
|---|---|---|---|---|
| 1 | initial choice | chosen | 1 () | |
| 2 | no | discarded | 1 | |
| 3 | no | discarded | 1 | |
| 4 | yes | chosen | 4 () | |
| 5 | no | discarded | 4 | |
| 6 | no | discarded | 4 | |
| 7 | yes | chosen | 7 () | |
| 8 | no | discarded | 7 |
The scan performs 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 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 ?
- (A) 47
- (B) 39
- (C) 21
- (D) 51
Show the result
(C) .
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: . The waiting times are , with sum (formula ).
The other options: (A) is the order in which the jobs are given (); (B) is the sum of the completion times of the sorted order (), a different quantity; (D) is the worst order, longest job first. The result was also confirmed by trying all orders.
Quiz 9
A file uses seven characters with frequencies (in hundredths) . 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) bits per character.
Show the full solution
| step | merged | new weight | queue after |
|---|---|---|---|
| 1 | 12 | ||
| 2 | 22 | ||
| 3 | 28 | ||
| 4 | 42 | ||
| 5 | 58 | ||
| 6 | 100 |
The cost is the sum of the weights of the internal nodes: hundredths, i.e. . Check with the depths: and at depth ; at depth ; at depth : . The fixed-length code needs bits (D). The entropy of the source is about , a lower bound that a code with integer lengths cannot reach here: option (A) would be below the optimum .
Quiz 10
How many extractions of the minimum from the priority queue does HUFFMAN perform on an alphabet of characters (counting the extraction in the final return)?
- (A) 38
- (B) 40
- (C) 78
- (D) 39
Show the result
(D) .
Show the full solution
The loop has iterations with extractions each (), plus extraction in the return: (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 . Option (A) forgets the return; (B) counts ; (C) is , extractions plus insertions.
PART 2 (2 exercises, 11 points each)
Exercise 1 (points 11)
Signal matching. A template of integers must be matched against a measured signal of integers, with . A matching is a strictly increasing sequence of indices : every template value is used exactly once, in order, and the measurements that are not chosen are skipped. Its score is The goal is the maximum score over all matchings. Values can be negative, so every template value must really be matched.
Example. For and the matching has score , which is the maximum.
For and let be the maximum score of a matching of the prefix into the prefix , with if no matching exists (that is, if ). The answer is . Cost model: products, sums and comparisons between integers cost ; assignments, index computations and the fixed values cost .
- (a) [3 points] Prove an optimal substructure property for and derive the recurrence, with the base cases.
- (b) [3 points] Write the bottom-up pseudocode that computes 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 and , and compare with the enumeration of all matchings. Give the values for the example. How many calls does the reconstruction make?
Show the result
(a) ; for and ; for : (for only the second term is finite).
(b) , matching (that is , , ). Last row of the table: . Only the cells with are computed: cells.
(c) Sentinel . For the example: internal nodes and calls ( of them are table reads or base cases).
(d) Products , sums , comparisons ; total . For the example products, sums, comparisons ( operations); the enumeration has matchings of products and sums each ( operations plus the comparisons). Reconstruction: at most calls with plus the final call with , since decreases at every call; calls in the example ( working calls and the final one).
Show the full solution
(a) Optimal substructure and recurrence
The subproblems are the pairs of prefixes , 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.
- : the empty template has the empty matching, with score , for every : .
- (including with ): strictly increasing indices cannot fit in positions: no matching, .
Substructure. Let and let be an optimal matching of , of score . The last index is either smaller than or equal to .
- (the measurement is skipped). Then is a matching of and it is optimal for it. By contradiction (cut-and-paste): if there were a matching of with a higher score, would also be a matching of (its indices are ) with a score higher than that of , which is optimal: impossible. So .
- (the value is matched with ). Removing the last pair, is a matching of of score , and it is optimal: if were better for , then followed by the pair would be a matching of (all the indices of are , so they stay increasing) of score : contradiction. So .
Conversely, each of the two quantities is the score of a feasible matching of whenever it is finite (case 1 needs ; case 2 always works for since is finite). Hence is the larger of the two:
For the formula of the last line would also be correct (because and ), but the third line saves a comparison.
Why not plain divide and conquer. The call spawns and , which in turn both reach , and so on: the same subinstances appear many times and the recursion tree is exponential, while there are only distinct subinstances. This is the situation where a table pays off.
(b) Bottom-up algorithm, table and reconstruction
Which cells are needed. The dependencies and never increase the difference . From only cells with are reached; cells with are the base case . So only the band is computed, cells per row ( in total) instead of . Row depends on row and on itself at smaller : filling by increasing and, inside a row, increasing respects the dependencies. The dependencies of in the band are in the band: has and satisfies .
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 of the scheme).
Correctness. By induction on (and on inside the row): the cells of row are the base case; for a cell of the band the values read, and , are already correct by the induction hypothesis and the code evaluates the recurrence of (a). The reconstruction follows the arrows from back to row and prints the pairs in increasing order of index, because the recursive call comes before the print.
The example. , , , , band width . In each cell: value and arrow ( = match, = skip); a dot marks a cell outside the band, never computed.
| 1 | 2 | 3 | 4 | 5 | 6 | ||
|---|---|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | |
| () | 2 | 8 | 8 | 8 | . | . | |
| () | -2 | 10 | 10 | 11 | . | ||
| () | -8 | 19 | 19 | 19 |
Cells by hand:
- (: only the match). : , against : match, . : , : skip, . : : skip.
- . : against : match. : , : skip. : , : match.
- . : against : match. : : skip. : , : skip.
Result: . Reconstruction (bold cells): skip skip match, pair , match, pair , match, pair , stop. Read in increasing order: , that is . The second best matching has score (it uses and for and : ). 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 is already used for the infeasible cells. The sentinel is : 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 the first call returns immediately (cell ) and the second is finite, so the result is correct: 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 with is an internal node exactly once (the first time it is reached; every other occurrence is a table read); the cells of row and of the region are leaves. Every cell of the band is reachable from : to reach do matches and skips in any order. So the internal nodes are the cells of the band: for the example. Each internal node makes calls, so the tree has nodes, of which are leaves (base cases and table reads). The memoized algorithm computes the same cells as the bottom-up one, in the order of the recursion.
(d) Exact cost and comparison
For each of the cells of the band the algorithm computes : one product and one sum. A comparison is performed only when , that is for cells of each row (the cells ):
Example: , : products, sums, comparisons, operations. The cost is , at most quadratic in (maximum around , about cells).
Enumeration. There are increasing sequences of indices, each scored with products and sums, plus the comparisons to find the maximum: for the number is exponential. For the example matchings operations plus comparisons, three times more than already for such a small case, and the gap explodes with and .
Reconstruction. Each call of PRINT_MATCH decreases by (match: ; skip: ), and the recursion ends when , so there are at most calls with plus the final call with : . In the example the calls are and the final one : calls in total.
Extra: space. If only the score is needed, row depends only on row : two rows of cells suffice. The reconstruction needs the whole table .
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 matchings on random instances (, , entries in ): the scores always coincide, the rebuilt matching is increasing and has exactly the optimal score, the operation counters are exactly products, sums and comparisons, and the internal nodes of the memoized tree never exceed . For the example the code gives with matching , the tables above, internal nodes and calls.
Typical mistakes. Initializing with for (a matching that does not exist would get a score); computing the full table and then reading cells outside the band; using or 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 allows only the match.
Exercise 2 (points 11)
Pairs and triples with a given sum. Let be an array of integers with , where is a power of two ( and of the same order of magnitude). Let be the number of occurrences of the value and let . For an integer let be the number of pairs of indices with and . Enumerating the pairs costs 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, for FFT of order , for INV_FFT, for LIN_CONV on two vectors of length .
- (a) [4 points] Prove that , where is the coefficient of in and if is even and if is odd. Write an algorithm
PAIRSthat usesLIN_CONVand prove it correct. Apply it to , , with and . - (b) [2 points] Determine the exact cost of
PAIRSin terms of and (count the increments that build the vector as sums, and count the final subtraction and division), evaluate it on the example, and find the first value for which it is cheaper than the enumeration of the pairs. - (c) [2 points] Let be the number of ordered triples , not necessarily distinct, with . Show that is the coefficient of in , write an algorithm that computes it by evaluating with the FFT, and give its exact cost as a function of . Compute for the array of (a), and compare with computing by two calls of
LIN_CONV. - (d) [3 points] Let be the principal -th root of unity, a power of two, and for . For an integer let be the cyclic shift of by positions, . Prove that satisfies for . Given , compute without running the transform, and write for the vector with in position and elsewhere.
Show the result
(a) . For the example ; : , , ; : , , .
(b) . For the example (, ): operations, against sums for the enumeration. For the FFT version becomes cheaper from ( against ); at it is not ( against ).
(c) . With (first power of two , for ): cost . For the example (, ): operations and . Two calls of LIN_CONV cost .
(d) . . .
Show the full solution
(a) The reduction to a polynomial product
Counting identity. Expanding the square of the sum over the array positions,
(The second form holds because is counted once for each and is the number of with .) So the coefficient of is the number of ordered pairs , (equal indices allowed) with . Split them:
- ordered pairs with : each unordered pair appears twice, and , both with the same sum: they are ;
- pairs with : , i.e. : there are if is even, none if is odd: .
So , that is .
Algorithm. has degree bound (coefficients ) and has bound ; LIN_CONV on two vectors of length (a power of two) pads to 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) / 2Correctness. The loops compute exactly. By the linear convolution theorem LIN_CONV returns the coefficients of (padded with a zero), so 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 (the division is exact because is even).
The example. , : , that is . The coefficients of are (index to ; the product has degree ). By hand, collects the ordered pairs of values : and give , and give , gives , and give : . Since is even, (the two indices with value paired with themselves). So : the pairs of positions (), (), (). For : and ( is odd): : positions (), (), and ().
Typical mistakes. Answering without removing the pairs when is even; using instead of as order of the transform (cyclic wrap-around: coefficients of degree would be added to the low ones); using the number of distinct values instead of the occurrences .
(b) Exact cost
- building : increments (sums) (zeroing the vector and the indices cost );
LIN_CONVwith : ;- one subtraction and one division: .
Example: operations, against 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 . Compare with :
| enumeration | 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 the FFT version wins and the ratio grows: for it is against . 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), , so the coefficient of is the number of ordered triples with sum : . The degree bound of is ().
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 on points with a power of two, (for , ), cube each value, and interpolate. The cube of a value is the value of the cube, as long as the points determine .
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. of the padded vector gives ; are the values of on ; has bound , so points determine it uniquely and INV_FFT returns its coefficients (followed by zeros). The integers are recovered by rounding.
Cost. FFT of order : ; the cubes: ; INV_FFT: . Total and, with and :
The example. , : . The coefficients of are , hence . Check by hand: the multisets of values with sum are , , , , , ; each contributes (number of orders of the values) times (product of the ): . A brute force over the ordered triples of positions confirms it.
Alternative with two calls of LIN_CONV. First with vectors of length : and a result of length , padded to ; then with both vectors padded to length : . Total , almost twice the 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 against .
Typical mistakes. Taking (too small for : the high-degree coefficients wrap around onto the low ones and comes out wrong); cubing the coefficients instead of the values; forgetting that counts ordered triples with repetition (to count triples of distinct indices one must subtract the cases , , and add back ).
(d) The shift property of the DFT
Proof. By definition,
Put . As runs over , runs over the same set, each value exactly once (the map is a bijection of ). Moreover , and since the power depends only on : . Therefore
(The same is seen on polynomials: the shifted vector represents reduced modulo , and at a root of unity , so the value at is multiplied by . 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. and : , so (, , ...), (the imaginary unit) and, with as component index, for :
- ;
- ;
- ;
- .
So . Direct check of : .
The vector . is shifted by positions, and (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, , that is column of the Fourier matrix , as seen directly from .
Typical mistakes. Forgetting the reduction modulo of the index (the shift is cyclic, elements leaving on the right come back on the left); writing (the sign is with the convention of the course, and the shift is to the right for positive ); 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 , and for . PAIRS and TRIPLES were compared with the brute force on random instances (, up to elements, every in the allowed range): all the counts coincide. For the example the code gives , , the vector and the coefficients of above, and the cost of TRIPLES; the crossover table of (b) was computed with the formula. The shift property was checked on random complex vectors of order and random (agreement to ); and 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):
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) == 4Self-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: ; Master Theorem not applicable to ; comparisons; ; Strassen in Case 1; products; ; ; ; extractions | Forgetting the leaves in a recurrence; applying Case 3 without a polynomial gap; confusing counts of operations and of calls; stopping Strassen at instead of ; 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 and , recurrence with the special case | Missing proof of optimality of the subsolutions; base case for ; forgetting the case skipped |
| 1(b) | 3 | Correct fill order, band justified, arrows, table with and matching | 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 with the reason, count by internal nodes ( internal nodes, calls) |
Sentinel or ; analysing the memoized code with the recurrence of the full tree |
| 1(d) | 3 | products and sums, comparisons, values ; comparison with matchings; reconstruction | Counting a comparison also for ; using instead of the band; no comparison with the exponential enumeration |
| 2(a) | 4 | , ordered pairs, correction for , division by , PAIRS with LIN_CONV, correctness, , |
Missing the pairs ; order instead of ; not rounding |
| 2(b) | 2 | , value on the example, crossover at | Forgetting the construction of ; confusing with ; no crossover discussion |
| 2(c) | 2 | , with the reason, cost , , comparison with two LIN_CONV () |
(wrap-around); cubing the coefficients; cost in |
| 2(d) | 3 | Change of index , bijection, , , , | Forgetting the modulo ; wrong sign of the exponent; shift not cyclic |