CS211 Spring 2005 Final Exam May 17, 2005. Solutions. Instructions



Similar documents
Data Structure [Question Bank]

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

ECE 250 Data Structures and Algorithms MIDTERM EXAMINATION /5:15-6:45 REC-200, EVI-350, RCH-106, HH-139

Converting a Number from Decimal to Binary

Exam study sheet for CS2711. List of topics

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

Data Structures and Algorithms Written Examination

root node level: internal node edge leaf node Data Structures & Algorithms McQuain

CSE 326, Data Structures. Sample Final Exam. Problem Max Points Score 1 14 (2x7) 2 18 (3x6) Total 92.

Ordered Lists and Binary Trees

DATA STRUCTURES USING C

Binary Search Trees CMPSC 122

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

Java Software Structures

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

From Last Time: Remove (Delete) Operation

TREE BASIC TERMINOLOGIES

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Learning Outcomes. COMP202 Complexity of Algorithms. Binary Search Trees and Other Search Trees

Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010

Data Structures and Algorithms

3. Mathematical Induction

Analysis of a Search Algorithm

2. (a) Explain the strassen s matrix multiplication. (b) Write deletion algorithm, of Binary search tree. [8+8]

PES Institute of Technology-BSC QUESTION BANK

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push)

Sorting revisited. Build the binary search tree: O(n^2) Traverse the binary tree: O(n) Total: O(n^2) + O(n) = O(n^2)

Outline BST Operations Worst case Average case Balancing AVL Red-black B-trees. Binary Search Trees. Lecturer: Georgy Gimel farb

Sequential Data Structures

Lecture Notes on Binary Search Trees

Data Structures, Practice Homework 3, with Solutions (not to be handed in)

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

Binary Heap Algorithms

To My Parents -Laxmi and Modaiah. To My Family Members. To My Friends. To IIT Bombay. To All Hard Workers

Persistent Binary Search Trees

A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Home Page. Data Structures. Title Page. Page 1 of 24. Go Back. Full Screen. Close. Quit

Binary Trees and Huffman Encoding Binary Search Trees

recursion, O(n), linked lists 6/14

Analysis of Binary Search algorithm and Selection Sort algorithm

- Easy to insert & delete in O(1) time - Don t need to estimate total memory needed. - Hard to search in less than O(n) time

Binary Search Trees (BST)

Chapter 14 The Binary Search Tree

Lecture Notes on Binary Search Trees

Binary Search Trees. A Generic Tree. Binary Trees. Nodes in a binary search tree ( B-S-T) are of the form. P parent. Key. Satellite data L R

Big O and Limits Abstract Data Types Data Structure Grand Tour.

5. A full binary tree with n leaves contains [A] n nodes. [B] log n 2 nodes. [C] 2n 1 nodes. [D] n 2 nodes.

A binary search tree is a binary tree with a special property called the BST-property, which is given as follows:

Mathematical Induction. Lecture 10-11

CompSci-61B, Data Structures Final Exam

Binary Heaps * * * * * * * / / \ / \ / \ / \ / \ * * * * * * * * * * * / / \ / \ / / \ / \ * * * * * * * * * *

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

CSC148 Lecture 8. Algorithm Analysis Binary Search Sorting

Full and Complete Binary Trees

Algorithms and Data Structures

Introduction to Algorithms March 10, 2004 Massachusetts Institute of Technology Professors Erik Demaine and Shafi Goldwasser Quiz 1.

Class Notes CS Creating and Using a Huffman Code. Ref: Weiss, page 433

Linked Lists, Stacks, Queues, Deques. It s time for a chainge!

Node-Based Structures Linked Lists: Implementation

Efficiency of algorithms. Algorithms. Efficiency of algorithms. Binary search and linear search. Best, worst and average case.

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Sample Questions Csci 1112 A. Bellaachia

Symbol Tables. Introduction

Binary Search Trees. Data in each node. Larger than the data in its left child Smaller than the data in its right child

10CS35: Data Structures Using C

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Algorithms and Data Structures Written Exam Proposed SOLUTION

Algorithm Homework and Test Problems

International Journal of Software and Web Sciences (IJSWS)

The ADT Binary Search Tree

CS711008Z Algorithm Design and Analysis

