DUKE UNIVERSITY Department of Computer Science. Test 2: CompSci 100e

Similar documents
DUKE UNIVERSITY Department of Computer Science. Test 2: CompSci 100

DUKE UNIVERSITY Department of Computer Science. Test 1: CompSci 100

Test #2. Login: 2 PROBLEM 1 : (Balance (6points)) Insert the following elements into an AVL tree. Make sure you show the tree before and after each ro

CSE 332 Autumn 2013: Midterm Exam (closed book, closed notes, no calculators)

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

// a stack is printed from bottom (leftmost) to top (rightmost) System.out.println(stk);

EXAMINATIONS 2016 TRIMESTER 2

CSE 332 Spring 2013: Midterm Exam (closed book, closed notes, no calculators)

DUKE UNIVERSITY Department of Computer Science. Test 1: CompSci 100

CS61BL: Data Structures & Programming Methodology Summer 2014

Faculty of Science FINAL EXAMINATION COMP-250 A Introduction to Computer Science School of Computer Science, McGill University

Points off Total off Net Score. CS 314 Final Exam Spring 2016

CSE 332 Winter 2015: Midterm Exam (closed book, closed notes, no calculators)

Compsci 100. Owen Astrachan April 14, 2010

CSE 332 Spring 2014: Midterm Exam (closed book, closed notes, no calculators)

EXAMINATIONS 2017 TRIMESTER 2

Summer Final Exam Review Session August 5, 2009

Abstract Data Types (ADTs) Queues & Priority Queues. Sets. Dictionaries. Stacks 6/15/2011

CompSci 201 Tree Traversals & Heaps

COSC 2007 Data Structures II Final Exam. Part 1: multiple choice (1 mark each, total 30 marks, circle the correct answer)

Course Review. Cpt S 223 Fall 2009

STANDARD ADTS Lecture 17 CS2110 Spring 2013

Points off Total off Net Score. CS 314 Final Exam Spring 2017

Suppose we want to create a data structure called DataStore that has the following operations:

Points off Total off Net Score. CS 314 Final Exam Spring Your Name Your UTEID

CSE 373 Spring 2010: Midterm #1 (closed book, closed notes, NO calculators allowed)

CS61B, Fall 2015 Final Examination (with corrections) P. N. Hilfinger

CSE100. Advanced Data Structures. Lecture 12. (Based on Paul Kube course materials)

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger.

Data Structures Question Bank Multiple Choice

Computer Science E-22 Practice Final Exam

University of Illinois at Urbana-Champaign Department of Computer Science. Final Examination

Friday Four Square! 4:15PM, Outside Gates

References and Homework ABSTRACT DATA TYPES; LISTS & TREES. Abstract Data Type (ADT) 9/24/14. ADT example: Set (bunch of different values)

: Fundamental Data Structures and Algorithms. June 06, 2011 SOLUTIONS

