Salta al contenuto
Note per Studenti Data Structures and Algorithms - Official Sample Exam 3 Report

Data Structures and Algorithms - Official Sample Exam 3

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

In questa pagina 7

This is one of the official sample written exams distributed by the equivalent course taught in Italian ("Dati e Algoritmi", Engineering, University of Padua), translated into English. It is not a dated exam session: it is a sample paper. It contains parts 1 and 2 of the written exam (22 points in total: part 1 = 2 + 2 + 3 + 4, part 2 = 5 + 6); the duration is not printed on the sheet. The third part of the real exam (programming) is not part of this sheet.

The official solution is not public: every answer below was derived here and checked with Python scripts (heap operations, postorder successor on 500 random proper trees, level numbering compared with a queue-based numbering, and a count of recursive calls on trees of increasing size). Pseudocode is kept in the style of the course (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 →).

Two questions (Part 1 Exercise 4 and Part 2 Exercise 2) concern multi-way search trees and graphs, which are out of syllabus for the notes of this course: they are reported with their text but not solved.

Part 1, Exercise 1 (points 2)

Define as a computational problem the problem of finding, given an integer n>1n > 1, an integer kk with 1<k<n1 < k < n such that nn is divisible by kk, if such a kk exists.

Show the result
  • Instances: I={n∈Z:n>1}\mathcal{I} = \{n \in \mathbb{Z} : n > 1\}.
  • Solutions: S={2,3,… }∪{none}S = \{2, 3, \dots\} \cup \{\text{none}\}, that is the integers ≥2\ge 2 plus a special value "none".
  • Π={(n,k):1<k<n, k∣n}∪{(n,none):n has no divisor k with 1<k<n}\Pi = \{(n, k) : 1 < k < n,\ k \mid n\} \cup \{(n, \text{none}) : n \text{ has no divisor } k \text{ with } 1 < k < n\}.
Show the full solution

A computational problem is a relation Π⊆I×S\Pi \subseteq \mathcal{I} \times S between instances and solutions, such that every instance has at least one solution (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 →). We must therefore decide three things.

1. Instance domain. The input is a single integer n>1n > 1, so I={2,3,4,… }\mathcal{I} = \{2, 3, 4, \dots\}.

2. Solution domain. The output is a divisor kk of nn strictly between 11 and nn ("a proper divisor, not trivial") if one exists. The wording "if such a kk exists" is the trap of the exercise: for a prime nn no such kk exists, yet the definition of problem requires a solution for every instance. We add a special value, so S={2,3,… }∪{none}S = \{2, 3, \dots\} \cup \{\text{none}\} (a flag such as 00, −1-1 or ⊥\bot is equivalent).

3. The relation. Π={(n,k):n∈I, k∈Z, 1<k<n, n mod k=0} ∪ {(n,none):n is prime}.\Pi = \{(n, k) : n \in \mathcal{I},\ k \in \mathbb{Z},\ 1 < k < n,\ n \bmod k = 0\} \ \cup\ \{(n, \text{none}) : n \text{ is prime}\}. For composite nn the pairs of the first set are the correct ones; for prime nn only (n,none)(n, \text{none}) is in Π\Pi, because nn has no divisor between 11 and nn (the second set is the case "the required kk does not exist").

Examples.

  • n=12n = 12: the pairs (12,2),(12,3),(12,4),(12,6)(12, 2), (12, 3), (12, 4), (12, 6) are all in Π\Pi. One instance can have several solutions, and an algorithm solving the problem computes only one of them.
  • n=7n = 7: (7,none)∈Π(7, \text{none}) \in \Pi and (7,2)∉Π(7, 2) \notin \Pi.
  • n=4n = 4: (4,2)∈Π(4, 2) \in \Pi (note k=2<4k = 2 < 4, and k<nk < n excludes k=nk = n), while (4,4)∉Π(4, 4) \notin \Pi and (4,1)∉Π(4, 1) \notin \Pi.

Typical errors. Defining only the first set, so that primes have no solution and Π\Pi is not a valid problem; forgetting the bounds 1<k<n1 < k < n (then k=1k = 1 and k=nk = n would always be solutions and the problem would be trivial); describing an algorithm (trial division) instead of the problem: the problem says what, not how.

Part 1, Exercise 2 (points 2)

Let TT be a proper binary tree with n>1n > 1 nodes and root rr. Let uu be the left child of rr. Which node is the successor of uu in the postorder traversal of TT?

Show the result