Sorting Algorithms. Nelson Padua-Perez Bill Pugh. Department of Computer Science University of Maryland, College Park

6 March Array Implementation of Binary Trees

Data Structures. Level 6 C Module Descriptor

Why Use Binary Trees?

Near Optimal Solutions

Heaps & Priority Queues in the C++ STL 2-3 Trees

Lecture Notes on Linear Search

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Linked Lists Linked Lists, Queues, and Stacks

COMPSCI 105 S2 C - Assignment 2 Due date: Friday, 23 rd October 7pm

Connectivity and cuts

AP Computer Science Java Subset

Algorithms and data structures

The Union-Find Problem Kruskal s algorithm for finding an MST presented us with a problem in data-structure design. As we looked at each edge,

Why? A central concept in Computer Science. Algorithms are ubiquitous.

B-Trees. Algorithms and data structures for external memory as opposed to the main memory B-Trees. B -trees

Binary search algorithm

Catalan Numbers. Thomas A. Dowling, Department of Mathematics, Ohio State Uni- versity.

Introduction to Data Structures and Algorithms

A binary heap is a complete binary tree, where each node has a higher priority than its children. This is called heap-order property

Output: struct treenode{ int data; struct treenode *left, *right; } struct treenode *tree_ptr;

The following themes form the major topics of this chapter: The terms and concepts related to trees (Section 5.2).

Previous Lectures. B-Trees. External storage. Two types of memory. B-trees. Main principles

Data Structures Fibonacci Heaps, Amortized Analysis

Mathematical Induction

Recursion. Slides. Programming in C++ Computer Science Dept Va Tech Aug., Barnette ND, McQuain WD

Data Structure with C

LINKED DATA STRUCTURES

Transcription:

CS11 Spring 005 Final Exam May 17, 005 Solutions Instructions Write your name and Cornell netid above. There are 15 questions on 1 numbered pages. Check now that you have all the pages. Write your answers in the boxes provided. Use the back of the pages for workspace. Ambiguous answers will be considered incorrect. The exam is closed book and closed notes. Do not begin until instructed. You have 1 hours. Good luck! 1 3 4 5 6 7 8 Score Grader /5 /4 /4 /7 /0 /4 /4 /10 9 10 11 1 13 14 15 Σ Score Grader /6 /6 /5 /5 /10 /6 /4 /100

May 17, 005 CS11 Final Exam Page 1 of 1 1. (5 points) Consider a sorted circular doubly-linked list where the head element points to the smallest element in the list. (a) What is the asymptoptic complexity of finding the smallest element in the list? O(1) (b) What is the asymptoptic complexity of finding the largest element in the list? O(1) (c) What is the asymptoptic complexity of determining whether a given element e appears in the list? O(n) (d) What is the asymptotic complexity of finding the median element in the list? O(n) (e) What is the asymptotic complexity of deleting a given element e in the list (not including the cost of finding it)? O(1)

May 17, 005 CS11 Final Exam Page of 1. (4 points) Check the ADT or data structure that is most appropriate for each of the following problems: (a) You want to build an address book with entries in alphabetical order by last name. Unsorted List Sorted List Stack x Balanced Search Tree Directed Graph (b) You want to build a meeting reminder for a PDA that keeps track of events you schedule and periodically checks the next event to sound an alarm to remind you of the next thing you need to do. List Hashtable Stack Queue x Priority Queue (c) You want to build a table of contents for a textbook. The textbook consists of chapters, chapters consist of sections, and sections consist of subsections. List Hashtable x Tree Binary Tree Balanced Tree (d) You want to build an email address miner that scans a hard drive looking for email addresses, then sends them to a remote host. List Hashtable x HashSet Array Balanced Tree

