CS2114 Final
For large values of n which statement is true?
(n2 + n ) / 2 behaves like n^2
Suppose QueueADT is implemented using a singly linked list. What is the lowest Big-Oh time complexity that can be achieved for an enqueue method?:
O(1)
For binary search trees with no duplicate entries, entries in the right subtree of a node are less than the entry in the node.
False
Given the following code: public static int powerOf5(int exponent){ if (exponent == 0) return 1; else return 5 * powerOf5(exponent -1); } what is powerOf5(3)?
125
The clone() method defined in the Object class performs:
A shallow copy
Select the best generalized algorithm for adding to a list using a linked chain implementation:
Create a new node, populate the data and next fields of the new node, update the linked chain to include the new node
A class that implements Iterator will have a compile time error if it does not implement a remove method
False
What is not true about a binary search tree?
If there are n nodes, then its height is n/2
A stack is
LIFO (last in first out)
Would blacklisting a specific state/region fully prevent Distributed DOS (DDOS) attacks on a targeted victim's public online service (for example YouTube)?
No
Java uses quicksort and mergesort under the hood for built-in sorting of arrays and lists. These algorithms have efficiency:
O( n log n)
If client code is traversing a list by using an iterator. The efficiency of traversal is:
O(n)
The worst-case time complexity of insertion sort is:
O(n2)
If client code is traversing a list by repeatedly using a get method and the underlying structure is a linked chain. The efficiency of traversal is:
O(n^2)
What is the big Oh of the following code snippet? for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (favorites[j] == i) return favorites[j];
O(n^2)
The benefit of using sentinel nodes
Special cases are not required for operations on nodes at the beginning or end of the list
Select all of the following that will happen if removeFront() is called on a deque with 3 items?
The first node of the three will be removed firstNode.data will be returned
Based on ListInteface.java, an attempt to remove and item from an empty list will
Throw an IndexOutofBoundsException
A ListIterator provides a superset of the functionality that an Iterator provides.
True
Based on the find method traced in the video, it is a recursive method.
True
Locating a new node's insertion point in a binary search tree stops when
We reach a null child.
for (int i = 1; i < n; i *= 2) System.out.println("Value " + i + " is " + values[i]);
O(logn)
Suppose you try to perform a binary search on the unsorted array {1, 4, 3, 7, 15, 9, 24}. Which element will not be found when you try searching for it?
15
Select the most accurate steps to remove a node that contains a designated element.
Find the node that contains the designated element, get a reference to the node before it, reset the next reference of the node before it to be the node after it
Select all of the following that will happen if removeFront() is called on a deque with 1 item?
firstNode and lastNode will become null firstNode.data will be returned lastNode.data will be returned
With respect to Cybersecurity the term ______ means the protection of data from being viewed or used by unauthorized users.
Confidentiality
Which of the following statements about binary search algorithms is FALSE?
Binary search can be implemented to take O(1) time in the worst case. Binary search takes (log n) time, worst case.
Based on the find method traced in the video, it throws an exception when data is not found.
False
Binary search trees with no duplicate entries have all leaves on the the second level.
False
Consider a generic method declared as depicted below, with type parameter <T extends Number> and two method parameters both of type T: public <T extends Number> void specialMethod(T first, T second)
client code can only provide type Number or any subclass of Number for the type parameter for T
Which of the following would remove the Node referenced by the non-null variable curr from items, a non-empty doubly linked list with sentinel nodes firstNode and lastNode? Assume that curr has access to methods getPrevious(), setPrevious(Node n), getNext(), and setNext(). Also, items has access to getSize().
curr.getPrevious().setNext(curr.getNext()); curr.getNext().setPrev(curr.getPrev());
public class RecursiveMath ... public int fib (int a) { if (a < 2) return a; else return fib(a-1) + fib(a-2); } ... } What is the base case for fib in the above definition?
fib(a) for a < 2
public static void displayArray(int[] array, int first, int last) { if (first == last) System.out.println(array[first] + " "); else int mid = (first + last) / 2; displayArray3(array, first, mid); displayArray3(array, mid + 1, last); } An initial call to displayArray3 has parameter values of 0 and 20 for first and last respectively: displayArray3(myArray, 0, 20). Which is the correct sequence of subsequent calls?
displayArray3(myArray, 0, 10) displayArray3(myArray, 0, 5) displayArray3(myArray, 0, 2)
Given that 0 <= k < number of entries in the list minus 1, after a call to remove(k), getEntry(k) should return
The item formerly stored in position k+1
If an item is inserted in position k of a list of n items, which of the following is true?
The item in position n will be moved to position n+1
To efficiently remove a node at the end of a linked chain implementation of a queue with a tail reference requires a
extra reference in the node pointing to the previous node
To remove the node in position k, which of the following is needed?
A reference to the node in position k-1
We know that using Generics reduces the need to cast types. Which of the following answers best conveys some of the other benefit(s) of using generics and parameterized or generic types in Java?
Generics provide type safety and enable strong type checks at compile time Provide developers with the ability to implement generic algorithms (classes and methods)
Imagine you have an empty stack of strings named stack. List the contents of the stack from top to bottom after the following operations have executed. (Assume that the pop method returns the element that was popped.) stack.push("K"); stack.pop(); stack.push("P"); stack.push("G"); stack.push("R"); String str = stack.pop(); stack.push("V"); stack.push(str);
R V G P
private void displayChain(Node curr) { if (curr.getNext() != null) displayChain(curr.getNext()); System.out.println(curr.getData()); } Indicate how each private helper member method would print a non-empty chain
Reverse order
Which of the following possible reasons BEST explains why a SortedList implementation would not need the method, add(int newPosition, T newEntry)?
The SortedList add(newEntry) method has the responsibility of adding new entries in sorted order, as a result Client code would no longer be required to, or be allowed to, specify the location of the new entries by using add(int newPosition, T newEntry).
When adding a node newNode to a linked list referenced by head, what code would be the branch for the case that the list is empty?
head = newNode;
An enhanced for statement can only be use on data structures that
implement Iterable PreviousNext
The advantage of a hard drive versus cache is that
Hard drives hold more data
If the coke guy put a soda with "Bro" into the front of the vending machine, followed by "Sidekick" and "Better Half," in what order will the machine users receive the cokes?
"Better Half" "Sidekick" "Bro"
Which combination of statements are True? Statements: The question mark (?) is a wildcard or placeholder, representing an unknown type In the statement "? extends MyClass", the ? represents a subtype of MyClass where MyClass represents an Upper Bound In the statement "? extends MyClass", the ? represents a supertype of MyClass where MyClass represents a Lower Bound
1 and 2
public static void displayArray(int[] array, int first, int last) { if (first == last) System.out.println(array[first] + " "); else int mid = (first + last) / 2; displayArray3(array, first, mid); displayArray3(array, mid + 1, last); } An initial call to displayArray3 has parameter values of 0 and 20 for first and last respectively: displayArray3(myArray, 0, 20). Which of the following would be the values of first and last in the second recursive call from that method call?
11, 20
Consider the following recursive method: public int examMethod(int n) { if (n == 1) return 1; else return (n + this.examMethod(n-1)); } What value is returned by the call examMethod(16)?
136
How many times will F be called if n = 5, ignoring F(5) itself? public static long F(int n) { if (n == 0) return 0; if (n == 1) return 1; return F(n-1) + F(n-2);}
14
public static void displayArray(int[] array, int first, int last) { if (first == last) System.out.println(array[first] + " "); else int mid = (first + last) / 2; displayArray3(array, first, mid); displayArray3(array, mid + 1, last); } With the call displayArray3 ({4,5,6,7,8,9,10,11},0,7), how many recursive calls would be made?
14
Suppose you try to perform a binary search on the unsorted array {1, 4, 3, 7, 15, 9, 24}. How many of the items in this array will be found if they are searched for?
5
Approximately how many recursive calls would our Towers of Hanoi pseudo code algorithm make given a tower with 11 disks?
2^11
Given a recursive algorithm to calculate the the nth fibonacci number that makes 2 recursive calls. Approximately how many recursive calls would it make to calculate the 7th fibonacci number? The fibonacci series is a series of numbers in which each number is the sum of the two preceding numbers. Here's the beginning of the sequence: 1, 1, 2 , 3, 5, 8
2^7
Given the following code: public static void springFreeze(int temp){ if (temp < 32) System.out.println("Frost!"); else { System.out.println("temps are dropping..."); springFreeze(temp - 4); } } How many times will springFreeze(40) print out "temps are dropping..."?
3
Given that the height of a tree is 1 more than the number of edges from the root to the deepest node: If a binary tree of height 5 has nodes that either have 0 or 2 children and all leaves on the same level, how many nodes are in the tree?
31
Given the following code: public void demoRecursion(int value){ if (value > 25) System.out.print (80 - value); else demoRecursion(value * 2); } What is the output for demoRecursion(5)?
40
Given the following code: public void demoRecursion(int value){ if (value > 25) System.out.print (80 - value); else demoRecursion(value * 2); } What is the output for demoRecursion(1)?
48
Given that the height of a tree is 1 more than the number of edges from the root to the deepest node: If a binary tree of height 3 has nodes that either have 0 or 2 children and all leaves on the same level, how many nodes are in the tree?
7
Given the following code: public static void displayArray(int[] array, int first, int last) { System.out.print(array[first] + " "); if (first < last) displayArray(array, first + 1, last); } With the call displayArray3 ({4,5,6,7,8,9,10,11},0,7), how many recursive calls would be made?
7
Given a recursive algorithm to countdown to 1 from a given integer that makes 1 recursive call. Approximately how many recursive calls would it make to countdown from 99?
99
If you attempt to call the clone method on an object that doesn't implement the Cloneable interface
A CloneNotSpportedException will be thrown
Which of the following are true? (Select all of that apply)
A SortedList implementation contains code which compares new elements being added to the SortedList to the elements previously added and stored within the SortedList. This comparison helps the add() method code determine the correct position to add the new element so as to preserve sorted order Lists are ordered but not necessarily sorted. List ordering is based on the positions of the elements or Objects within the List, NOT on the value or state of the element or Object
Shallow copy for an object means creating a new instance of the object containing a copy of all of its instance variables references.
False
Your Web Browser is an example of what type of software?
Client
When you upload assignment submissions to WebCAT for grading you (and your software and hardware) are adopting the role of a _________ with WebCAT acting in the role of a _________.
Client, Server
Insertion sort on an array is requires (select all that apply):
Comparison of each unsorted item to enough currently sorted items to find its insertion point Shifting of sorted items above each unsorted item's insertion point
Based on the find method traced in the video, it depends on data extending Comparator.
False
Based on the find method traced in the video, it is an equals method for binary search trees.
False
Binary search trees with no duplicate entries have nodes with exactly two children .
False
For binary search trees with no duplicate entries, entries in the left subtree of a node are greater than the entry in the node.
False
Given the following code: public static int powerOf5(int exponent){ if (exponent == 0) return 1; else return 5 * powerOf5(exponent -1); } what is powerOf5(-2)?
Infinite Recursion
What are the merits of insertion sort compared to bubble sort and selection sort?
It is faster for already sorted data.
Suppose you are trying to choose between an array and a singly linked list to store the data in your Java program. Which arguments would correctly support one side or the other?
Linked lists are better suited to a program where the amount of data can change unpredictably. Arrays provide more efficient access to individual elements.
Compare the Interface specifications for the List and Sorted List Abstract Data Types then answer the following questions. The relevant interface files are provided via the first page of the module - Introduction to sorted lists. Which of the following are true? (Select all of that apply)
ListInterface includes the method definition, add(int newPosition, T newEntry), while SortedListInterface does not ListInterface includes the method definition, T replace(int givenPosition, T newEntry), while SortedListInterface does not. SortedListInterface includes an additional remove method definition, boolean remove(T anEntry). The SortedListInterface includes a new method, int getPosition(T anEntry).
What is the primary risk of implementing a SortedList by inheriting from the List class?
Methods like add(newPosition, newEntry) and replace(givenPosition, newEntry) would be inherited, client code can use these methods in a manner that affects the sorted order
Implementing SortedLists using the class definition below would result in which of the following? public class MySortedList> extends MyList implements SortedListInterface
MySortedList would inherit all of the methods from MyList, methods unique to the SortedListInterface would need to be implemented
Which of the following are true for a list ADT?
ordered items can be replaced
Given the method header: public<T extends Comparable<? super T>> int binarySearch( T[] ray, T target) Which would be the best header for a helper method?
private <T extends Comparable<? super T>> int binarySearchHelper(T [] ray, T target, int first, int last)
This sorting algorithm starts by finding the smallest value in the entire array. Then it finds the second smallest value, which is the smallest value among the remaining elements. Then it finds the third smallest value, the fourth, and so on.
selection sort
Problem size is defined as
the number of items an algorithms processes
In the demonstrated linked-chain implementation of a StackADT, when a node is popped from the stack the original first node will no longer be referenced the original first node will have a new value the second to last node will now be the top all of the above
the original first node will no longer be referenced
In the linked chain implementation of a queue, the chain's first node contains
the queue's front entry
An algorithm has: a) time requirements b) space requirements c) both a & b d) none of the above
time requirements space requirements
Consider the following code: public int examMethod(int n) { if (n == 1) return 1; else if (n > 1) return (n + this.examMethod(n-1)); } What is the purpose of examMethod?
to compute the sum of the positive integers from 1 to n
Given the following code skeleton for the private helper method: if (first > last) return ___________________;else { int mid = (first + last) / 2; if (ray[mid].equals(target))return ___________________; if (ray[mid].compareTo(target) < 0)return ___________________; elsereturn ___________________;} Select the order of the code to fill in the blanks:
-1 mid binarySearchHelper(ray,target,mid + 1,last) binarySearchHelper(ray,target,first,mid-1)
Consider the following method: public int examMethod(int n) { if (n == 1) return 1; else return (n + this.examMethod(n-1)); } Which of the following inputs will cause a non-terminating recursion?
0
Given the following code: public static void springFreeze(int temp){ if (temp < 32) System.out.println("Frost!"); else { System.out.println("temps are dropping..."); springFreeze(temp - 4); } } How many times will springFreeze(28) print out "temps are dropping..."?
0
Suppose you try to perform a binary search on a 5-element array sorted in the reverse order of what the binary search algorithm expects. How many of the items in this array will be found if they are searched for?
1
If an inorder traversal of a complete binary tree visits the nodes in the order ABCDEF (where each letter is the value of a node), which order are the nodes visited during an postorder traversal? Recall that OpenDSA defines a complete binary tree as follows: "A complete binary tree has a restricted shape obtained by starting at the root and filling the tree by levels from left to right. In the complete binary tree of height d, all levels except possibly level d are completely full."
ACBEFD
public T removeFront() { T front = getFront(); firstNode = firstNode.getNext(); if(firstNode == null) { lastNode = null; } else { firstNode.setPrev(null); } return front; } What will happen if removeFront() is called on an empty deque?
An EmptyDequeException will be thrown
Which of the following is more restrictive? ArrayList<Integer> myList; ArrayList<? super Integer> myList;
ArrayList<Integer> myList;
This is a notoriously inefficient algorithm traditionally taught to introduce sorting algorithms:
Bubble sort
Which of the following is the best example of a data availability management concern, as described by the CIA Triad?
How to distinguish a flash crowd vs DDOS attack.
Match the following terminology: Root Leaf Siblings Child node Edge
In a tree, the topmost node of the tree. A node that has no children. Nodes that have the same parent node. Node referenced by another node in a tree. The connection that links two nodes.
How would the following code print the array? public static void displayArray(int[] array, int first, int last) { if (first <= last){ displayArray(array, first, last - 1); System.out.print(array[last] + " "); } }
In order
How would the following code print the array? public static void displayArray(int[] array, int first, int last) { System.out.print(array[first] + " "); if (first < last) displayArray(array, first + 1, last); }
In order
private void displayChain(Node curr) { if (curr != null) { System.out.println(curr.getData()); displayChain(curr.getNext()); } } Indicate how each private helper member method would print a non-empty chain
In order
How would the following code print the array? public static void displayArray(int[] array, int first, int last) { if (first < last) displayArray(array, first + 1, last); System.out.print(array[first] + " "); }
In reverse order
private void displayChain(Node curr) { if (curr != null) { displayChain(curr.getNext()); System.out.println(curr.getData()); } } Indicate how each private helper member method would print a non-empty chain
In reverse order
public static void displayArray(int[] array, int first, int last) { System.out.print(array[last] + " "); if (first < last) displayArray(array, first, last - 1); }
In reverse order
With respect to the declaration ArrayList<? super Customer> myCustomer; Which of the following is True?;
In the statement "? super Customer", the ? represents a Customer type or a super type of Customer, where Customer is considered to be the Lower Bound
When using the runner technique on a singly linked chain to insert an item in order, both prev and curr nodes are used in order to (select all that apply):
Insert an item before the node that curr references Loop through the items in the chain to find the insertion location
Which of the following is true about a doubly linked chain implementation of a list with sentinel nodes?
It takes more space It makes the code executed for adding a new value to the list the same whether the list is empty, has one items, or many items.
Suppose you have a binary search tree with no left children. Duplicate keys are not allowed. Which of the following explains how this tree may have ended up this way?
It was filled in ascending order.
Which cache policy is more susceptible to exploitation by a malicious user (hacker) who knows the cache policy used by a given system?
Least Recently Used
Keeping track of lastNode in addition to firstNode
Makes enqueue operations O(1) Causes lastNode to need to be updated if the only item in the queue is dequeued Causes lastNode to need to be updated every time an item is enqueued
private void displayChain(Node curr) { if (curr == null) System.out.println(curr.getData()); else displayChainBackwards(curr.getNext()); } Indicate how each private helper member method would print a non-empty chain
Neither reverse or in order
public static void displayArray(int[] array, int first, int last) { System.out.print(array[first] + " "); if (first < last) displayArray(array, first, last - 1); }
Neither reverse or in order
If an algorithm requires 7 basic operations for an algorithm with a problem size of n, the algorithmic complexity is
O(1)
If the top of the stack is the last element in the array what is the complexity for pop() in big Oh notation?
O(1)
If the top of the stack is the last element in the array what is the complexity for push(newEntry) in big Oh notation?
O(1)
In a circular array-based implementation of a queue, what is the performance when the dequeue operation ?
O(1)
In a linked chain implementation of a queue, the performance of the enqueue operation is
O(1)
What is the time complexity for adding an entry to a fixed-size array-based bag ADT?
O(1)
What is the time complexity for adding an entry to a linked-based bag ADT?
O(1)
Suppose you have a sorted list of numbers stored in a Java array of ints. What is the worst-case time complexity of searching for a given number in the list using binary search?
O(log n)
If the top of the stack is the first entry of the array what is the complexity for pop() in big Oh notation?
O(n)
If the top of the stack is the first entry of the array what is the complexity for push(newEntry) in big Oh notation?
O(n)
Suppose you have a list of numbers stored in consecutive locations in a Java array. What is the worst-case time complexity of finding a given element in the array using linear search?
O(n)
The time complexity of linear search is:
O(n)
What is the worst-case time complexity for searching a linked-based bag ADT for a particular entry?
O(n)
When we use recursion to solve a problem, we have a problem that contains one or more problems that are similar to itself a version of the problem that is simple enough to be solved by itself, without recursion, and a way of making the the problem simpler so that it is closer to (and ultimately the same as) the version in 2. What is 2. called?
The base case
public class RecursiveMath ... public int fib (int a) { if (a == 1) return 1; else return fib(a-1) + fib(a-2); } ... } Given the above definition, what is the result of executing the following? RecursiveMath bill = new RecursiveMath(); int x = bill.fib(-1);
The code does not terminate
Both ListInterface and SortedListInterface include the method definition, contains(anEntry). Consider the example implementation of the List contains(anEntry) method presented below. public boolean contains(T anEntry) { boolean found = false; int index = 0; while (!found && (index < numberOfEntries)) { if (anEntry.equals(list[index])) { found = true; } index++; } // end while return found; } // end contains How could the contains(anEntry) method implementation used for List be improved upon when implementing the contains(anEntry) method for a SortedList?
The contains method could be written so that it stops searching the List for anEntry when it passes the location where anEntry should be found if stored within a SortedList.
The following references can be used to add an item to position k in a linked chain implementation of a list:
The node containing the item in position k - 1
What is the main benefit of implementing a SortedList by inheriting from a revised List Base class instead of inheriting from the standard List Base class?
The revised List Base class can be set up so that unwanted methods - like add(newPosition, newEntry) and replace(givenPosition, newEntry) - cannot be inherited by subclasses
An enhanced for statement can be programmed using a call to the iterator() method and calling the hasNext() and next() methods of the returned iterator.
True
Based on the find method traced in the video, it depends on T extending Comparable.
True
Binary search trees with no duplicate entries have nodes with 0,1, or 2 children .
True
Deep copy for an object means performing a shallow copy plus copying all of the mutable objects inside the object.
True
For binary search trees with no duplicate entries, entries in the left subtree of a node are less than the entry in the node.
True
For binary search trees with no duplicate entries, entries in the right subtree of a node are greater than the entry in the node.
True
Is the following statement True or False? Statement: Bounded type parameters allows developers to restrict the types that can be used as type arguments in a parameterized type.
True
Is the following statement True or False? Statement: To declare generic methods we write methods using the format methodModifiers <genericTypeParameters> returnType methodName(methodParameters)
True
The next method needs to be called for each time the remove method is called in order to avoid an exception being thrown.
True
To deep clone an array-based collection, you need to perform 3 levels of cloning: Shallow copy, clone the array object, and deep clone the items stored in the array.
True
Which of the following are valid approaches to implementing a SortedList? (select all that apply)
Write it from scratch, most of the methods implemented similarly to the List implementation, some methods removed, added, or updated to ensure that the List remains in sorted order Use composition, where a SortedList uses a List as a field, with other attributes and methods to supported the SortedList features Use composition, where a SortedList uses a List as a field, with other attributes and methods to supported the SortedList features
Which of the following best describes the 2 key components of a recursive method:
a base case and a recursive case
One approach to implementing a SortedList is through inheritance, creating a subclass of the List class then overriding the relevant methods to ensure that the List remains in sorted order. Which of the following inherited List methods MUST be overridden to ensure that sorted order is preserved? (select all that apply)
add(newEntry) add(newPosition, newEntry) replace(givenPosition, newentry)
A method with the header public static double getMax(Iterable<price> prices) can be called with a parameter that is:
any type that implements Iterable
Given that backIndex references the last element of the queue stored in a contents array, which of the following best describes how to update backIndex when a new entry is successfully enqueued:
backIndex = ( backIndex + 1) % contents.length
The fact that an iterator keeps its place within a list is a
benefit because it saves work and improves efficiency
This sorting algorithm repeatedly examines neighboring elements, swapping those pairs that are out of order.
bubble sort
When a linked chain contains nodes that reference both the next node and the previous node, it is called a(n)
doubly linked chain
If an ArrayQueue is stored an array contents with 1 unused element, which of the following are true (select all that apply):
contents.length -1 indicates the capacity of the queue If size represent the number of elements in the arrayqueue then its range is 0 <= size < contents.length
Give the following code: public void countDown(int leadTime, String message) { System.out.println(leadTime + "..."); if (leadTime > 0) countDown(leadTime - 1, message); else System.out.println(message); } If client code calls countDown(5,"GAMEOVER"), what is the order of the subsequent method calls?
countDown(4,"GAMEOVER"), countDown(3,"GAMEOVER"), countDown(2,"GAMEOVER"), countDown(1,"GAMEOVER"), countDown(0,"GAMEOVER")
Given that the height of a tree is 1 more than the number of edges from the root to the deepest node:If a binary tree n nodes that either have 0 or 2 children and all leaves on the same level, what is the height of the tree?
log2(n+1)
A risk of multiple iterators
one iterator makes a change that another doesn't know about
In a circular array-based implementation of a queue, the initial size of the array should be
one more than the queue's initial capacity
You should express the complexity of an algorithm in terms of its: space requirements execution time problem size overall complexity
problem size
In the demoed array-based implementation of a Stack ADT, the entry peek returns may be found at
the last occupied location in the array
public class RecursiveMath ... public int fib (int a) { if (a < 2) return a; else return fib(a-1) + fib(a-2); } ... } Given the above definition, what is the result of executing the following? RecursiveMath bill = new RecursiveMath(); int x = bill.fib(-1);
x is set to -1