CS 146 Final Exam 1 Solutions by Dr. Beeson 1. Analysis of non-recursive algorithms. Consider the problem of counting the number of points with integer coordinates (x,y) on the circle of radius R, where R is a positive integer. (a) Write code to do this without using any floating-point arithmetic. Efficiency is not a concern here. static int CirclePoints(int R) // count the points with integer coordinates on the circle // of radius R > 0 { int x,y,ans=0; for(x= -R;x<=R; x++) for(y= -R;y<=R; y++) if(x*x + y*y == R) ++ans; return ans; } (b) Use Θ notation to estimate the running time of your code in part (a) in terms of R. Two nested for-loops, each running over 2R+1 values: T(n) = Θ(R 2 ) (c) With floating-point arithmetic allowed, write code that will be faster for large R. static int CirclePoints(int R) // count the points with integer coordinates on the circle // of radius R > 0 { int x,y,ans=2; double ysq, epsilon = 1.0e-8; for(x= -R+1;x<R; x++) { ysq = R*R x*x; y = (int) (Math.sqrt(ysq) + epsilon); if(y*y + x*x == R*R) ++ans; } return ans; } (d) Use Θ notation to estimate the running time of your code in part (c) in terms of R: Now there is only one loop, so T(n) = : T(n) = Θ(R). Computing the square root takes a long time compared to integer arithmetic though, so the constant is bigger than just one per line.
2. Indicate, for each pair of expressions (A,B) in the table below, whether A is O, or Θ of B. Write Yes or No in each blank box of the table. [You will only receive points if you answer more than 50% correct, since you can get 50% correct by guessing.] A B O Θ 2 n n 3 No No n n 5 + n Yes No n lg n 5 No No n lg n + n Yes Yes n 5 + n n 5 Yes Yes n 23 ( n 56 ) Yes No n 23 n 28 Yes No n lg n n 2 Yes No n lg n n No No 3. Linked lists. The class StringList has these members: { String key; StringList next; } Write a method void append( StringList x) that appends x to the end of this. For example, if this is ( cat, dog ) and x is ( giraffe, anteater ), then after running append, this has the value ( cat, do, giraffe, anteater ). void append(stringlist x) // append x to the end of this { StringList marker; for(marker=this;marker.next;marker=marker.next) ; // find the end of this marker.next = x; // point the end of this to x }
4. Analyzing recursive code using recurrence relations. A recursive palindrome is a string that it is a palindrome, and in addition both its left half and its right half (if they have more than one character) are recursive palindromes. The left half and right half of a string of odd length 2n + 1 or of even length 2n are the first n characters and the last n characters. For example, WOWWOW and ABACABA are recursive palindromes but MADAM is not. For another example, WOWWOWXWOWWOW is a recursive palindrome. Assume only upper-case letters will be used. We will consider two problems about recursive palindromes: One, testing a string of length n to see if it is or is not a recursive palindrome. The function to do this can be called IsRP. The second problem is counting the number of recursive palindromes of length n. The function to do this can be called CountRP. Assume that it returns an int, i.e. BigInteger is not needed. (a) Write a recurrence relation for the worst-case running time T(n) of IsRP. T(n) = 2 T(n/2) + cn since there are two recursive calls (to check the left and right half) and checking whether x is a palindrome takes cn steps. (b) Solve that recurrence relation to give an estimate for T(n). ( Estimate means that your answer uses big-o notation.) T(n) = n lg n. This is the same recurrence relation as for merge sort. (c) Write a recurrence relation for the worst-case running time T(n) of CountRP. T(n) = T(n/2). The code is very simple, and only one recursive call will be made. ( Even though there are two lines with recursive calls, only one will be executed.) static int CountRP(int n) { int ans; if(n==1 n==2) return 26; if(n % 2 == 0) return CountRP(n/2); return 26* CountRP(n/2); } (b) Solve that recurrence relation to give an estimate for T(n). ( Estimate means that your answer uses big-o notation.) T(n) = lg n
5. Binary Search Trees. The picture represents a binary search tree. The numbers shown are arbitrary node labels, not numbers representing the contents of the nodes. The contents are not shown. If node 1 is deleted, using binary search tree deletion, what will be the new root node? Answer: node 12, the successor of 1. 6. Red-black trees. For each of the following two trees, either indicate how to color the nodes red and black (use R and B to label the nodes) to make the tree a red-black tree, or explain why that is not possible. Answer: the second tree cannot be a red-black tree because it has a branch of length 7, more than twice that of its shortest branch (three). The first tree can be made a red-black tree by coloring 2,6, and 7 red, and the other nodes black.
7. B-tree insertion. A new key 4 is to be inserted into the following B-tree. This B-tree 2,3, or 4 children per internal node. Draw a similar diagram showing the B-tree after the insertion of 4. Use the one-pass insertion algorithm, i.e. the one given in your textbook 8. Merge sort. The following array is to be sorted: 4 6 8 1 10 5 15 13 2 16 14 7 3 9 11 12 (a) If mergesort is called to sort this array, how many recursive calls will there be (not counting the top-level call)? 30 (Remark: the textbook s mergesort does get called on arrays of length 1). There will be calls to sort 2 subarrays of length 8, 4 of length 4, 8 of length 2, and 16 of length 1, making a total of 30. (b) What will be the maximum recursion depth, i.e., the maximum number of nested calls that have not been returned from yet? 5 (Here we DO count the top-level call.) (c) What will the array look like immediately after the return from the first recursive call?
Then the first half will be sorted and the second half unchanged. 1 4 5 6 8 10 13 15 2 16 14 7 3 9 11 12 9. Quick sort. The following array is to be sorted (it s the same as the one above): 4 6 8 1 10 5 15 13 2 16 14 7 3 9 11 12 (a) if quicksort is used to sort this array, what will the array look like just before the first recursive call? Pivoting will have been done. The result is 4 6 8 1 10 5 2 7 3 9 11 12 15 16 14 13 (b) What will the array look like just after the return from the first recursive call? The part before 12 will be sorted 1 2 3 4 5 6 7 8 9 10 11 12 15 16 14 13 10. Heap algorithms. The following array represents a binary tree. 4 1 7 9 5 6 3 8 2 10 11 (a) Using the convention we used for heaps, draw a picture of this tree. (b) After calling BUILD-MIN-HEAP, the resulting array will be a min-heap. Show it in array form: 1 2 3 4 5 6 7 8 9 10 11
11. Execute Prim s algorithm to find a minimal spanning tree in the following graph, starting from vertex 2. List the vertices in the order they come off the queue, and then highlight the minimal spanning tree by drawing it right on the diagram. Vertices in the order they come off the queue: 2,7,3,4,1,9,6,5,8,10. Edges of the tree are 7,9,3,4,1,6,2,14,17. Sorry, I don t have a way to draw those edges heavier, so this will have to do. Total weight 63.
12. Execute Kruskal s algorithm to find a minimal spanning tree in the following graph (which is, incidentally, the same graph as in the previous problem). List the edges in the order they are added to the answer, and also highlight the minimal spanning tree by drawing it right on the diagram. Since the edges have unique weights, you can identify an edge by its weight, e.g. you can write 11 instead of (4,5). Edges: 1,2,3,4,6,7,9,14,17. Total weight 63. Check: that s the same total weight and the same MST as we got from Prim s algorithm. It has to be not only the same weight but the same tree because the edge weights are unique.
13. If we run Dijkstra s algorithm on the graph shown below (which is the same as the graph in the previous problem, but here is another picture of it), starting from node 2, (a) how many nodes will be removed from the queue before every node gets its correct distance from node 2 calculated? Answer [just one number] : 6 (b) List the nodes in the order of their removal from the queue. Answer [a list of numbers]: 2,7,3,4,1,9,6,5,8,10. When 9 comes off, and its neighbors are marked, then those numbers don t change after that, so 6 is the answer to (a). The diagram is provided for you to use if you wish, but it s not needed to communicate the answer.
14. Needleman-Wunsch. (a) What are the asymptotic time and space requirements of the Needleman-Wunsch algorithm? Express your answers in terms of the maximum length n of the two input strings, using big-o notation. Time: O(n 2 ) Space: O(n 2 ) (b) Execute the Needleman-Wunsch algorithm to find the best alignment of COPE and CAP, scoring exact matches as 1 and non-matches as 0, with a gap penalty of 1 (i.e. matching a letter with a gap scores -1). Use the following table to execute the algorithm, showing the predecessor arrows as was done in class. Here I use D, U, L to indicate diagonal, up, left, as I don t have a way to make arrows. C O P E 0-1 -2-3 -4 C -1 1D 0L -1L -2L A -2 0U 1D 0D -1D P -3-1U 0D 2D 1L The best alignment is COPE CAP- and the score of that alignment is 1
15. Basic properties of some algorithms we studied (a) What two algorithms we studied used a priority queue? Dijstra and Prim (b) Which algorithm has a recursive version, depth-first search or breadth-first search? Depth-first search (c) Which search algorithm uses a stack? Depth-first search (d) Which algorithm is used for finding, in one run, the shortest distance between all possible pairs of points in a weighted directed graph? Floyd-Warshall (e) Which algorithm can detect negative cycles in a graph? Bellman-Ford 16. Basic properties of some data structures (a) What kind of tree that we studied has this property? any two leaf nodes have same depth. B-tree (b) True or false: If A and B are the left and right children of some node of a heap, then we must have A B. False (c) What kind of tree is used in the implementation of databases? B-trees (d) True or false: in a binary search tree, the height of the tree is logarithmic in the number of nodes. False (e) What is the worst-case running time for the insertion algorithm for binary search trees? O(n). I accepted O(height) also. (f) What is the worst-case running time for the insertion algorithm for red-black trees? O(lg n). I accepted O(height) here too.
17. Graphs and their representations. How would you represent the air transport network of the world by a weighted graph? (a) The nodes would be airports. (b) The edges would be pairs of cities connected by direct flights. It would be a directed graph. (c) The weights would be perhaps the cost per person, or cost per pound, or cost per flight, or for some purposes even hours it takes to fly that route. (d) How could this graph, plus some additional information, be used to run a ticketselling website where you would enter your starting and destination cities, and travel dates, and get the best flights? What algorithms would be used? Dijkstra s algorithm could be used to find the cheapest or shortest path. However, this leaves the element of time out of it. Finding flights that don t leave you stranded in Chicago for two days requires the additional information about when the flights are scheduled. Then, for example, your graph s nodes would be pairs (airport, time), and there would be waiting edges between (x,t) and (x, t2) whenever t < t2. A weight could be assigned to those edges representing the cost of waiting. You don t need all the infinitely many possible times, just the pairs (x,t) when a flight leaves or arrives from x. That still makes a big graph, but not too big for Dijkstra s algorithm. Now you can use Dijkstra directly to do what Hotwire, etc. do.