May 17, 005 CS11 Final Exam Page 3 of 1 3. (4 points) Suppose we wish to compute x n for integer values of n. We can do this recursively as follows: if n = 0, return 1 if n = 1, return x if n > 1 and n is even, recursively compute y = x n/ and return y y if n > 1 and n is odd, recursively compute y = x n 1 and return x y. Assuming addition and multiplication are O(1) operations, what is the worst-case asymptotic complexity of computing x n this way? O(log n) 4. (7 points) Prove that for odd n 1, n ( 1) i+1 i = 1 + 3 4 + 5 + n = i=1 n(n + 1). By induction on n. Basis n = 1: 1 i=1 ( 1)i+1 i = ( 1) 1+1 1 = 1 = 1(1+1). Induction step n 3, n odd: Using strong induction, we would like to show that the theorem is true for n, assuming it is true for all odd m < n. In particular, assume it is true for n. Then ( n n ) ( 1) i+1 i = ( 1) i+1 i + ( 1) n 1+1 (n 1) + ( 1) n+1 n i=1 = = i=1 (n )(n 1) n(n + 1) splitting off the last two terms + ( 1) n 1+1 (n 1) + ( 1) n+1 n by the induction hypothesis by elementary algebra. We conclude by the strong induction principle that n i=1 ( 1)i+1 i = n(n+1).

May 17, 005 CS11 Final Exam Page 4 of 1 5. (0 points) True or false? (a) T F The AVL invariant states that a tree s shortest and longest paths differ in length by at most 1. (b) T F The rotate operation on AVL trees preserves inorder numbering. (c) T F Abstract classes can be instantiated like any other class. (d) T F A stack is a FIFO structure and a queue is a LIFO structure. (e) T F If class A implements interface I, class B extends A, and class C extends B, then C implements I. (f) T F If class A implements interface I, class B extends A, class C extends B, and interface J extends interface I, then C implements J. (g) T F 3 n is O( n ). (h) T F log(3 n ) is O(log( n )). (i) T F log 3 n is O(log n). (j) T F log(n ) is O(log(n 3 )). (k) T F The optimal number of collisions per bucket in a hashtable is 1. (l) T F If f(n) is O(g(n)) and g(n) is O(h(n)), then f(n) is O(h(n)). (m) T F An occurrence of this in a static method will cause a compile-time error. (n) T F Binary search is as efficient on linked lists as on arrays, provided the list is doubly linked. (o) T F The finally block in a try-catch-finally statement is executed even if no exception is thrown and there is a return statement in the try block. (p) T F A non-abstract subclass of an abstract class C must provide definitions for all the abstract methods of C. (q) T F Downcasting is always legal and can be done without an explicit cast. (r) T F Every dag has a unique topological sort. (s) T F In the worst case, search in an unbalanced binary tree is asymptotically the same complexity as search in a balanced binary tree. (t) T F An ActionListener registered with a JMenuItem is executed automatically whenever that JMenuItem is selected.

May 17, 005 CS11 Final Exam Page 5 of 1 6. (4 points) Recall that in a binary tree, a node may have 0, 1, or children. In the following questions about binary trees, the height of a tree is the length (number of edges) of the longest path. A tree consisting of just one node has height 0. (a) What is the maximum number of nodes in a binary tree of height d? d+1 1 (b) What is the minimum number of nodes in a binary tree of height d? d + 1 (c) What is the maximum height of a binary tree containing n nodes? n 1 (d) What is the minimum height of a binary tree containing n nodes? log n 7. (4 points) Using a witness pair, prove that log(n + 4) is O(log n). (Hint. Try and 7.) We show that for all n 7, log(n + 4) log n = log n. Since log is a monotone operation (preserves the inequality ), it suffices to show that for all n 7, n + 4 n, or equivalently, 4 n n = n(n 1). But equality holds for n = 7, so the inequality certainly holds for all larger values of n.

