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 , an integer with such that is divisible by , if such a exists.
Show the result
- Instances: .
- Solutions: , that is the integers plus a special value "none".
- .
Show the full solution
A computational problem is a relation 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 , so .
2. Solution domain. The output is a divisor of strictly between and ("a proper divisor, not trivial") if one exists. The wording "if such a exists" is the trap of the exercise: for a prime no such exists, yet the definition of problem requires a solution for every instance. We add a special value, so (a flag such as , or is equivalent).
3. The relation. For composite the pairs of the first set are the correct ones; for prime only is in , because has no divisor between and (the second set is the case "the required does not exist").
Examples.
- : the pairs are all in . One instance can have several solutions, and an algorithm solving the problem computes only one of them.
- : and .
- : (note , and excludes ), while and .
Typical errors. Defining only the first set, so that primes have no solution and is not a valid problem; forgetting the bounds (then and 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 be a proper binary tree with nodes and root . Let be the left child of . Which node is the successor of in the postorder traversal of ?
Show the result
The successor of is the leftmost leaf of the right subtree of : let be the right child of and follow left children from until a leaf is reached; that leaf is the answer. (If is a leaf, the answer is 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: is internal and has two children. has nodes, so the root is not a leaf. is proper, so has exactly two children: the left child and a right child .
Step 2: order of the visit of the root. postorder(T, r) visits, in this order, all nodes of (the subtree rooted at ), then all nodes of , then :
postorder(T_u) postorder(T_w) rStep 3: is the last node of . is the root of , and the root is the last node visited in postorder. So the node visited right after is the first node visited in the postorder of .
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 (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 with = leaf (left child) and internal with children (internal, children ) and (leaf). The postorder is ; the node after is , which is exactly following left children. (Verified by script on 500 random proper trees, including skewed ones.)
Special case. If the right child is a leaf, the postorder is: nodes of , , , and the successor of is itself.
Typical errors. Answering "the right child of " (true only when it is a leaf), or "the parent " (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 , that is the tree
3
/ \
4 6
/ \
5 7(and removeMin() returns the key ).
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 children keys). In the array the children of are and and the parent is . 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.
insert(5): .insert(3): put at index , parent index has key : swap. .insert(6): put at index , parent : stop. .insert(4): put at index ; parent is index with key : swap; now is at index with parent : stop. .insert(7): put at index ; parent is index with key : stop. .insert(2): put at index ; parent is index with key : swap; now at index , parent index with key : swap; now at the root: stop. .
Tree before removeMin():
2
/ \
4 3
/ \ /
5 7 6removeMin(): the minimum is the root, (returned). Move the last entry () to the root and delete the last position, giving with a possible violation between the root and its children. Down-heap bubbling: compare with the smaller child.
- Root : children (index 1) and (index 2); the smaller is and : swap with index . Array .
- Now is at index ; its children would be at indices and , which do not exist (only entries): it is a leaf, stop.
Final array and the tree drawn in the result. Check of the heap order: and . (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 entries has 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 , define the level numbering of the nodes of as follows:
- if is the root of , then the index of in the level numbering is , that is ;
- if is not the root of , let be the parent of : then if is the left child of ; if is the right child of .
We want to design a recursive algorithm that stores in a field v.indexLN the index of in the level numbering of the nodes of , for every node .
(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 , where is the number of nodes of .
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 (one call per node, constant work per call), hence .
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 we already know .
(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) + 1Initial call: levelNumbering(T, T.root(), 1), because .
Correctness (by induction on the height of , assuming the parameter is when the call is made). Leaf: the algorithm writes and stops. Internal node : it writes ; the left child has and the right child 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 . 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 , its children and , the leaves (the numbering reads the tree level by level, left to right: it is the array position 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 →):
- Number of calls. The algorithm is called once on the root (initial call) and, for every node, once by its parent. So there is exactly one call per node: calls.
- Cost of one call, excluding the recursive calls: the assignment
v.indexLN <- i, the testisInternal, the computation of and , the access to the two children: a constant number of elementary steps, (RAM model, 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 →). - Total: , so the algorithm is as requested.
The same result follows from the recurrence: if the two subtrees have and nodes, with and (a leaf costs , an internal node ). The closed form holds for and, by induction, (since ). This is . (The script confirmed calls = n on random, left-skewed and level-order trees up to nodes.)
Remark. The bound counts and as one elementary step each, as in the RAM model of the course. The values can be huge: in a very unbalanced tree with nodes the index can have about bits (measured on a left-skewed tree: bits for nodes). In the RAM model with unit-cost arithmetic this is ignored, and the cost of 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 , not linear); calling the algorithm with 2*i for both children; starting with index instead of (then the children of the root would be and ); forgetting the initial call; not stating the number of calls in the analysis.
Part 2, Exercise 2 (points 6)
Let be a graph with vertices and edges.
(a) Design an algorithm that, given and an integer , stores for every vertex , in a variable v.numNeighbors, the number of vertices at distance from .
(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 | ; solution domain with a special "none" value; with the pairs , , , and for primes | no solution for primes; bounds 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: is the last node of and the first node visited in postorder is a leaf | right child of in general; the root ; 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 / / |
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 , root call with , children and , base case; analysis: one call per node and per call, total | missing parameter (index of the parent not available); index from ; cost from repeated paths; no justification of the count of calls |
| Part 2, Exercise 2 | 6 | out of syllabus: not graded on this course |