The successor of uu is the leftmost leaf of the right subtree of rr: let ww be the right child of rr and follow left children from ww until a leaf is reached; that leaf is the answer. (If ww is a leaf, the answer is ww itself.)

Show the full solution

Recall 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 → 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 →. In a postorder traversal a node is visited after all the nodes of its subtrees, and the children are visited in order (left first).

Step 1: rr is internal and has two children. TT has n>1n > 1 nodes, so the root is not a leaf. TT is proper, so rr has exactly two children: the left child uu and a right child ww.

Step 2: order of the visit of the root. postorder(T, r) visits, in this order, all nodes of TuT_u (the subtree rooted at uu), then all nodes of TwT_w, then rr:

postorder(T_u)   postorder(T_w)   r

Step 3: uu is the last node of TuT_u. uu is the root of TuT_u, and the root is the last node visited in postorder. So the node visited right after uu is the first node visited in the postorder of TwT_w.

Step 4: first node of the postorder of a subtree. In postorder(T, w) an internal node is visited only after its children. Hence the first visited node cannot have children: it is a leaf. Which one? The first recursive call goes to the left child, which in turn first calls its own left child, and so on. So we repeatedly go to the left child, until a node without children: the leftmost leaf of TwT_w (in a proper tree every internal node has a left child, so the descent never gets stuck).

          r
        /   \
       u     w          successor of u = z
      / \   / \
     .   . a   .        w -> a -> ... -> z : always the left child
          / \
         z   .

Example. Take rr with uu = leaf (left child) and ww internal with children aa (internal, children c,dc, d) and bb (leaf). The postorder is u,c,d,a,b,w,ru, c, d, a, b, w, r; the node after uu is cc, which is exactly w→a→cw \to a \to c following left children. (Verified by script on 500 random proper trees, including skewed ones.)

Special case. If the right child ww is a leaf, the postorder is: nodes of TuT_u, ww, rr, and the successor of uu is ww itself.

Typical errors. Answering "the right child of rr" (true only when it is a leaf), or "the parent rr" (that would be the successor in the case with no right subtree, which does not happen here: in a proper tree the right child always exists); confusing postorder with preorder or inorder.

Part 1, Exercise 3 (points 3)

Consider a priority queue P, implemented by means of a heap, initially empty. Suppose the following operations are executed in the given order: P.insert(5,·), P.insert(3,·), P.insert(6,·), P.insert(4,·), P.insert(7,·), P.insert(2,·), P.removeMin(). Draw the resulting heap (as a tree, writing only the keys) at the end of the sequence of operations.

Show the result

Array P=[3,4,6,5,7]P = [3, 4, 6, 5, 7], that is the tree

        3
      /   \
     4     6
    / \
   5   7

(and removeMin() returns the key 22).

Show the full solution

A heap is a complete binary tree stored level by level in an array, with the heap-order property (parent key ≤\le children keys). In the array P[0..n−1]P[0..n-1] the children of P[i]P[i] are P[2i+1]P[2i+1] and P[2i+2]P[2i+2] and the parent is P[⌊(i−1)/2⌋]P[\lfloor (i-1)/2 \rfloor]. 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 → and 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 →.

insert(k, x): put the entry after the last position, then up-heap bubbling: while the key is smaller than its parent's, swap with the parent.

  1. insert(5): [5][5].
  2. insert(3): put 33 at index 11, parent index 00 has key 5>35 > 3: swap. [3,5][3, 5].
  3. insert(6): put 66 at index 22, parent 3≤63 \le 6: stop. [3,5,6][3, 5, 6].
  4. insert(4): put 44 at index 33; parent is index ⌊(3−1)/2⌋=1\lfloor (3-1)/2 \rfloor = 1 with key 5>45 > 4: swap; now 44 is at index 11 with parent 3≤43 \le 4: stop. [3,4,6,5][3, 4, 6, 5].
  5. insert(7): put 77 at index 44; parent is index 11 with key 4≤74 \le 7: stop. [3,4,6,5,7][3, 4, 6, 5, 7].
  6. insert(2): put 22 at index 55; parent is index 22 with key 6>26 > 2: swap; now at index 22, parent index 00 with key 3>23 > 2: swap; now at the root: stop. [2,4,3,5,7,6][2, 4, 3, 5, 7, 6].

Tree before removeMin():

          2
       /     \
      4       3
     / \     /
    5   7   6

