Data Structures and Algorithms - Mock Exam 3
Questa pagina non ha ancora la versione ripasso: qui sotto c'è il testo completo.
In questa pagina 7
Mock exam built on the model of the official written-exam examples of the equivalent Italian course (Dati e Algoritmi, UniPD); it is a simulation, not a real paper. The official examples have two parts: a first part of short questions of analysis and theory (here exercises 1-3, 3 + 4 + 4 = 11 points) and a second part with the execution of algorithms on data structures and the design of an algorithm in pseudocode with its analysis (here exercises 4-5, 5 + 6 = 11 points). The official sheets do not state the duration: 150 minutes for the two parts is a proposal. Since the real exam also has a programming part, exercise 6 (a LeetCode-style problem in Java) is an additional proposal, with 10 points and 60 more minutes at the computer: it is not taken from the official examples. No material allowed.
The topics of this mock are: comparison of orders of growth, best and worst case analysis, hash tables (compression function, separate chaining, load factor, rehashing), a binary tree in array representation, and maps. Linked lists with iterators, binary search trees and open addressing (linear probing) are not developed in the course notes, so they are replaced by the array representation of a binary tree (exercise 4) and by the list-based map (exercise 3, part c). Pseudocode follows the notation of PseudocodePseudocode is the rigorous, free-form way algorithms are specified in this course: a header with name, input and output, then a body that mixes programming constructs with natural language only where it helps.Pseudocode →; all the results were checked by running the algorithms (Python for exercises 1-5, Java 21 for exercise 6).
Exercise 1 (points 3)
Consider the following functions of :
(a) (2 points) Group the functions into classes of functions with the same order of growth (), and list the classes in increasing order of growth. Write for .
(b) (1 point) Prove from the definition of that , giving explicit constants , and .
Show the result
(a) , where , , , , , exponential.
(b) for all : , , .
Show the full solution
(a) Use the properties of growth rates in Analysis of Algorithms and Asymptotic NotationThe worst-case time complexity t_A(n) counts elementary RAM steps on the hardest instance of size n; since it is hard to compute exactly, it is bounded asymptotically with O, Omega, Theta and o, ignoring constants and lower-order terms.Analysis of Algorithms and Asymptotic Notation →.
- and . and : both are a constant times (the base of a logarithm does not matter inside ), so and they form one class.
- . .
- . Polylogarithmic against polynomial: , and by part (b).
- . , so . The lower-order term is absorbed by and does not change the class.
- . (polylogarithmic against polynomial, with exponent ).
- . with , and every polynomial is in : .
Typical mistakes: thinking that the small factor in the exponent makes "almost linear" (it is still exponential, and beats every polynomial); putting before ; treating and as different classes.
(b) The definition ( if there are and with for all ) asks for two bounds, each proved with the method of the notes (rewrite the lower-order term as a multiple of the dominant one).
- Lower bound. , so . Hence .
- Upper bound. For we have , so . Hence .
Both hold for every , so and . Typical mistake: proving only the upper bound, which gives but not .
Exercise 2 (points 4)
Consider the following algorithm.
Algorithm shrinkScan(A)
Input: array A[0 ÷ n-1] of n ≥ 1 integers
Output: the number of cells equal to 0 met before the algorithm stops
c ← 0;
m ← n;
while (m ≥ 1) do {
j ← 0;
while (j < m) do {
if (A[j] < 0) then return c;
if (A[j] = 0) then c ← c + 1;
j ← j + 1;
}
m ← ⌊m/2⌋;
}
return c(a) (1 point) Execute shrinkScan on (). Give the returned value and the number of times the test A[j] < 0 is evaluated.
(b) (1 point) Describe an instance of each size that is a best case for the algorithm and give the best-case time as a .
(c) (2 points) A student says: "the outer loop makes about iterations and each one can make up to steps, so the worst-case time complexity is ". Determine the worst-case time complexity of shrinkScan and say what is wrong with the claim.
Show the result
(a) Returned value ; the test A[j] < 0 is evaluated times.
(b) Any instance with : the algorithm stops after one test, .
(c) The worst case is (for instances without negative cells the test is evaluated times, between and ). The claim is wrong because the inner loop makes steps with , not steps every time: the sum is a geometric series, below .
Show the full solution
(a) Trace (see PseudocodePseudocode is the rigorous, free-form way algorithms are specified in this course: a header with name, input and output, then a body that mixes programming constructs with natural language only where it helps.Pseudocode → for the notation).
| outer pass | cells read | tests A[j] < 0 |
zeros found | after the pass | |
|---|---|---|---|---|---|
| 1 | 5 | 5 | 2 | 2 | |
| 2 | 2 | 2 | 1 | 3 | |
| 3 | 1 | 1 | 0 | 3 |
Then , the outer loop ends and the algorithm returns . Tests: . No cell is negative, so the early return never fires.
(b) The only way to leave the algorithm before the loops end is the return on a negative cell. If (for example ) it is reached at the very first test of the first pass: a constant number of operations for the initialisation, one test, and the return. So , whatever the size. Note that this is a statement about the best instance; the complexity of the notes is the worst case (see Analysis of Algorithms and Asymptotic NotationThe worst-case time complexity t_A(n) counts elementary RAM steps on the hardest instance of size n; since it is hard to compute exactly, it is bounded asymptotically with O, Omega, Theta and o, ignoring constants and lower-order terms.Analysis of Algorithms and Asymptotic Notation →).
(c) The worst case needs an upper bound valid for every instance and one instance that reaches it.
- Upper bound (every instance). Pass has and its inner loop makes at most iterations, each of constant cost . The outer loop runs for , so the total is at most plus a constant cost per outer pass, which adds . Hence .
- Lower bound (one instance). Take with no negative cell, for instance all cells equal to . The first pass alone makes iterations: at least tests, so .
Together, . The exact number of tests on the instance with no negative cell is : for it is (checked by running the algorithm).
Where the student goes wrong: "number of passes times the cost of the longest pass" is a valid upper bound, , but it is not tight, because the passes are not all long. A correct analysis sums the actual cost of each pass. Typical mistakes: saying "the complexity is " without specifying worst case, when the best case is ; giving the best case as .
Exercise 3 (points 4)
A map is implemented with a hash table with separate chaining. The keys are integers, so the hash code is the key itself, and the compression function is MAD:
where is the current number of buckets. The table is initially empty with . After each put that inserts a new key, if the load factor is greater than the table is rehashed: the new capacity is the smallest prime number , the same formula is used with the new , and the old entries are reinserted scanning the old buckets from upwards, each chain from its first to its last entry. A new entry is always appended at the end of its chain. The keys are put in this order:
(a) (1 point) Compute , and for each of the eight keys.
(b) (2 points) Show the content of the buckets after the fourth put, after the rehash that it triggers, and after the eighth put.
(c) (1 point) Give the final load factor and the number of key comparisons made by the eight put operations (the reinsertions of a rehash are not counted). How many comparisons would the same eight put make on a map implemented with an unsorted list? Would a ninth put of a new key trigger a rehash, and what must be changed in the formula if it does?
Show the result
(a)
| 85 | 15 | 48 | 13 | 44 | 70 | 86 | 59 | |
|---|---|---|---|---|---|---|---|---|
| 5 | 16 | 13 | 10 | 1 | 11 | 8 | 12 | |
| 0 | 1 | 3 | 0 | 1 | 1 | 3 | 2 | |
| 5 | 5 | 2 | 10 | 1 | 0 | 8 | 1 |
(b) After the fourth put (, ): bucket 0: ; bucket 1: ; bucket 3: ; buckets 2, 4 empty. Rehash to : bucket 2: ; bucket 5: ; bucket 10: . After the eighth put: bucket 0: ; bucket 1: ; bucket 2: ; bucket 5: ; bucket 8: ; bucket 10: ; buckets 3, 4, 6, 7, 9 empty.
(c) ; comparisons for the hash table, for the list; the ninth put gives , so a rehash to happens, and since the prime of the MAD method must be replaced by a prime greater than (for instance ).
Show the full solution
(a) For each key compute , reduce modulo (the MAD step, see Hash TablesA hash table implements a map by sending each key through a hash function to one of N buckets, handling collisions with separate chaining, and it gives expected O(1 + load factor) time per operation but Theta(n) in the worst case.Hash Tables →), then reduce modulo . For example : , so the remainder is ; then and . For : , remainder ; , . The other columns are obtained in the same way (the table above).
(b) Puts with ( row of the table):
- bucket 0; bucket 1; bucket 3 (, , no rehash).
- bucket 0, which already holds : the chain becomes (the new entry goes at the end). Now , : rehash.
N = 5 bucket 0: 85, 13 bucket 1: 15 bucket 2: - bucket 3: 48 bucket 4: -Rehash: the new capacity is the smallest prime , that is . Scan the old buckets in order, so the entries are reinserted in the order , each at the position given by : , , (appended after ), . No search is needed, because the keys are already known to be distinct.
N = 11 0:- 1:- 2:48 3:- 4:- 5:85,15 6:- 7:- 8:- 9:- 10:13Remaining puts with ( row): ; ; ; , behind . After each of them , so there is no further rehash. Final table:
N = 11 0:70 1:44,59 2:48 3:- 4:- 5:85,15 6:- 7:- 8:86 9:- 10:13Typical mistakes: reinserting the old entries in input order instead of bucket order (here would be placed before , giving the chain in bucket 5); taking the new size instead of the prime ; forgetting that the new entry is appended at the end of the chain.
(c) , : .
Comparisons. A put searches the chain of its bucket for the key before appending. Only two puts find a non-empty chain: meets (1 comparison) and meets (1 comparison). All the others find an empty chain. Total: comparisons.
List-based map (MapsA map is a collection of entries with distinct keys supporting get, put and remove by key, and implementing it with a list costs linear time while an array indexed by the whole key universe is fast but wastes space.Maps →). Every put must scan all the existing entries to check that the key is new: the -th put makes comparisons, in total (for keys ). With the hash table the expected cost of each operation is , constant for bounded ; the worst case, all keys in one bucket, is per operation, like the list.
Ninth put. A new key gives and , so a rehash to the smallest prime , that is , is needed. The MAD method requires a prime ; with we would have and the buckets could never be reached, so must be replaced (for instance ).
Exercise 4 (points 5)
A binary tree with nodes is stored in an array with level numbering: the root is , the left child of is and the right child is . A cell holds the key of the node, or null if there is no node at that position; a child index means that the node has no child there. All the nodes have integer keys. A node is visible if its key is strictly greater than the key of every proper ancestor of (the root is always visible).
(a) (1 point) Draw the tree stored in and say which nodes are visible.
(b) (2 points) Write in pseudocode a recursive algorithm countVisible that, given and , returns the number of visible nodes. Specify input and output of the generic call and the initial call.
(c) (2 points) Analyse the time complexity of countVisible as a function of . Is it ? How large can be with respect to ?
Show the result
(a) Visible nodes: (6 nodes). Not visible: .
(b) Initial call countVisible(A, M, 0, -∞); it returns on the array of part (a).
(c) : exactly calls ( for ), each of constant cost. It is not : can be exponential in (, up to about for a skewed tree).
Show the full solution
(a) Children of are and (HeapsA heap is a complete binary tree whose entries satisfy the heap-order property, stored in an array by level numbering, which implements a priority queue with insert and removeMin in logarithmic time and can be built from n entries in linear time.Heaps →, level numbering, here applied to a generic binary tree as in Binary TreesA binary tree is an ordered tree where each node has at most two children (left and right); in a proper binary tree every internal node has exactly two, which gives the leaf count m = n - m + 1 and bounds linking height, leaves and nodes.Binary Trees →): has children and ; has children and ; has children and ; has no children (, are null); has children and ; is null so , are null; has children and .
8
/ \
5 11
/ \ \
3 9 14
/ \ / \
10 6 12 17Visibility: the maximum key among the proper ancestors is for (visible); for and (so is not visible, is); the ancestors of and are and , maximum , so is not visible and is; the ancestors of and are , maximum , so is visible and is not; the ancestors of are , maximum , so is visible; the ancestors of and are , maximum , so is visible and is not. Visible: .
(b) It is a preorder-like visit (Tree TraversalsPreorder visits a node before its subtrees (top-down), postorder after them (bottom-up); both run in time proportional to the number of nodes plus the cost of the visits, and are design patterns for algorithms on trees.Tree Traversals →) in which the node is processed before its subtrees and carries the information of the path (the maximum key found so far). The parameter best is exactly what a node needs to know about its ancestors.
Algorithm countVisible(A, M, i, best)
Input: array A[0 ÷ M-1] storing a binary tree with level numbering (null = no node),
index i ≥ 0 of a position, best = maximum key among the proper ancestors
of position i (-∞ if i is the root)
Output: number of visible nodes of the subtree whose root is at position i
if (i ≥ M) OR (A[i] = null) then return 0; // BASE CASE: no node here
c ← 0;
if (A[i] > best) then { // visible: key above all ancestors
c ← 1;
best ← A[i]; // the maximum for the children
}
l ← countVisible(A, M, 2i + 1, best); // left subtree
r ← countVisible(A, M, 2i + 2, best); // right subtree
return c + l + rThe initial call is countVisible(A, M, 0, -∞). As required for recursive algorithms (PseudocodePseudocode is the rigorous, free-form way algorithms are specified in this course: a header with name, input and output, then a body that mixes programming constructs with natural language only where it helps.Pseudocode →, Recursion and its AnalysisA recursive algorithm solves an instance by calling itself on smaller instances until a base case; its cost is the sum of node costs in the recursion tree and its correctness is proved by induction.Recursion and its Analysis →), every recursive call has the same signature as the header, the base case is explicit and the returned values are stored in variables before being used. Execution on the array of (a): at positions , and elsewhere, so the result is .
(c) Use the recursion tree (Recursion and its AnalysisA recursive algorithm solves an instance by calling itself on smaller instances until a base case; its cost is the sum of node costs in the recursion tree and its correctness is proved by induction.Recursion and its Analysis →). Every node of (a non-null cell) executes the body once and makes exactly two recursive calls, on the two child positions, whether or not the children exist. A call on a null cell or on an index stops in the base case and makes no further call. So:
- there are calls on existing nodes (one per node) and, besides the first call on the root, every other call is a child call of an existing node: the total number of calls is (for : calls, on nodes and on null positions; checked by running the algorithm);
- each call costs (two comparisons, a few assignments, the sum).
Total: . The array has cells, but the algorithm never visits the cells that are not children of an existing node: the cost is independent of , so it is not .
For a binary tree of height , level numbering needs cells, and can be as large as (a path in which every node has one child), so can be of order while is small (see HeapsA heap is a complete binary tree whose entries satisfy the heap-order property, stored in an array by level numbering, which implements a priority queue with insert and removeMin in logarithmic time and can be built from n entries in linear time.Heaps →: the array of a skewed tree grows exponentially). In that case an algorithm that scans the whole array would be exponential in , while countVisible stays linear. Typical mistakes: writing or for the cost; stopping the recursion only when and forgetting the null test (it would read a null as a key); updating best after the recursive calls instead of before them; using instead of in the visibility test (equal keys would then count as visible).
Exercise 5 (points 6)
Let be a sequence of integers, possibly with repetitions. Position is a repetition if for some . For example, in the positions and are repetitions.
(a) (3 points) Design an algorithm firstRepeat that returns the smallest position that is a repetition, or if all the elements are distinct. The algorithm must use a map through the methods get and put of the Map interface only, and must make a single pass over . State precisely input and output.
(b) (2 points) Analyse the time complexity of firstRepeat: best case, average case with a hash table with separate chaining (assume a uniform hash function and a load factor kept below a constant), and worst case. What changes if is implemented with an unsorted list?
(c) (1 point) Give a loop invariant that proves the correctness of the algorithm.
Show the result
(a) firstRepeat returns , the first position whose key is already in , otherwise (on it returns ).
(b) Best case (for example ); average case for distinct elements; worst case (all keys in one bucket); with an unsorted list in the worst case.
(c) At the start of iteration , contains exactly the values of , and no position is a repetition.
Show the full solution
(a) Idea: scan from left to right keeping in the values already seen (key = value of , value = its position). A position is a repetition exactly when is already a key of ; the first time this happens we have found the smallest repetition and we can stop. See MapsA map is a collection of entries with distinct keys supporting get, put and remove by key, and implementing it with a list costs linear time while an array indexed by the whole key universe is fast but wastes space.Maps → for the interface: get returns null if the key is absent, so the stored value must never be null: the position works.
Algorithm firstRepeat(S)
Input: array S[0 ÷ n-1] of n ≥ 0 integers
Output: the smallest j such that S[j] = S[i] for some i < j, or -1 if there is none
M ← empty map;
for j ← 0 to n-1 do {
if (M.get(S[j]) ≠ null) then return j; // S[j] already seen: first repetition
M.put(S[j], j); // first occurrence of S[j]: remember it
}
return -1Trace on : : get(7) is null, put ; : put ; : put ; : get(3) returns , not null, so the algorithm returns (the position would be the next repetition, but the algorithm has already stopped). On all the get return null and the result is ; on the result is ; on the empty sequence the loop does not run and the result is .
(b) Each iteration makes one get and (if it does not return) one put; their cost with a hash table is given in Hash TablesA hash table implements a map by sending each key through a hash function to one of N buckets, handling collisions with separate chaining, and it gives expected O(1 + load factor) time per operation but Theta(n) in the worst case.Hash Tables →.
- Best case. If the algorithm returns at after a constant number of operations: .
- Average case, distinct elements (the algorithm does all iterations). Under uniform hashing and with the load factor kept below a constant (by rehashing),
getandputcost in expectation, so the expected total is . The rehashings cost overall, amortised over the insertions. - Worst case. All the keys fall in the same bucket (the table degenerates into a list). At iteration the chain has entries and the key is absent:
getscans entries andputscans them again before appending, so the iteration costs and the total is . (Running the algorithm with a constant hash function on distinct keys gives key comparisons, that is .) - Unsorted list. Both operations are (MapsA map is a collection of entries with distinct keys supporting get, put and remove by key, and implementing it with a list costs linear time while an array indexed by the whole key universe is fast but wastes space.Maps →), so with distinct elements the cost is again in the worst case, whatever the input: the hash table is better on average, not in the worst case.
(c) Invariant: at the beginning of the iteration with index (), (i) no position is a repetition, and (ii) contains exactly the values of as keys, each associated with its position.
- Initialisation (): there are no positions ; is empty.
- Maintenance: assume the invariant at . If is a key of , then by (ii) it equals some with , so is a repetition, and by (i) no smaller position is: the
return jis correct. Otherwise is different from all of , position is not a repetition (so (i) holds for ), and theputadds exactly the new key (so (ii) holds for ). - Termination: if the loop ends normally, and by (i) no position is a repetition: is correct. The loop makes iterations, so the algorithm terminates.
Typical mistakes: storing null as the value, which get cannot distinguish from an absent key; returning the repeated value instead of the position; returning the position of the first occurrence; claiming in the worst case without the assumption of uniform hashing; scanning the whole sequence before answering (then the best case is no longer ).
Exercise 6 (points 10)
Programming part: this exercise is a proposal, in the style of the problems of competitive-programming sites, and is not taken from the official examples.
A sensor logs a sequence of signed integer readings. A window is a non-empty block of consecutive readings. Write in Java the method
static long countWindows(int[] r, long target)that returns the number of windows of r whose readings sum to exactly target. Windows with the same readings but at different positions count as different.
Constraints. where is r.length; ; .
Examples.
| input | output | explanation |
|---|---|---|
r = [1, 2, 3], target = 3 |
2 |
windows and |
r = [1, -1, 1, -1], target = 0 |
4 |
at positions 0-1, at 1-2, at 2-3 and the whole array |
r = [0, 0, 0], target = 0 |
6 |
all the windows |
Required complexity. Expected time and extra space; the solutions that examine all the windows () are too slow for .
Show the result
For the three examples the method returns 2, 4, 6. On r = [5]: target = 4 gives 0 and target = 5 gives 1. On an array of zeros with target = 0 it returns 20000100000, which does not fit in an int.
Show the full solution
Idea. Let and be the prefix sums. The window has sum . So a window ending at has sum target exactly when an earlier prefix has value . We scan once, keeping in a map (MapsA map is a collection of entries with distinct keys supporting get, put and remove by key, and implementing it with a list costs linear time while an array indexed by the whole key universe is fast but wastes space.Maps →, implemented by HashMap, a hash table with separate chaining, see Hash TablesA hash table implements a map by sending each key through a hash function to one of N buckets, handling collisions with separate chaining, and it gives expected O(1 + load factor) time per operation but Theta(n) in the worst case.Hash Tables →) how many times each prefix-sum value has appeared so far; at each position we add to the answer the number of earlier prefixes equal to . The empty prefix must be in the map from the start, otherwise the windows that begin at position are missed.
import java.util.HashMap;
import java.util.Map;
public class Windows {
/** Number of non-empty contiguous windows of r whose sum equals target. */
static long countWindows(int[] r, long target) {
Map<Long, Integer> seen = new HashMap<>(); // prefix sum -> how many prefixes have it
seen.put(0L, 1); // the empty prefix, sum 0
long prefix = 0; // sum of r[0..j]
long count = 0; // windows found so far
for (int x : r) {
prefix += x;
// windows ending here with sum target: earlier prefixes equal to prefix - target
count += seen.getOrDefault(prefix - target, 0);
seen.merge(prefix, 1, Integer::sum); // record the current prefix
}
return count;
}
}The order of the two map operations matters: the lookup is done before the current prefix is recorded, so that a window is never empty (a window with would otherwise be counted from a prefix to itself).
Trace on example 2 (r = [1, -1, 1, -1], target = 0). Start: seen = {0: 1}, prefix = 0.
x |
prefix |
looked up prefix - target |
found | count |
seen after |
|---|---|---|---|---|---|
| 1 | 1 | 1 | 0 | 0 | {0:1, 1:1} |
| -1 | 0 | 0 | 1 | 1 | {0:2, 1:1} |
| 1 | 1 | 1 | 1 | 2 | {0:2, 1:2} |
| -1 | 0 | 0 | 2 | 4 | {0:3, 1:2} |
Result , as expected.
Complexity. One pass of iterations, each with a get and a put (getOrDefault and merge) on the hash table: expected each under uniform hashing with bounded load factor (Hash TablesA hash table implements a map by sending each key through a hash function to one of N buckets, handling collisions with separate chaining, and it gives expected O(1 + load factor) time per operation but Theta(n) in the worst case.Hash Tables →), so expected time and space for the at most distinct prefix sums. In the worst case, with all the prefix sums in the same bucket, the cost would be , like the map implemented with a list.
Why long. The prefix sums reach and the number of windows reaches for : both overflow int. Typical mistakes: int for the prefix sum or for the counter; forgetting seen.put(0L, 1); recording the current prefix before looking up prefix - target; using a double loop (correct but , about steps).
Test battery (compiled with JDK 21 and -Xlint:all, no warnings, and run):
- the three examples:
2,4,6; also[5]with targets and :0,1; - random arrays of length - with values in and targets in , compared with the brute-force double loop: mismatches;
- zeros,
target = 0:20000100000; - random readings in ,
target = 7:0windows (the whole run on the three large inputs takes about ms); - readings equal to and
target:1(only the whole array).
Self-assessment grid
| Exercise | Points | What must be there for full marks | Typical mistakes |
|---|---|---|---|
| 1 | 3 | The classes with the reason of each step; both bounds with | Treating and as different classes; taking as polynomial; proving only |
| 2 | 4 | Trace with result and tests; best case with an instance; worst case with upper bound (geometric series) and lower bound (one instance) and the error in the claim | Answering ; not distinguishing best and worst case; best case |
| 3 | 4 | The hash values; tables after the 4th put, after the rehash (order of reinsertion, ) and at the end; ; and comparisons; ninth put triggers the rehash to and must change | Wrong reinsertion order; instead of the prime ; forgetting ; counting rehash reinsertions as comparisons |
| 4 | 5 | Tree and visible nodes; recursive algorithm with explicit base case and best passed down; calls, independent of ; up to exponential in |
Cost ; missing null test; wrong update of best; instead of |
| 5 | 6 | One pass with get/put, return j on the first key already in , the position stored as value; best , average , worst , list-based ; invariant with the three steps |
Value null stored; returning the value or the first occurrence; no assumption on the hash function; invariant without initialisation or maintenance |
| 6 | 10 | Prefix sums plus a map of counts with the empty prefix in it; lookup before insertion; long everywhere; expected ; tested on the examples and on large inputs |
int overflow; missing initial {0: 1}; wrong order of lookup and insertion; double loop |