Data Structures and Algorithms - Official Sample Exam 5
Questa pagina non ha ancora la versione ripasso: qui sotto c'è il testo completo.
In questa pagina 6
Official sample of a written exam, one of the samples distributed by the equivalent Italian course of Data Structures and Algorithms (Dati e Algoritmi) for Engineering at the University of Padua, translated into English. It is not a dated exam session. The sheet has two parts (Part 1: exercises 1-3, Part 2: exercises 4-5), with the points per question: total 22 points; the duration and the allowed material are not stated on the sheet. The official solution is not public: every answer below was derived and checked (with Python programs where the answer can be computed). The third part of the real exam (programming) is not part of this sheet.
Heap convention: as in Priority QueuesA priority queue is a collection of (key, value) entries where removal returns the entry with the smallest key (highest priority), and a list implementation makes either insertion or removal cost linear time.Priority Queues → 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 →, a heap is a min-heap (the smallest key is at the root).
Exercise 1 (points 3)
Define as a computational problem the following problem: given an array of integers, determine the number of cells whose value is greater than or equal to a given integer .
Show the result
, , . Example: .
Show the full solution
A computational problem is a relation between instances and solutions (see Computational Problems, Algorithms and Models of ComputationA computational problem is a relation between instances and solutions, an algorithm is a finite procedure that computes one valid solution for each instance in a model of computation (RAM), and a data structure organises the data the algorithm works on.Computational Problems, Algorithms and Models of Computation →). Three things must be said: the instances, the solutions, the relation.
- Instances. The input has two parts: the array and the threshold . So an instance is a pair with an array of integers () and . Forgetting among the data is the commonest mistake: with only the question has no meaning.
- Solutions. The answer is a count: (0 is possible, if no cell reaches ).
- Relation. Here the solution of every instance is unique, so is a function; the requirement "every instance has at least one solution" holds because the count always exists.
Checks: (cells 5, 7, 7); ; ; the empty array always gives 0. Note that repeated values are counted once per cell (the two 7s count twice): "number of cells", not of distinct values. A program counting the cells on the examples above confirmed these values.
Exercise 2 (points 4)
Consider the preorder traversal of a tree with nodes performed by invoking preorder(T,T.root()). For each node let be the number of children of and the cost of visiting . Recall that .
(a) Say how many nodes the recursion tree associated with preorder(T,T.root()) has, and what the cost of each node is.
(b) Let for every . Using the previous point, determine the complexity of preorder(T,T.root()).
Show the result
(a) The recursion tree has exactly nodes (one call per node of ); the node of costs .
(b) .
Show the full solution
(a) In 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 → the traversal is analysed through its recursion tree (see 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 →):
Number of nodes.
preorderis called once on the root and then once on each child of each visited node, so there is exactly one call (one node of the recursion tree) for each node of : nodes. The recursion tree has the same shape as .Cost of a node. The call on costs, not counting the recursive calls (which belong to the other nodes of the recursion tree):
- the visit of : ;
- the scan of the children of (the iterator of
children(u)in Trees - Definitions and PropertiesA rooted tree is a hierarchy of nodes under a single root; depth is the distance from the root, height the distance from the farthest leaf, and the height of a tree equals the depth of its deepest leaf.Trees - Definitions and Properties →): proportional to ; - the constant work of the call itself (test, call overhead): . It is the "+1": even a leaf, with , has a positive cost.
So the cost of the node of is .
(b) The total cost is the sum of the costs of the nodes:
- ;
- (given: every node except the root is the child of exactly one node);
- for each of the nodes, so (each term is between and with , hence the sum is between and ).
Therefore , since for and the dominant term is . The same cost would be obtained for postorder (same recursion tree, same cost per node).
Typical mistakes: saying the cost is because "a traversal is linear" (true only if : the general formula is ); or multiplying by the height of instead of summing over the nodes.
Check: a program that builds random trees with , runs the preorder counting the work per call, confirmed exactly calls, , and total cost over equal to 1.78, 1.35, 1.20, 1.17 (converging to a constant slightly above 1, as expected for ).
Exercise 3 (points 4)
Consider the array of entries and the top-down approach to build a heap from . Show the tree associated with the array at the end of each iteration of the top-down approach. (It is enough to show the keys of the entries.)
Show the result
Keys at the end of each iteration (the array after the iteration, restricted to ):
- :
- :
- :
- :
- : (final heap)
Show the full solution
Top-down construction (Solution 1 in 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 →): for the entry is inserted into the heap with an up-heap bubbling: while it has a parent with a larger key (parent of index is ) the two are swapped. Invariant at the end of iteration : is a heap and is still in the original order. Here , so there are 5 iterations (); before starting, alone is a heap.
Initial array, read as a complete binary tree (level order), is not a heap (10 is larger than its children):
10
/ \
8 6
/ \ /
7 5 2In every drawing below the nodes outside are not yet part of the heap and are not drawn.
: is a child of the root ; , swap. Array .
8
/
10: is the right child of the root ; , swap. Array .
6
/ \
10 8: becomes the left child of (index 3, parent index 1); , swap; then the parent is the root : stop. Array .
6
/ \
7 8
/
10: becomes the right child of the node (index 4, parent index 1); , swap; the new parent is the root , swap again. Two swaps. Array .
5
/ \
6 8
/ \
10 7: becomes the left child of (index 5, parent index 2); , swap; then the root , swap again. Array .
2
/ \
6 5
/ \ /
10 7 8The final array is a heap: the heap-order property holds for each node (children of : ; of : ; of : ) and the tree is complete.
Typical mistakes: showing only the final tree (the exercise asks for the tree after each iteration); using the bottom-up approach (a different algorithm, which here would give ); treating the heap as a max-heap; stopping the bubbling after one swap.
Check: a program implementing the top-down construction on reproduced all five arrays above and the number of swaps per iteration , and checked the heap-order property of the final array.
Exercise 4 (points 5)
Let be a binary search tree that implements a map whose entries are pairs , where (the key) is an instant of time in which an earthquake occurred, and (the value) is the intensity of the earthquake. Every node has a field v.max holding the maximum intensity of the earthquakes represented by the entries of (the subtree rooted at ).
(a) Design a recursive algorithm CheckGG that, given a time and an intensity value , returns yes if there was an earthquake of intensity at a time , and no otherwise. State clearly the input and the output of the algorithm.
(b) Analyse the complexity of the algorithm of the previous point.
Show the result
(a) CheckGG(v,t,i), initial call CheckGG(T.root(),t,i). If is null return no. If recurse on the right child only. Otherwise () return yes if the intensity of is , or if the right child exists and its max is ; else recurse on the left child only. One recursive call at most per call.
(b) , with the height of (at most calls, constant work each); if is balanced, in the worst case of a degenerate tree.
Show the full solution
Binary search tree property (see Trees in CA tree is a set of nodes with a root and a unique predecessor per node; in C a binary search tree uses a struct with two child pointers and recursive search, insertion at a leaf, three-case deletion and four traversals.Trees in C → and 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 →): all keys in the left subtree of a node are smaller than its key and all keys in the right subtree are larger; keys of a map are distinct. A traversal of the whole tree would be correct but ; the field max allows us to follow one path only.
Which entries have time in ? Let be the key of .
- If : and its whole left subtree (keys ) have time ; only the right subtree can contain valid entries. Go right.
- If : itself has time , and every entry of the right subtree too (keys ): all of them qualify as time. The left subtree has entries with time both below and above : it must be explored.
So for the entries to examine are: , the whole right subtree (answered in by v.right.max, that is the maximum of all their intensities), and a part of the left subtree.
Algorithm.
Algorithm CheckGG(v, t, i)
Input: v = a node of the search tree (or null), t = a time, i = an intensity;
v.key = time of the entry of v, v.value = its intensity, v.max as in the text
Output: yes if T_v contains an entry (time, intensity) with time >= t and intensity >= i;
no otherwise
if v = null then return no // base case: empty subtree
if v.key < t then
return CheckGG(v.right, t, i) // v and its left subtree are too early
else { // v.key >= t
if v.value >= i then return yes // v itself qualifies
if v.right != null AND v.right.max >= i then
return yes // all keys of the right subtree are > v.key >= t
return CheckGG(v.left, t, i) // only the left subtree remains
}Initial call: CheckGG(T.root(), t, i); the value returned by the recursive call is returned (not lost), as required for recursive algorithms in 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 →.
Correctness (induction on the number of nodes of ). Base: null has no entries, no is right. Step: assume the claim for the subtrees of .
- : the entries of with time are all in the right subtree, so the answer for is the answer for the right subtree, correct by hypothesis.
- : if has intensity then is a witness and
yesis correct. If the right child hasmax, some entry of the right subtree has intensity and, having key , time :yesis correct. Otherwise neither nor any entry of the right subtree is a witness, so a witness exists in iff it exists in the left subtree: correct by hypothesis.
(b) Complexity. Each call does a constant number of operations (comparisons and field reads) and makes at most one recursive call, on a child of . The recursion tree is therefore a path from the root, going down by one level at each call: at most calls on nodes plus possibly one on null, that is at most calls, each . The total is . In a balanced tree , giving ; in the worst case and the cost is . In every case it is not worse than the of a full traversal.
Typical mistakes: recursing on both children whenever (correct, but in the worst case it visits many nodes: no gain over a traversal); forgetting that the right subtree is entirely recent when (and thus not using max of the right child); using v.max of the node itself to answer yes (it also counts entries with time ); forgetting null children.
Check: the algorithm was implemented in Python on binary search trees (inserted in random order, max maintained) and compared with the brute-force definition on 60000 random queries over 3000 random trees of up to 40 entries (including empty trees and outside the range of the keys): all answers agreed and the number of calls never exceeded . Worked example on the tree with root , left subtree with children , , right subtree with children , (the max values are 7 at the root, 6 at 30, 7 at 70): CheckGG(root,45,6) = yes (found at the root through the right child, whose max is 7); CheckGG(root,65,8) = no after 4 calls (the root goes right because ; at 70 the right child has max 7 and 70 has intensity 2, so it goes left; 60 is before 65, so it goes right to null).
Exercise 5 (points 6)
Let and be two sorted arrays of integer keys each. In each array the keys are distinct, but a key may appear in both arrays.
(a) Design an algorithm CountNeg, containing a single loop, that determines the number of distinct negative keys appearing in and/or . For example, if and the algorithm returns 3 (distinct negative keys: ). To get full marks the algorithm must use constant space, apart from and .
(b) Specify a suitable invariant to be used to prove the correctness of the algorithm.
Show the result
(a) A merge-like scan with two indices and a counter : while some array still has a negative key at its current position, count the smaller of the two current negative keys and advance the index (or both indices, if the keys are equal). Returns 3 on the example. Time in the worst case (at most iterations), extra space.
(b) At the start of each iteration (and at the end of the loop): let . Then (1) every element of is negative; (2) every key of and of is greater than every element of ; (3) (the number of distinct elements of ).
Show the full solution
Idea. The arrays are sorted, so the negative keys of each form a prefix. It is the scheme of the merge of two sorted sequences: with two indices we read the keys of both arrays in increasing order. At each step we look at the two current keys; the smaller one is a new negative key to count (it cannot have been counted before, because it is larger than everything already consumed). If the two current keys are equal it is the same key: count it once and advance both. We stop as soon as no array has a negative key left in the current position. No auxiliary array is needed (constant space), and a key present in both arrays is counted once.
Algorithm.
Algorithm CountNeg(S1, S2, n)
Input: two sorted arrays S1[0..n-1], S2[0..n-1] of integers; keys distinct within each array
Output: the number of distinct negative keys that appear in S1 and/or S2
i <- 0; j <- 0; c <- 0
while (i < n AND S1[i] < 0) OR (j < n AND S2[j] < 0) do {
if (j = n OR S2[j] >= 0) then // only S1 has a negative key at the current position
i <- i + 1
else if (i = n OR S1[i] >= 0) then // only S2 has a negative key at the current position
j <- j + 1
else if S1[i] < S2[j] then
i <- i + 1
else if S1[i] > S2[j] then
j <- j + 1
else { // S1[i] = S2[j]: same key, counted once
i <- i + 1
j <- j + 1
}
c <- c + 1
}
return cIn the first branch, the condition of the while guarantees that has a negative key at position (since has none); in the second, has one by the same reasoning, because the first test failed. In the last three branches both heads are negative. Every iteration moves or (or both) forward and each of is at most , so the loop ends after at most iterations: termination. Cost in the worst case (for example if all the keys of both arrays are negative and distinct), constant work per iteration; only are used: constant space. On the example: , so advances (, key ); then and advances (, key ); then and both advance (, key ); then and : stop, return 3.
(b) Invariant (see Correctness and Loop InvariantsCorrectness means termination plus solving the problem; it is proved with basic proof techniques (example, counterexample, contradiction, induction) and, for loops, with an invariant shown to hold initially, to be preserved, and to imply the final state.Correctness and Loop Invariants →). Let be the set of keys already consumed. At the start of every iteration (after any number of iterations, including zero):
- all the elements of are negative;
- every key of and of is strictly greater than every element of ;
- .
Initialisation. : , . All three hold (vacuously for 1 and 2).
Maintenance. Assume the invariant before an iteration in which the loop condition holds, and let be the key consumed: in the first and third branches, in the second and fourth, the common value in the fifth. In each case is the minimum among the keys at the current positions that are negative, and it is negative. Then:
- is not in , by property 2 ( is greater than all of ), and in the branches where both heads are consumed the two heads are equal, so grows by exactly 1, the same as : property 3. Property 1 holds because .
- Property 2: in an array that advances, the remaining keys are larger than the consumed head (strictly increasing). In an array that does not advance, the head is (since is the smaller negative head, and a non-negative head is larger than ), and it is not equal to (otherwise that array would have advanced too: fifth branch), so it is , and so are the following keys. All the keys left are therefore greater than and, by the hypothesis, greater than the old elements of .
Termination. The loop ends when or and or . Since the arrays are sorted, every key at position in is (or there are none), and the same holds for : all the negative keys are in the consumed prefixes, so by property 1 is exactly the set of negative keys of . By property 3, is its number of elements: the value returned is correct.
Typical mistakes: using two loops (one scanning each array) or a nested loop to look for the common keys (the exercise requires one loop); allocating a set or an array to remove duplicates (not constant space); counting a key twice when it is in both arrays; forgetting the case where one array is exhausted ( or ) and reading ; not stating what the invariant says about the keys not yet read (property 2), which is what makes duplicates impossible.
Check: the algorithm was run in Python on the example of the text (it returns 3) and on 20000 random pairs of sorted arrays with distinct keys (length 0 to 12): the result always equals the number of distinct negative keys computed with a set, and the number of iterations never exceeded ; with all keys negative and distinct (2 arrays of keys) it performs exactly iterations.
Self-assessment grid
| Exercise | Points | What is needed for full marks | Typical mistakes |
|---|---|---|---|
| 1 | 3 | Instances (array and ), solution set (non-negative integers) and the relation stated precisely | Omitting from the instance; describing an algorithm instead of the relation; counting distinct values instead of cells |
| 2 | 4 | (a) nodes, one per node of ; cost per node. (b) Sum over nodes with and , result | Answering ; forgetting the ; multiplying by the height; no justification of the sums |
| 3 | 4 | The tree (or array) after each of the 5 iterations, correct swaps with the parent, final array | Showing only the final result; bottom-up instead of top-down; stopping bubbling too early; max-heap |
| 4 | 5 | Correct recursion on one child only; input/output stated; use of max of the right child when ; base case; with justification |
Recursing on both children; wrong use of v.max; missing base case; losing the returned value; complexity |
| 5 | 6 | A single loop, constant space, duplicates counted once, empty arrays handled; invariant with the three properties (consumed keys negative, rest larger, counter = their number) and its proof | Two loops or a set; double counting; reading out of bounds; invariant that says nothing about the unread keys |