removeMin(): the minimum is the root, 22 (returned). Move the last entry (P[5]=6P[5] = 6) to the root and delete the last position, giving [6,4,3,5,7][6, 4, 3, 5, 7] with a possible violation between the root and its children. Down-heap bubbling: compare with the smaller child.

  • Root 66: children 44 (index 1) and 33 (index 2); the smaller is 33 and 6>36 > 3: swap with index 22. Array [3,4,6,5,7][3, 4, 6, 5, 7].
  • Now 66 is at index 22; its children would be at indices 55 and 66, which do not exist (only 55 entries): it is a leaf, stop.

Final array [3,4,6,5,7][3, 4, 6, 5, 7] and the tree drawn in the result. Check of the heap order: 3≤4,63 \le 4, 6 and 4≤5,74 \le 5, 7. (The same sequence was run with a Python implementation: every intermediate array above was confirmed.)

Typical errors. Starting removeMin with the wrong replacement (taking the smallest child instead of the last entry); swapping with the larger child; drawing the tree before the removal; building the heap by sorting the keys, which gives a valid heap but not the one produced by the operations; inserting each key at the root instead of after the last position.

Part 1, Exercise 4 (points 4)

Prove that a Multi-Way Search Tree containing nn entries has n+1n + 1 leaves.

Show the result

