









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
The final exam for the CS61B: Data Structures course at UC Berkeley in Spring 2017. The exam consists of 13 questions worth a total of 200 points and is to be completed in 165 minutes. The exam is closed book, except for three double-sided written cheat sheets. The first question is worth 0.5 points and requires students to write their name and ID on the front page, write the exam room, check the IDs of their neighbors, write the given statement, sign, and write their login in the corner of every page. The remaining questions cover topics such as Kruskal's and Prim's algorithms, shortest paths, and data structures.
Typology: Exams
1 / 16
This page cannot be seen from the preview
Don't miss anything!










Optional. Mark along the line to show your feelings Before exam: [L____________________J]. on the spectrum between L and J. After exam: [L____________________J]. UC Berkeley – Computer Science CS61B: Data Structures Final Exam, Spring 2017. This test has 13 questions worth a total of 200 points, and is to be completed in 165 minutes. The exam is closed book, except that you are allowed to use three double sided written cheat sheets (front and back). No calculators or other electronic devices are permitted. Give your answers and show your work in the space provided. Write the statement out below in the blank provided and sign. You may do this before the exam begins. “I have neither given nor received any assistance in the taking of this exam.” Signature: ___________________________
0 0.5 7 23 1 12 8 0 2 28 9 16 3 14 10 16 4 12 11 12 5 16 12 12 6 12 13 26. TOTAL 200 Name: __________________________ SID: ___________________________ Three-letter Login ID: _________ Left SID: ______________________ My left neighbor has ID: _______ Right SID: _____________________ My right neighbor has ID: ______ Exam Room: _____________________ Tips:
UC BERKELEY Login: _________
0. So it begins (0. 5 points). Write your name and ID on the front page. Write the exam room. Check the IDs of your neighbors. Write the given statement. Sign. Write your login in the corner of every page. Enjoy your free 0. 5 points J. 1. Mystery Spanning Tree 3000 ( 12 points). a) ( 4 pts) For the graph below, list the edges in the order they’re added to the MST by Kruskal’s and Prim’s algorithm. Assume Prim’s algorithm starts from vertex A. Assume ties are broken in alphabetical order (i.e. the edge 𝐴𝐵 would be considered before 𝐴𝐶 ). Denote each edge with alphabetical overbar notation 𝐴𝐵, which represents the edge from A to B. You may not need all blanks. For your convenience, the graph is printed twice (to make running algorithms easier). Prim’s algorithm order: _____ _____ _____ _____ _____ _____ _____ _____ _____ Kruskal’s algorithm order: _____ _____ _____ _____ _____ _____ _____ _____ _____ b) (2 pts) Is there any vertex for which the shortest paths tree (SPT) is the same as your Prim MST above? ○ Yes, and it’s _________ ○ No c) ( 6 pts) For the following propositions, fill in true or false completely and provide a brief explanation. For a proposition that is false, a counter-example suffices. Assume all edge weights are unique. ○ True / ○ False: Adding 1 to the smallest edge across any cut of a graph G must change the total weight of its minimum spanning tree. ○ True / ○ False: The shortest path from vertex A to vertex B in a graph G is the same as the shortest path from A to B using only edges in T, where T is the MST of G. ○ True / ○ False: Given any cut, the maximum-weight crossing edge is in the maximum spanning tree.
UC BERKELEY Login: _________ 3. Traversals (1 4 points). Suppose we have an NAryIntTree, defined as shown below. Any node may have any number of children. If a node is a leaf, children is null. Assume that children[i] is never null for any i. a) (6 pts) Fill in the printTreePostOrder method below, which prints the values of the tree in postorder, with one val per line. Your solution must be recursive and take linear time in the number of nodes. public class NAryIntTree { private Node root; public class Node { public Node[] children; public int val; } public void printTreePostOrder() {
} public ________________________________________________ {
} /* ... */ } b) (8 pts) Fill in the code below which prints out the values of the tree in level order with one val per line. Your solution must be iterative and take linear time in the number of nodes for any tree. private void printTreeLevelOrder() { // is a method of NAryIntTree
}
Login: _______ 4. Algorithms and Data Structures (1 2 points). a) (4 pts) In class we primarily considered two graph representations: the adjacency list and the adjacency matrix. Antares suggests that we can improve the performance of Dijkstra’s algorithm with a third graph representation he calls an “adjacency heap”. For each vertex v, v’s adjacency heap stores all of v’s neighbors in a heap ordered by edge weight, so that the smallest edge adjacent to v is at the root of its heap. Naturally, Antares stores these heaps as arrays. Antares reasons that by considering small edges first, Dijkstra’s will be able to complete faster. Will using an adjacency heap result in better, equivalent, or worse asymptotic runtime performance for Dijkstra’s algorithm than using a regular adjacency list? Assume that we only care about worst case asymptotic performance. Briefly justify your answer. ○Adjacency heap is better ○ Performance is the same ○ Adjacency heap is worse Justification: _________________________________________________________ b) ( 4 pts) Suppose Antares has conjured up the Gulgate Priority Queue (GPQ). Given a GPQ containing N elements, the worst-case running time for insertion, deletion, and change-priority are given as follows: Insertion: 𝛩(𝑁), Deletion: 𝛩(𝑁), Change-Priority: 𝛩( 1 ). Suppose we run the implementation of Dijkstra's algorithm provided in class (where every vertex is initially inserted into the PQ with infinite priority) using a GPQ on a graph with V vertices and E edges. What is the worst case runtime of Dijkstra’s? Give your answer in big O notation in terms of V and E. Assume that E >> V (this means E is much greater than V). Runtime: O(_______________________________) c) ( 4 pts) Suppose Antares has also created a Xelha Quick Union (XQU) to check if two vertices are connected while running Kruskal’s. Given that there are N items in an XQU, the running time for XQU operations is as follows: Constructor: 𝛩(𝑁), Union: 𝛩(𝑁 log 𝑁), Is-Connected: 𝛩(log 𝑁) Suppose we run the implementation of Kruskal’s algorithm as presented in class using a XQU and a heap-based priority queue. Recall that in our version of Kruskal’s from class, all edges are initially inserted into a regular heap-based priority queue and removed one by one, and added to the MST so long as there are no cycles. What is the worst case runtime of Kruskal’s algorithm? Give your answer in big O notation in terms of V and E. Assume that E >> V. Runtime: O(______________________________)
Login: _______
UC BERKELEY Login: _________ 7. Arithmetic Tree ( 23 pts). An arithmetic tree is a tree that stores an arithmetic expression. For this problem, assume all nodes are either multiplication (represented with ⨉), addition (represented with +), or a number (represented as a written integer). For example, the following tree represents (1 ⨉ 5 ⨉ (2 + 2)) + (3 + - 1) + (3 ⨉ - 5 ⨉ 1 ), which would evaluate to 7. Your job is to fill out the code below such that evaluateTree(Node tree) evaluates the arithmetic tree rooted at tree to its correct value. For example, if evaluateTree were applied to the ⨉ node at the top left of the figure above, it would return 2 0. Multiplication and addition operator nodes can have any number of children. You do not need to check for bad inputs (e.g. null children). You may find it easier to work your way from the end of the problem back to the front. You may not need all blanks. public abstract class Node { public List children; public abstract void processNode(Stack stk); } public class ArithmeticTreeEvaluator { public static int evaluateTree(Node tree) { Stack stk = new Stack<>(); __________________________________________________________________; __________________________________________________________________; } private static void evaluateTreeHelper(Node tree, Stack stk) { for (___________________________________________________________) { evaluateTreeHelper(_____________________); } __________________________________________________________________; } }
UC BERKELEY Login: _________
9. Asymptotics (16 points). For each of the code snippets below, give the best and worst case runtimes in terms of N. Give the best runtimes in the column to the left , and the worst in the column to the right. Best: _Θ_____ Worst: _Θ_____ public static void f1(int N) { if (N == 0) { return; } f1(N / 2); f1(N / 2); g(N); // runs in Θ(N 2 ) time } _Θ_____ _Θ_____ public static int f2(String[] x, int i) { int N = x.length; int total = 0; try { while (i < N) { total += x[i].length(); i += 1; } } catch(NullPointerException e) { x[i] = "null"; f2(x, i); } return total; } _Θ_____ _Θ_____ Assume t is a binary IntTree with N nodes: public static void f3(IntTree t) { t.value = t.value * 2; if (t.left != null) { f3(t.left); } if (t.right != null) { f3(t.right); } } _Θ_____ _Θ_____ Assume t is a binary IntTree with N nodes: public static void f4(IntTree t) { t.value = t.value * 2; if (t.left != null) { f4(t.left); } t.right = t.left; if (t.right != null) { f4(t.right); } t.left = t.right; }
Login: _______ 10. Return of the XelhaTree (1 6 points). Write a function validXelhaTree which takes an IntTree and a List and returns true if the IntTree is a XelhaTree for the list. You may not need all lines. A XelhaTree is valid if it obeys the min heap property, and if an in-order traversal of the XelhaTree yields the list of items passed to createXelhaTree (in the same order). One line if statements with {} on the same line are fine. You may not need all the blanks. Assume there are no duplicates. public class XelhaTreeTest { public static class IntTree { public int item; public IntTree left, right; } public static IntTree createXelhaTree(List x) { ... } /** If x is null, returns largest possible integer 2147483647 */ private static int getItem(IntTree x) { if (x == null) { return Integer.MAX_VALUE; } return x.item; } public static boolean isAHeap(IntTree xt) {
_________________________________________________________ } public static void getTreeValues(IntTree xt, List treeValues){
_________________________________________________________ } public static boolean validXelhaTree(IntTree xt, List vals) { List treeValues = new ArrayList(); /* getTreeValues adds all values in xt to treeValues */ getTreeValues(xt, treeValues);
return isAHeap(xt) && ___________________________________ }
Login: _______ 12. Danger and Optimization (12 points). a) (5 pts) Suppose you provide a computing service where users can upload lists of integers and receive back the numbers in sorted order. Which sorts below would be appropriate to choose for this task, assuming you want to prevent users from submitting inputs that either result in terrible^2 runtime or cause an exception? Assume you are using Java. ○ Appropriate / ○ Inappropriate : Merge Sort ○ Appropriate / ○ Inappropriate : Insertion Sort ○ Appropriate / ○ Inappropriate : Quicksort using Hoare partitioning and that starts by shuffling ○ Appropriate / ○ Inappropriate : LSD ○ Appropriate / ○ Inappropriate : Recursive MSD b) (5 pts) Suppose you provide a service where users can upload a list of names (stored as Java Strings) and it will return the list of all unique Strings. Which set implementations below would be appropriate to choose for this task, assuming you want to prevent users from submitting inputs that either result in terrible runtime or cause an exception? ○ Appropriate / ○ Inappropriate : 2-3 Tree based Set ○ Appropriate / ○ Inappropriate : LLRB based Set ○ Appropriate / ○ Inappropriate : Hash based Set ○ Appropriate / ○ Inappropriate : Trie based Set ○ Appropriate / ○ Inappropriate : TST based Set c) (2 pts) Suppose you provide a service where users can upload their own custom graphs and a start vertex, and you will find the list of all vertices reachable from the start. Which graph search algorithms would be appropriate to choose for this task, assuming you want to prevent users from submitting inputs that either result in terrible runtime or cause an exception? ○ Appropriate / ○ Inappropriate : Recursive DFS ○ Appropriate / ○ Inappropriate : BFS d) (0 pts) What should Josh name his future kid (assume female if you want a gender specific name)? (^2) By terrible we mean: Imagine you are demoing your website and want to impress someone with its speed. Does it run so slow that you are embarrassed? If so, that is terrible.
UC BERKELEY Login: _________ 13. Reductions ( 26 .5 points). Often in computer science, problems are just other problems in disguise. Complete each problem below according to the directions given. Many of these problems are very challenging. a) ( 3 pts) Describe an algorithm to find a maximum spanning tree. Your algorithm must use Kruskal's as a "black box," that is, without any modifications. Your answer should be brief. b) ( 5 pts) Suppose you want to find the SPT of a graph, but where you redefine the total cost of a path as follows. Let cost(List) be the sum of the weights of the edges, plus the number of edges. In other words, we want to run Dijkstra’s taking into account not just the weights of the edges, but also the number of edges. Describe an algorithm to find this shortest paths tree. Your algorithm must use Dijkstra’s as a “black box”. Your answer should be brief. c) ( 5 pts) Dijkstra’s algorithm sometimes fails on graphs with negative edges. Suppose we have a graph G with a single negative edge with weight - Q, and we want to find the shortest path. Suppose we construct a new graph G’ where every edge has Q added to its weight. If we run Dijkstra’s on G’, does the resulting shortest path tree always give the correct shortest paths for G? If yes, explain why. If no, provide a counter-example. ○ Yes, because: ○ No, counter-example: d) (6 pts) Suppose that we’re using a programming language Zulg where instead of comparison we have a zelch operation. Suppose that we prove that “puppy, cat, dog”^3 , requires 𝛺(𝑁 log log 𝑁) zelch operations. Assume that zelch takes constant time. For each of the following statements, determine whether the answer is false, true, or the answer depends on whether P = NP. ○ True / ○ False / ○ P=NP?: A zelch based sort requires at least 𝛺(𝑁 log log 𝑁) zelch operations. ○ True / ○ False / ○ P=NP?: Sorting an array in Zulg requires 𝛩(𝑁 log log 𝑁) time in the worst case. ○ True / ○ False / ○ P=NP?: The optimal sorting algorithm in Zulg requires 𝑂(𝑁 log log 𝑁) time in the worst case. ○ True / ○ False / ○ P=NP?: All sorting algorithms in Zulg require 𝑂(𝑁 log log 𝑁) time in the worst case. (^3) Recall that “puppy, cat, dog” is a game from lecture where we have N boxes, each containing a unique object (e.g. a puppy, a cat, and a dog) of known size, and our job is to determine which box contains which object.
UC BERKELEY Login: _________ Nothing written on this page will be graded. Data Structures Reference: HashSet { void add(Key k) boolean contains(Key k) } HashSet is the same except Key must implement Comparable MinPQ> { MinPQ(Comparator c) void insert(Item x) Item min() Item delMin() } Uses natural order unless comparator given during construction. HashMap { void put(Key k, Value v) boolean containsKey(Key k) Value get(k) } TreeMap is the same except Key must implement Comparable Stack { void push(Item x) Item pop() } Queue { void enqueue(Item x) Item dequeue() } Assume all of these classes implement Iterable and have a size() method.