May 17, 005 CS11 Final Exam Page 6 of 1 8. (10 points) Write a recursive delete method for singly-linked lists with integer data that deletes the first occurrence of a given integer from the list and returns the resulting list. class ListNode { private int value; //data value public ListNode next; //next element of list, or null if last public ListNode(int v) { value = v; public int value() { return value; //delete first occurrence of i in list s static ListNode delete(int i, ListNode s) { if (s == null) return s; if (s.value() == i) return s.next; s.next = delete(i, s.next); return s; 9. (6 points) List the sequence of nodes visited by preorder, inorder, and postorder traversals of the following tree: A B C D E F G H I J (a) preorder: ABDGEHICFJ (b) inorder: GDBHEIACJF (c) postorder: GDHIEBJFCA

May 17, 005 CS11 Final Exam Page 7 of 1 10. (6 points) Consider the following directed graph. B E H A C D F G I J (a) List the nodes in the order they would be visited in a depth-first search of the graph starting at A. When choosing a node to explore next, break ties in favor of the alphabetically least. ABDEGHJIFC (b) List the nodes in the order they would be visited in a breadth-first search of the graph starting at A. When choosing a node to explore next, break ties in favor of the alphabetically least. ABCDEFGHIJ (c) How many directed simple cycles does this graph have? 0 1 3 9 x 7 infinitely many

May 17, 005 CS11 Final Exam Page 8 of 1 11. (5 points) Given the following heap, draw the heap that would result after deleting the minimum element. 5 9 13 11 10 9 4 35 4 9 10 13 11 4 9 4 35 1. (5 points) Say the following tree was obtained by inserting the element 4 into an AVL tree. The tree no longer satisfies the AVL invariant, but the invariant can be reestablished by performing two rotate operations. Show the resulting tree after this is done. 56 9 63 6 10 4 10 9 56 6 4 63

May 17, 005 CS11 Final Exam Page 9 of 1 13. (10 points) Given a binary search tree, write an instance method between(...) that takes a lower bound lower and an upper bound upper and returns a HashSet containing all of the data elements x in the tree between lower and upper, inclusive. To add an element x to the HashSet h, use h.add(x). (Hint. Define a helper method betweenhelper that takes an extra HashSet argument containing all the elements accumulated so far.) import java.util.hashset; class TreeNode<E extends Comparable> { E value; TreeNode<E> left; TreeNode<E> right; HashSet<E> between(comparable lower, Comparable upper) { return betweenhelper(lower, upper, new HashSet<E>()); HashSet<E> betweenhelper(comparable lower, Comparable upper, HashSet<E> h) { if (value.compareto(upper) <= 0 && value.compareto(lower) >= 0) h.add(value); if (left!= null && value.compareto(lower) >= 0) h = left.betweenhelper(lower, upper, h); if (right!= null && value.compareto(upper) <= 0) h = right.betweenhelper(lower, upper, h); return h;

May 17, 005 CS11 Final Exam Page 10 of 1 14. (6 points) Say what is output by the following programs. If the program gives an error, say what that error is. (a) int x = 5; try { x = 3; throw new NullPointerException(); catch (Exception e) { System.out.println(x); finally { System.out.println(x + 1); 3 4 (b) class A { int foo() { return 1; class B extends A { int foo() { return ; class C extends B { int bar(a a) { return a.foo(); C x = new C(); System.out.println(x.bar(x)); (c) class A { int e = 1; class B extends A { int e = ; class C extends B { int bar(a a) { return a.e; C x = new C(); System.out.println(x.bar(x)); 1

May 17, 005 CS11 Final Exam Page 11 of 1 15. (4 points) Questions (a) and (b) on the next page refer to the following constructor for a graphical user interface. GUI() { final JFrame frame = new JFrame("Rock Through the Ages"); final JMenuBar menubar = new JMenuBar(); final JTextArea textarea = new JTextArea(); frame.setdefaultcloseoperation(jframe.exit_on_close); JButton button = new JButton("1965-1969"); button.addactionlistener(new ActionListener() { public void actionperformed(actionevent e) { frame.settitle("rock Through the Ages: 1965-1969"); textarea.settext("1967 Jimi Hendrix - Axis: Bold As Love\n"); textarea.append("1967 Cream - Disraeli Gears\n"); textarea.append("1968 Rolling Stones - Beggar s Banquet"); frame.validate(); ); menubar.add(button); button = new JButton("1970-1974"); button.addactionlistener(new ActionListener() { public void actionperformed(actionevent e) { frame.settitle("rock Through the Ages: 1970-1974"); textarea.settext("197 Yes - Fragile\n"); textarea.append("1973 Led Zeppelin - Houses of the Holy\n"); textarea.append("1973 Pink Floyd - Dark Side of the Moon"); frame.validate(); ); menubar.add(button); frame.setjmenubar(menubar); textarea.setpreferredsize(new Dimension(400,00)); frame.add(textarea,borderlayout.center); frame.pack(); frame.setlocation(00,00); frame.setvisible(true);

May 17, 005 CS11 Final Exam Page 1 of 1 (a) Draw the object that appears on the screen when the code on the previous page is executed. (b) Draw the object as it appears after the 1970-1974 button is pushed. End of Exam