Out of syllabus: multi-way search trees are not explained in the notes of this course (they are only mentioned in 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 the question is not solved here.

Show the full solution

The proof requires the definition of multi-way search tree (nodes with several ordered keys and one child more than keys, external leaves holding no entries), which is not part of the notes for this course. Nothing is solved here to avoid answers that are not based on the course material. The corresponding Italian-language course covers this topic in its own notes.

Part 2, Exercise 1 (points 5)

Given a proper binary tree TT, define the level numbering of the nodes of TT as follows:

  • if vv is the root of TT, then the index ℓ(v)\ell(v) of vv in the level numbering is 11, that is ℓ(v)=1\ell(v) = 1;
  • if vv is not the root of TT, let uu be the parent of vv: then ℓ(v)=2ℓ(u)\ell(v) = 2\ell(u) if vv is the left child of uu; ℓ(v)=2ℓ(u)+1\ell(v) = 2\ell(u) + 1 if vv is the right child of uu.

We want to design a recursive algorithm that stores in a field v.indexLN the index ℓ(v)\ell(v) of vv in the level numbering of the nodes of TT, for every node v∈Tv \in T.

(a) Provide the pseudocode of the requested algorithm. (b) Analyse the complexity of the algorithm.

To receive the maximum score the algorithm must have time complexity O(n)O(n), where nn is the number of nodes of TT.

Show the result

(a)

Algorithm: levelNumbering(T, v, i)
Input:  proper binary tree T, node v in T, index i = l(v)
Output: field indexLN of every node of T_v set to its level numbering index
v.indexLN <- i
if T.isInternal(v) then
    levelNumbering(T, T.left(v), 2 * i)
    levelNumbering(T, T.right(v), 2 * i + 1)

Initial call: levelNumbering(T, T.root(), 1).

(b) Time Θ(n)\Theta(n) (one call per node, constant work per call), hence O(n)O(n).

Show the full solution

Idea. The index of a node depends only on the index of its parent and on whether the node is a left or right child. Information therefore flows from the root down to the leaves: this is the preorder pattern (see 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 →): do the work on the node first, then recurse on the children. The parent's index is not stored in the node, so we pass it as an extra parameter i of the recursive call: when we call the algorithm on vv we already know ℓ(v)\ell(v).

(a) Pseudocode.

Algorithm: levelNumbering(T, v, i)
Input:  proper binary tree T, node v in T, integer i = l(v)
Output: for every node w in T_v, w.indexLN = l(w)
v.indexLN <- i                                  // visit of v
if T.isInternal(v) then
    levelNumbering(T, T.left(v), 2 * i)         // left child: 2 l(v)
    levelNumbering(T, T.right(v), 2 * i + 1)    // right child: 2 l(v) + 1

Initial call: levelNumbering(T, T.root(), 1), because ℓ(root)=1\ell(\text{root}) = 1.

Correctness (by induction on the height of TvT_v, assuming the parameter ii is ℓ(v)\ell(v) when the call is made). Leaf: the algorithm writes i=ℓ(v)i = \ell(v) and stops. Internal node vv: it writes ℓ(v)\ell(v); the left child has ℓ=2ℓ(v)\ell = 2\ell(v) and the right child ℓ=2ℓ(v)+1\ell = 2\ell(v) + 1 by definition, which are exactly the values passed; by the inductive hypothesis the two calls set the correct index in all nodes of the two subtrees. The initial call passes 1=ℓ(root)1 = \ell(\text{root}). In a proper tree an internal node has both children, so T.left(v) and T.right(v) always exist.

Example. Perfect tree with 7 nodes: the root gets 11, its children 22 and 33, the leaves 4,5,6,74, 5, 6, 7 (the numbering reads the tree level by level, left to right: it is the array position +1+ 1 of the 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).

         1
      /     \
     2       3
    / \     / \
   4   5   6   7

(b) Complexity. The analysis is the one of a traversal (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 →, 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 →):

The same result follows from the recurrence: if the two subtrees have nLn_L and nRn_R nodes, T(n)=T(nL)+T(nR)+cT(n) = T(n_L) + T(n_R) + c with n=nL+nR+1n = n_L + n_R + 1 and T(1)=c0T(1) = c_0 (a leaf costs c0c_0, an internal node cc). The closed form T(n)=(c0+c) n+12−cT(n) = (c_0 + c)\,\frac{n+1}{2} - c holds for n=1n = 1 and, by induction, T(n)=(c0+c)nL+12−c+(c0+c)nR+12−c+c=(c0+c)n+12−cT(n) = (c_0 + c)\frac{n_L + 1}{2} - c + (c_0 + c)\frac{n_R + 1}{2} - c + c = (c_0 + c)\frac{n + 1}{2} - c (since nL+nR+2=n+1n_L + n_R + 2 = n + 1). This is Θ(n)\Theta(n). (The script confirmed calls = n on random, left-skewed and level-order trees up to 40014001 nodes.)

Remark. The bound O(n)O(n) counts 2i2i and 2i+12i + 1 as one elementary step each, as in the RAM model of the course. The values ℓ(v)\ell(v) can be huge: in a very unbalanced tree with nn nodes the index can have about n/2n/2 bits (measured on a left-skewed tree: 20012001 bits for 40014001 nodes). In the RAM model with unit-cost arithmetic this is ignored, and the cost of Θ(n)\Theta(n) holds.

Typical errors. Computing the index inside the call of the parent without passing the information (then each node needs the parent, which the tree does not store); using a loop from the root for each node (cost Θ(n⋅h)\Theta(n \cdot h), not linear); calling the algorithm with 2*i for both children; starting with index 00 instead of 11 (then the children of the root would be 00 and 11); forgetting the initial call; not stating the number of calls in the analysis.

Part 2, Exercise 2 (points 6)

Let G=(V,E)G = (V, E) be a graph with nn vertices and mm edges.

(a) Design an algorithm that, given GG and an integer k>0k > 0, stores for every vertex v∈Vv \in V, in a variable v.numNeighbors, the number of vertices at distance ≤k\le k from vv. (b) Analyse the complexity of the algorithm.

Show the result

Out of syllabus: graphs and graph traversals are not covered by the notes of this course, so the question is not solved here.

Show the full solution

The exercise needs graphs, distances and graph traversals, none of which appears in the notes of this course (Fundamentals, Trees, Priority Queues and Heaps, Maps and Hash Tables). It is not solved here, to avoid answers that are not based on the course material.

Self-assessment grid
exercise points what must be there for full marks typical errors
Part 1, Exercise 1 2 I={n>1}\mathcal{I} = \{n > 1\}; solution domain with a special "none" value; Π\Pi with the pairs (n,k)(n, k), 1<k<n1 < k < n, k∣nk \mid n, and (n,none)(n, \text{none}) for primes no solution for primes; bounds 1<k<n1 < k < n forgotten; describing an algorithm instead of a problem
Part 1, Exercise 2 2 leftmost leaf of the right subtree of the root (descend left children from the right child; the right child itself if it is a leaf), with the reason: uu is the last node of TuT_u and the first node visited in postorder is a leaf right child of rr in general; the root rr; confusion with preorder or inorder
Part 1, Exercise 3 3 the six insertions with up-heap bubbling; removeMin with the last entry moved to the root and down-heap with the smaller child; final heap 33 / 4,64, 6 / 5,75, 7 swap with the larger child; wrong replacement entry; heap drawn before the removal; intermediate states not shown
Part 1, Exercise 4 4 out of syllabus: not graded on this course
Part 2, Exercise 1 5 pseudocode with the extra parameter ii, root call with 11, children 2i2i and 2i+12i + 1, base case; analysis: one call per node and Θ(1)\Theta(1) per call, total Θ(n)\Theta(n) missing parameter (index of the parent not available); index from 00; cost Θ(n⋅h)\Theta(n \cdot h) from repeated paths; no justification of the count of calls
Part 2, Exercise 2 6 out of syllabus: not graded on this course