How much space does this routine use in the worst case for a given n? public static void use_space(int n) { int b; int [] A;

CSE 373 Winter 2009: Midterm #1 (closed book, closed notes, NO calculators allowed)

FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 ( Marks: 1 ) - Please choose one The data of the problem is of 2GB and the hard

CS61BL Summer 2013 Midterm 2

CSE 2123: Collections: Priority Queues. Jeremy Morris

COMP Data Structures

CSCE 2014 Final Exam Spring Version A

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

Prelim 2 SOLUTION. 5:30 PM, 25 April Total Question Name Short Search/ Collections Trees Graphs

COMP : Trees. COMP20012 Trees 219

BINARY HEAP cs2420 Introduction to Algorithms and Data Structures Spring 2015

Standard ADTs. Lecture 19 CS2110 Summer 2009

CS 307 Final Spring 2008

CS 455 Midterm Exam 2 Fall 2016 [Bono] November 8, 2016

BRONX COMMUNITY COLLEGE of the City University of New York DEPARTMENT OF MATHEMATICS AND COMPUTER SCIENCE. Sample Final Exam

COMP 103 Introduction to Data Structures and Algorithms

PRACTICE MIDTERM EXAM #2

Final Examination CSE 100 UCSD (Practice)

Course Review. Cpt S 223 Fall 2010

Model Solutions. COMP 103: Test May, 2013

CS 61B Midterm 2 Guerrilla Section Spring 2018 March 17, 2018

CSC 207 (17fa) Practice Final Page 1 of 19. Practice Final

CPSC 331 Term Test #2 March 26, 2007

University of Illinois at Urbana-Champaign Department of Computer Science. Second Examination

CSE 373 Autumn 2010: Midterm #1 (closed book, closed notes, NO calculators allowed)

EXAMINATIONS 2005 END-YEAR. COMP 103 Introduction to Data Structures and Algorithms

CSL 201 Data Structures Mid-Semester Exam minutes

Recitation 9. Prelim Review

Test 2: Compsci 100. Owen Astrachan. November 14, 2006

Prelim 2. CS 2110, November 20, 2014, 7:30 PM Extra Total Question True/False Short Answer

CS 2150 Final Exam, Spring 2018 Page 1 of 10 UVa userid:

PRIORITY QUEUES AND HEAPS

Priority Queues. 04/10/03 Lecture 22 1

Test 2: CPS 100. Owen Astrachan. April 3, Name: Login: (1 pt)

1 P a g e A r y a n C o l l e g e \ B S c _ I T \ C \

Computer Science Foundation Exam

INFO1x05 Tutorial 6. Exercise 1: Heaps and Priority Queues

HEAPS & PRIORITY QUEUES

CS171 Final Practice Exam

CSE100 Practice Final Exam Section C Fall 2015: Dec 10 th, Problem Topic Points Possible Points Earned Grader

חומר עזר לבחינה במבוא למדעי המחשב // Indicates whether some other object is "equal to" // this one. boolean equals(object other)

CS 314 Final Fall 2012

CSE wi: Practice Midterm

CPSC 211, Sections : Data Structures and Implementations, Honors Final Exam May 4, 2001

Test 2: Compsci 100. Owen Astrachan. November 12, 2008

CS106X Handout 39 Autumn 2012 November 28 th, 2012 CS106X Midterm Examination II

NAME: c. (true or false) The median is always stored at the root of a binary search tree.

CSE Data Structures and Introduction to Algorithms... In Java! Instructor: Fei Wang. Mid-Term Exam. CSE2100 DS & Algorithms 1

CSE 373 OCTOBER 11 TH TRAVERSALS AND AVL

Test 2: CPS 100. Owen Astrachan. November 10, 2004

Points off Total off Net Score. CS 314 Final Exam Fall 2016

Review. CSE 143 Java. A Magical Strategy. Hash Function Example. Want to implement Sets of objects Want fast contains( ), add( )

SOLUTIONS. COMP103 Introduction to Data Structures and Algorithms

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

Cpt S 223 Fall Cpt S 223. School of EECS, WSU

Lec 17 April 8. Topics: binary Trees expression trees. (Chapter 5 of text)

PRIORITY QUEUES AND HEAPS

Revision Statement while return growth rate asymptotic notation complexity Compare algorithms Linear search Binary search Preconditions: sorted,

CMSC 341 Lecture 10 Binary Search Trees

CSE 143 Au03 Final Exam Page 1 of 15

COMP 250 Midterm #2 March 11 th 2013

ECE250: Algorithms and Data Structures Midterm Review

CS61B, Fall 2007 Final Examination P. N. Hilfinger

Analysis of Algorithms

Transcription:

DUKE UNIVERSITY Department of Computer Science Test 2: CompSci 100e Name (print): Community Standard acknowledgment (signature): Problem 1 value 14 pts. grade Problem 2 9 pts. Problem 3 10 pts. Problem 4 19 pts. Problem 5 10 pts. Problem 6 8 pts. TOTAL: 70 pts. This test has 13 pages, be sure your test has them all. Do NOT spend too much time on one question remember that this class lasts only 75 minutes and there are 70 points on the exam. That means you should spend no more than 1 minute per point. You may consult your five (5) sheets, your textbooks, and no other resources. You may not use any computers, calculators, or cell phones. You may refer to any program text supplied in lectures or assignments. Don t panic. Just read all the questions carefully to begin with, and first try to answer those parts about which you feel most confident. Do not be alarmed if some of the answers are obvious. If you think there is a syntax error or an ambiguity in a problem s specification, then please ask. In writing code you do not need to worry about specifying the proper import statements. Assume that all libraries and packages we ve discussed are imported in any code you write.

Test 2: CompSci 100e 2 PROBLEM 1 : (Short ones (14 points)) 1. You are creating a boggle word search program and you want to find all valid words where the letters are adjacent. What data structure would be best suited to hold the dictionary (i.e. lexicon)? A. Queue B. Heap C. Trie D. AVL Tree E. Hash Table 2. In order to use the class Point containing fields x and y in a HashSet, you are considering multiple hash functions. Of these hash functions, which one would give the best performance in a HashSet? Assume that your points are likely to be between (0, 0) and (1280, 1024) (the size of the average computer monitor). A. public int hashcode () return super.hashcode(); B. public int hashcode () return 42; C. public int hashcode () return x; D. public int hashcode () return x + y; E. public int hashcode () return x * 3 + y; F. public int hashcode () return x * 1000 + y; 3. True or False State whether the following statement is true or false. If false, you should give a specific counterexample. I. A certain hash table contains N integer keys, all distinct, and each of its buckets contains at most K elements. Collisions are resolved using chaining. Assuming that the hashing function and the equality test require constant time, the time required to find all keys in the hash table that are between L and U is O(K (U L)) in the worst case. II. Instead of using a heap, we use an AVL tree to represent a priority queue. The worst-case big-oh of add (insert) and poll (deletemin) do not change. III. Instead of using a heap, we use a sorted ArrayList to represent a priority queue. The worst-case big-oh of add and poll do not change. IV. Given the preorder and postorder traversals of a binary tree (i.e. printing out all of the elements but not the null nodes), it is possible to reconstruct the original tree. V. Given the preorder and inorder traversals of a binary tree, it is possible to reconstruct the original tree.

Test 2: CompSci 100e 3 PROBLEM 2 : (Reverse (9 points)) Each of the Java functions on the left take a string s as input, and returns its reverse. For each of the following, state the recurrence (if applicable) and give the big-oh complexity bound. Recall that concatenating two strings in Java takes time proportional to the sum of their lengths, and extracting a substring takes constant time. A. public static String reverse1(string s) int N = s.length(); String reverse = "; for (int i = 0; i < N; i++) reverse = s.charat(i) + reverse; return reverse; B. public static String reverse2(string s) int N = s.length(); if (N <= 1) return s; String left = s.substring(0, N/2); String right = s.substring(n/2, N); return reverse2(right) + reverse2(left); C. public static String reverse3(string s) int N = s.length(); char[] a = new char[n]; for (int i = 0; i < N; i++) a[i] = s.charat(n-i-1); return new String(a);

Test 2: CompSci 100e 4 PROBLEM 3 : (Bits (10 points)) You would like to implement the set operations for the integers 0-31 using a BitSet class. The ith bit is a 1 if and only if i is in the set. For example, 00000000000000000000000000000000 indicates that there are no elements in the set. 10000000000000000000000000001010 indicates that 1, 3, and 31 are in the set. The second set can be created with the following client code: BitSet s = new BitSet(); s.set(1, true); s.set(3, true); s.set(31, true); Below, we have given the constructor and the set method for BitSet. public class BitSet private int mybits; private final static int BITS_PER_INT = 32; public class BitSet(int bits) // set all bits to 0 mybits = 0; * Sets the bit at the specified index to the specified value. * @param bitindex a bit index that should be between 0 and 31 * @param value a boolean value to set. public void set(int bitindex, boolean value) if (bitindex < 0 bitindex >= BITS_PER_INT) // out of bounds return; if (value) // mybits = mybits (1 << bitindex); // set bit to on else mybits = mybits & ~(1 << bitindex); // set bit to off

Test 2: CompSci 100e 5 A. Complete the get method. In the above example s.get(3) should return true while s.get(7) should return false. * Returns the value of the bit with the specified index. The value * is true if the bit with the index bitindex is currently set in * this BitSet; otherwise, the result is false. * * @param bitindex the bit index. * @return the value of the bit with the specified index. public boolean get(int bitindex) // TODO: Complete get B. You would like to implement the union operation for the BitSet class. The union operation ( ) says that if A = (1, 2, 3, 4, 5) and B = (1, 3, 5, 7, 9), then A B = (1, 2, 3, 4, 5, 7, 9). Write the method union below. * Performs a union of this bit set with the bit set argument. This bit set is modified so that * a bit in it has the value true if and only if it either already had the * value true or the corresponding bit in the bit set argument has the value true. * * @param set a bit set. public void union(bitset set)

Test 2: CompSci 100e 6 PROBLEM 4 : (Huffman Trees (19 points)) The Huffman compression algorithm uses a tree to encode the codewords, where each node has either two or zero children. Someone has given you a tree that contains some nodes with only one child. A. Why can such a tree not be created using the Huffman encoding algorithm discussed in class? B. Write a function called tighten that given such an encoding tree will remove those nodes with one child. The diagram below shows a loose tree on the left and its tightened equivalent on the right. The three shaded nodes are the ones that were removed. The definition of a Huffman TreeNode is attached to the end of the test. * remove nodes with one child from Huffman tree * @param root is the root of a Huffman tree (may be null) * @return tree where nodes with one child are removed public static TreeNode tighten(treenode root)

Test 2: CompSci 100e 7 C. State the recurrence and the big-oh for your solution. D. You would like to check to make sure the character counts in the tree sum up correctly. That is the the weight field of a node should equal the sum of the weights of its children. Write validweights that checks to see if each node is the sum of its children. * * @return true iff each internal node s weights is the sum of its * children s weights public static boolean validweights(treenode root)

else else for (int i = 0 i < rest.length(); for (int i = i++) 0 i < rest.length(); i++) string remaining = rest.substr(0, string remaining i) + = rest.substr(i+1); rest.substr(0, i) + rest.substr(i+1 Permute(soFar + rest[i], Permute(soFar remaining); + rest[i], remaining); Test 2: CompSci 100e 8 PROBLEM 5 : (Puzzle Hunt) Problem 4: Pascal s Travels Problem 4: Pascal s Travels You You re are given given a matrix a grid of positive of positive integers to integers represent to arepresent game board, a where game the board, (0, 0) entry where is the theupper left corner. The number in each location is the number of squares you can advance in any of the four primary compass directions, provided [0, 0] that entry move is does the upper not takeleft youcorner. off the board. The number You are interested in each location in the total is the number number of distinct of ways one couldsquares travel from you thecan upper advance left corner in any to theof lower the right four corner, primary given compass the constraint directions, that no single provided path should that ever visit the same location twice. You re given a grid of positive integers to represent a game board, where [0, 0] entry is the upper left corner. The number in each location is the nu squares you can advance in any of the four primary compass directions, p move doesn t take you off move the board. doesn t You re take you interested off the board. in the total You re number interested of distinct in the total numb Consider ways the one initial could gametravel board to from ways the left, the one and upper could notice left that travel corner thefrom upper to the leftlower corner upper is right left occupied corner, by to a given 2. the That lower the means right you corner can take constraint either two that steps no tosingle the right, constraint path or should two 6 steps that ever down no visit single (but the not path two same steps should location to the ever left twice. visit or above, the same because location that would twice. carry you off the board). Suppose you opt to go right so that you find yourself in the configuration to the right. along as follows: 3 Consider 4 the initial game Consider board to the initial left, and game board to the left, and. notice. that the upper left notice corner that is occupied the upper by left a corner is occupied by a 2. That means you can take 2. That either means two steps you can to take either two steps to the right, or two steps down the right, (but not or two steps down (but not two steps to the left or above, because to the that left would or above, carrybecause that would carry you off the board). Suppose you off you the opt board). to go right Suppose you opt to go right 6 so that you find yourself so in that the configuration you find yourself to in the configuration to 6 the right. the right. From there, you could continue along as follows: After 41 that, you could continue 5along 2 as follows: 3 4..... s just one of potentially several r left to lower right. Your job here aths, which takes a Grid of number of ways to travel to the Note that you never want to o paths are considered to be on sub-path. And because you ld change the 5value at any given 6 5 rking that you ve. been there. Just.. lue several as you exit the So, recursive this series call. of moves illustrates just one of potentially several r nction job here and some paths utility you functions could take from upper left to lower right. Your job here d or of not. is to write a function called NumPaths, which takes a Grid of l to the integers and computes the total number of ways to travel to the ard) nt to lower right corner of the board. Note that you never want to to be count the same path twice, but two paths are considered to be use you distinct even if they share a common sub-path. And because you ny given 6 want to prevent cycles, you should change the value at any given 6 This series of moves illustrates just one of potentially several paths you could take from upper left to lower right. there. Just. Yourlocation task is to to write a zero a method as a way calledof numpaths, marking which that takes you ve a 2-dbeen array there. of integers Just and computes. the total number sive call. of ways be sure to travel to restore the lower the right original cornervalue of the as board. you Note exit that the you recursive never want call. to count the same path twice, but functions two paths are considered to be distinct even if they share a common sub-path. And because you want to prevent cycles, You ll you should want change to write thea value wrapper at any function given location and tosome a zeroutility as a way functions of marking that you ve been there. Just be sure to decide to restore it the you re original on value the board as you exit or not. the recursive call. You may want to write a helper function to handle the recursion and a utility function to decide it you are on the board or not. int NumPaths(Grid<int>& board)

Test 2: CompSci 100e 9 A. Write numpaths below. * Calculates total number of distinct ways one could travel from the * upper left corner of grid to the lower right corner, given the * constraint that no single path should ever visit the same location twice. * * @param board square matrix board[i][j] is the number of squares * one can advance vertically or horizonatally from (i,j) * * @return the number of possible paths from (0,0) to the lower * right corner of board (board.length-1, board[0].length - 1) public static int numpaths(int[][] board) // HELPER FUNCTIONS * @return true if (row,col) is within the bounds of the board * (i.e. 0 <= row < board.length and 0 <= col < board[0].length) * false otherwise public static boolean onboard(int[][] board, int row, int col) * @return the number of possible paths from (row,col) to the lower * right corner of board (board.length-1, board[0].length - 1) public static int numpaths(int[][] board, int row, int col)

Test 2: CompSci 100e 10 B. Give a recurrence for your solution. You do not need to solve the recurrence.

Test 2: CompSci 100e 11 PROBLEM 6 : (Tradeoffs (8 points)) You are given an array of n ints (where n is very large) and are asked to find the largest m of them (where m is much less than n). A. Design an efficient algorithm to find the largest m elements. YOu do not need to write your solution in Java. Precise English or pseudocode will suffice. You can assume the existence of all data structures we discussed in class. You do not have to explain how any of the standard methods (e.g. constructing a heap) work. Be specific, however, about which data structures you are using and how these data structures are interconnected. Your algorithm should work well for all values of m and n, from very small to very large. B. What is the running time of your algorithm? What is it for small m? What is it as m n (i.e. as m approaches n)?

Test 2: CompSci 100e 12 Throughout this test, assume that the following classes and methods are available. These classes are taken directly from the material used in class. There should be no methods you have never seen before here. Definitions Some common recurrences and their solutions. List Node T(n) = T(n/2) + O(1) O(log n) T(n) = T(n/2) + O(n) O(n) T(n) = 2T(n/2) + O(1) O(n) T(n) = 2T(n/2) + O(n) O(n log n) T(n) = T(n-1) + O(1) O(n) T(n) = T(n-1) + O(n) O(n 2 ) public class Node String info; Node next; Node(String s, Node link) info = s; next = link; Node for Binary Trees public class TreeNode String info; TreeNode left; TreeNode right; TreeNode parent; String TreeNode (String s, TreeNode lt, TreeNode rt) TreeNode p) info = s; left = lt; right = rt; parent = p; public class String /* Compares this string to the specified object. * The result is true if and only if the argument * is not null and is a String object that * represents the same sequence of characters public boolean equals(object anobject) /* Returns the index within this string of the * first occurrence of the specified substring. * -1 if it does not exist public int indexof(string str) /* Returns the length of this string. int length() /* Returns a new string that is a substring of this string. Begins at the specified beginindex and extends to the character at index endindex - 1 String substring(int beginindex, int endindex) TreeSet/HashSet public class TreeSet // Constructs a new, empty set public TreeSet() // Returns an iterator over the elements in // this set. The elements are visited in // ascending order. public Iterator iterator() // Returns the number of elements in this set. public int size() // Returns true if this set contains o public boolean contains(object o) // Adds the specified element to this set // if it is not already present. public boolean add(object o) Queue public class Queue /* A new element <code>o</code> is added to the queue public boolean add(object o) /* retrieves and removes head of queue public Object remove() // Retrieves, but does not remove, the head of this queue, or r public Object peeky() Stack public class Stack /* Pushes an item onto the top of this stack. public Object push(object o) /* Removes the object at the top of this stack and returns that o public Object pop() /* Tests if this stack is empty public boolean empty() PriorityQueue public class PriorityQueue // Constructs an empty Priority Queue public PriorityQueue() // Inserts the specified element into // this priority queue. public boolean add(object o) // Retrieves, but does not remove the head of this queue public Object peek() // Retrieves and removes the head of this queue public Object poll() // Returns the number of elements public int size()