Algorithms in Engineering - Exam of 9 July 2025
Questa pagina non ha ancora la versione ripasso: qui sotto c'è il testo completo.
In questa pagina 3
This is the translation of Part 2 of the written exam of 9 July 2025 of the equivalent course taught in Italian at the University of Padua ("Algoritmi per l'Ingegneria", Information Engineering, UniPD). The sheet contains only the second part (problem solving): two exercises, worth 16 and 17 points, 33 points in total; the duration is not printed on the sheet. Part 1 of the exam (a closed-answer questionnaire on the basics of the course) is not public and is not reproduced here.
The official exam format of this course is a written test in two parts: (1) a closed-answer questionnaire on the basics of the course; (2) problems (development and analysis of an algorithm, proof of a property). The second part may be left uncorrected if the first part is seriously insufficient; if the test is insufficient, the whole test must be taken again. The instructor may add an optional oral exam. Use of AI is forbidden.
The text of the problems is translated faithfully. The solutions below were written for this course and checked against the official solution (which is in English) and with Python programs (details at the end of each solution). Pseudocode follows the style of the notes (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 →, String Alignment and Longest Palindromic Subsequencetwo string problems solved by dynamic programming like the LCS; optimal DNA alignment with score matrix S and gap penalty g uses C(i,j) = max{C(i-1,j-1) + s, C(i-1,j) + g, C(i,j-1) + g} in Theta(mn) time and Theta(min{m,n}) space for the cost alone, while the longest palindromic subsequence works on substrings with p(i,j) = 2 + p(i+1,j-1) if x_i = x_j, else max of the two shorter substrings, scanned by diagonals with n(n-1)/2 comparisons.String Alignment and Longest Palindromic Subsequence →).
Exercise 1 (points 16)
Consider the following recurrence relation, defined for arbitrary positive values of the parameter :
Using parametric induction, determine a constant such that for every .
Show the result
: the constraints are (base cases) and (inductive step), so for every .
Show the full solution
This is exactly the setting of Parametric InductionParametric induction proves a bound T(n) <= cn+d (or >=) with unknown constants c and d: simulate the induction proof, collect constraints on c and d from the base and the step HP => TH, and if their intersection is nonempty pick the best pair. For MAX it gives exactly T(n) = n-1; it can fail even for true guesses (add a parameter or a lower-order term).Parametric Induction →: we simulate an induction proof of the guess , with an unknown constant that is the same for all , we collect the constraints that make every step valid, and at the end we choose a value of that satisfies all of them. The recurrence has floors and ceilings and unbalanced subproblems ( and ), so no closed form is available and the 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 → does not apply as it stands: parametric induction is the right tool.
Step 1: base cases [B]. For we have , and the guess requires , that is . There is one constraint per base value, and they are all implied by the most restrictive one, which is the one with the smallest :
(Typical error: checking only one value of , for instance , which gives and would produce a constant that is too small.)
Step 2: hypothesis [HP]. For assume for every with . The two recursive arguments must be inside this range:
- and ;
- for (for : ), and .
So [HP] can be applied to both terms (and the argument is never , where the guess would say and the recurrence is not defined).
Step 3: inductive step [HP TH]. We want for . We use the definition, [HP] on both terms (the coefficient and keep the inequality direction), and the always-valid bounds and :
The last symbol is a condition on , not a true inequality. Moving to the right-hand side:
How to read this condition. For , that is (it is the range in which the step is used), we need the smallest such that for all . Dividing by : . The right-hand side is decreasing in , so the worst case is the smallest , that is :
Geometrically: the lines all pass through the origin; we need one above the line for all . The line has slope (for ) while has slope , so once is above at the first admissible point it stays above: it is enough to impose it at , that is .
Step 4: intersection. The constraints are (base) and (step), so the set of admissible constants is ; for an upper bound we take the smallest:
Typical errors. Forgetting that the step is used for only and trying to impose at ; forgetting the in and obtaining from the step as well (the constant would then be , which does not satisfy the step with the bounds used here); using the bound , which is false (for it would say ); not checking that the arguments of lie in .
A remark on sharpness (not required). The constant is sufficient, but it is not the best one. A more careful bound on the ceiling, (valid for integers), gives , and the step becomes
which holds for every as soon as . So with this finer estimate the constraint from the step is no longer stronger than the one from the base and parametric induction yields , which is the best possible constant for the guess , because . The exam asks only for a constant, and is the value of the official solution.
Verification with a program. The recurrence was evaluated for every : holds everywhere, and the largest ratio is exactly , attained at (so is also correct, as in the remark). The first values are . For the program checked that both recursive arguments lie in , that , and that the chain of the step with ends in (in fact with equality), and that at the step with gives .
Exercise 2 (points 17)
A string is called antipalindromic if it has even length and, for , satisfies for . (So is antipalindromic; strings of odd length are not antipalindromic.)
Given as input an arbitrary string of length defined over some alphabet , we want to determine the length of one of its Longest Antipalindromic Subsequences (). (Observe that this length will always be an even number.)
2.(a) [6 points] Prove an optimal substructure property for the problem on the space of the substrings of .
2.(b) [3 points] Give a recurrence for the length of of a generic subinstance .
2.(c) [5 points] Give the iterative bottom-up pseudocode COMPUTE_SALM that, given an input string , returns the length of a , arguing its correctness.
2.(d) [3 points] Let be the number of comparisons between characters of the alphabet performed by the algorithm developed in Point 2.(c). Evaluate exactly.
Show the result
- (a) For : if then ; if then when and when ; if and , there is a with , and a ; if and , is a of or of .
- (b) With :
- (c) Fill an table by increasing diagonals and return ; time and space .
- (d) .
Show the full solution
This is the same scheme as 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 → and especially as the longest palindromic subsequence in String Alignment and Longest Palindromic Subsequencetwo string problems solved by dynamic programming like the LCS; optimal DNA alignment with score matrix S and gap penalty g uses C(i,j) = max{C(i-1,j-1) + s, C(i-1,j) + g, C(i,j-1) + g} in Theta(mn) time and Theta(min{m,n}) space for the cost alone, while the longest palindromic subsequence works on substrings with p(i,j) = 2 + p(i+1,j-1) if x_i = x_j, else max of the two shorter substrings, scanned by diagonals with n(n-1)/2 comparisons.String Alignment and Longest Palindromic Subsequence →: substrings (not prefixes) are needed because a character is removed from both ends of the string, the table is scanned by diagonals, and the comparisons are counted one per pair . See 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 → for the general paradigm.
First: what the definition says. For the conditions are (for and ) and (for and ): the string is "anti-mirror", every character differs from the one in the mirror position. For odd the value would require , which is impossible: this is why odd lengths are excluded and why is always even. Examples over : is not antipalindromic (), is (, ), is ( and ), is not.
2.(a) Optimal substructure
For a substring let be realized by indices (so and is even). We prove five properties.
Property 1 (). has length : its subsequences are and , and the second has odd length, so .
Property 2 ( and ). The subsequences are , , , ; the last one has , so it is not antipalindromic. Hence .
Property 3 ( and ). The string is antipalindromic () and, being the whole substring, no longer subsequence exists. Hence .
(In these three cases is unique.)
Property 4 ( and ). There exists a with , and such that is a .
Proof. Start from any of . Since , the string is an antipalindromic subsequence of length , so .
- We can force the two end characters. Let (replace the first character by and the last by ). It is still a subsequence of : the new first index is and the new last index is . It is still antipalindromic: for the outer pair the condition is , true by assumption, and for every inner pair with nothing has changed. It has the same length . So is a with the required first and last character.
- The middle part is an antipalindromic subsequence of . The indices are strictly between and , and the conditions on the inner pairs are exactly the conditions defining as antipalindromic (for it is ).
- It is optimal (cut and paste). If had an antipalindromic subsequence longer than , the string would be an antipalindromic subsequence of (outer pair , inner pairs from ) of length : this contradicts the optimality of .
Remark (why "there exists"). The statement says that some has this form, not that every does (the stronger statement is false). Example: , , , : the s have length and are both and , and the second one does not use . The weaker statement is enough to get a correct algorithm: for the recurrence only the length counts, and the proof exhibits one optimal solution of the required form. This is the same situation as for the greedy choice, where it is enough to show that at least one optimal solution is compatible with the choice.
Property 5 ( and ). Every is a of or of .
Proof. If used both the first and the last position, that is and (this requires ), then , contradicting the antipalindrome condition for . Hence or (or both; also if , which is a subsequence of both substrings). In the first case is a subsequence of , in the second one of . In both cases must be optimal for that substring: otherwise a longer antipalindromic subsequence of the substring would also be an antipalindromic subsequence of , longer than (cut and paste).
Typical error: in Property 5 claiming that is the best of the two substrings and also may use and together: for equal end characters they can never be both used, whereas for different end characters they are always used.
2.(b) The recurrence
Let , for . Properties 1 to 5 give directly, with or in the base cases, in Property 4, and in Property 5 the longer of the two lengths (both substrings are candidates, since every antipalindromic subsequence of them is one of ):
The values are or obtained from other values by adding , or are a maximum of two values: by induction they are all even, as required by the text.
Note the difference with the palindromic case: there the equal end characters are used () and different ones are discarded (max); here it is the opposite.
2.(c) Bottom-up algorithm
Order of the computation. Let be the length of . The base cases are the lengths and . For the cell depends on (length ), and (length ). So filling the upper triangle diagonal by diagonal, with increasing, guarantees that every cell read has already been written. (Scanning by rows from down to , left to right, would also work; scanning by increasing rows would not, because would not exist yet.)
COMPUTE_SALM(X)
n <- length(X)
for i <- 1 to n - 1 do
S[i, i] <- 0
if x_i != x_{i+1} then S[i, i+1] <- 2
else S[i, i+1] <- 0
S[n, n] <- 0
{ the first two diagonals, l = 1 and l = 2, contain the base cases }
for l <- 3 to n do
for i <- 1 to n - l + 1 do
j <- i + l - 1
if x_i != x_j then S[i, j] <- S[i+1, j-1] + 2
else S[i, j] <- max(S[i+1, j], S[i, j-1])
return S[1, n]Correctness. By induction on we show that, when the algorithm ends, for every cell of the upper triangle. For and the initialization loop writes exactly the values of the first three lines of the recurrence in (b). For assume the claim for all lengths smaller than : the cell with reads (length , so and it is in the triangle), and (length ), all already computed and correct by induction; the if applies the last two cases of the recurrence, which are correct by (a) and (b). For there is exactly one cell, , and . The algorithm is also correct for (the first loop does not run and ) and for (the second loop does not run).
Space. The table has cells. (Optional: since the diagonal needs only the diagonals and , three vectors of length are enough to compute the length in space.)
Worked example. (). The table (only ):
| 1: a | 2: a | 3: b | 4: b | 5: a | 6: b | |
|---|---|---|---|---|---|---|
| 1: a | 0 | 0 | 2 | 4 | 4 | 4 |
| 2: a | 0 | 2 | 2 | 2 | 4 | |
| 3: b | 0 | 0 | 2 | 2 | ||
| 4: b | 0 | 2 | 2 | |||
| 5: a | 0 | 2 | ||||
| 6: b | 0 |
Some cells by hand: : , , so . : , . : , (the string itself is antipalindromic). : , . : , . The answer is .
2.(d) Number of comparisons
The algorithm compares two characters of exactly once for every substring of length (every pair ): in the initialization loop for and in the main loop for (the additions and the maxima are on integers, not on characters of ). Exactly:
(For the inner loop runs times, and goes from , for , down to , for .) In other words, , one comparison for each of the pairs of positions . For , as in the example: . Typical errors: counting also the base cases (no comparison there); writing or (the question asks for the exact value).
Verification with programs. (i) COMPUTE_SALM was implemented with a comparison counter and compared with a brute force over all subsequences (checking the antipalindrome definition literally, for all , odd lengths rejected) on 3000 random strings with over alphabets of 2 to 5 symbols, and on every substring of length up to of each of them: all values agree, they are all even, and the counter is exactly every time. (ii) The three-vector version of the diagonal scan (the optional remark) returns the same length on further random strings. (iii) The remark in (a): for the exhaustive search finds exactly two s, with -based index sets and , so not all of them use the first character; for and the unique is the whole string. (iv) The table of the worked example and its answer and its comparisons coincide with the program's output. Official solution. Same results; one typo: in Property 4 the official text writes , but is never defined, it should be ( being the length of ).
Self-assessment grid
| exercise | points | what must be there for full marks | typical errors |
|---|---|---|---|
| Exercise 1 | 16 | guess with the base constraints (most restrictive at : ); [HP] valid because both arguments are in ; step with and , leading to for , hence ; intersection | only one base value checked; ignoring that the step holds for only; dropping the and obtaining from the step; wrong bound for the ceiling; constant depending on |
| Exercise 2(a) | 6 | five properties (two base cases of length with the antipalindrome check, case with the replacement of the end characters and the cut-and-paste argument on , case where the two ends cannot both be used); the statement for is "there exists" a SALM of that form | assuming every SALM uses both ends when ; forgetting that equal ends cannot be both used; no cut-and-paste for the optimality of the middle part; properties stated without proof |
| Exercise 2(b) | 3 | the five-line recurrence on : , , for the bases, and for the other two cases | swapping the roles of equal and different ends (palindrome-style recurrence); base value for ; missing the case with equal characters |
| Exercise 2(c) | 5 | diagonal scan with increasing, initialization of , update by the recurrence, return S[1, n]; correctness by induction on showing that every cell read is already correct |
scan by increasing rows (cells not yet computed); loop bounds wrong; missing base diagonals; no correctness argument |
| Exercise 2(d) | 3 | , with the explanation of the one comparison per pair | asymptotic only; ; counting the base diagonal or the integer operations |