dataset
stringclasses 1
value | id
stringlengths 21
21
| question
stringlengths 8
5.15k
| choices
listlengths 4
4
| answer
stringclasses 4
values | rationale
stringlengths 1
1.57k
|
|---|---|---|---|---|---|
canterbury_cs
|
canterbury_cs_0000000
|
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?
|
[
"5",
"0",
"1",
"2"
] |
C
|
Only the middle element will be found. The remaining elements will not be contained in the subranges that we narrow our search to.
|
canterbury_cs
|
canterbury_cs_0000001
|
Which data structure used to implement <code>Set</code> yields the worst performance for <code>Set.contains</code>?
|
[
"Binary search tree",
"Linked list",
"Sorted array",
"Hashtable"
] |
B
|
Implementing Set.contains involves a search of the data structure. A binary search tree and a sorted array are searched in O(lg n) time, and a hashtable in O(1), assuming a sane hash function. A linked list is searched in O(n) time.
|
canterbury_cs
|
canterbury_cs_0000002
|
For a graph with N nodes, what's the minimum number of edges it must have for it to contain a cycle?
|
[
"N + 1",
"N",
"N - 1",
"1"
] |
D
|
A vertex with an edge to itself is a cycle.
|
canterbury_cs
|
canterbury_cs_0000003
|
Read the following method skeleton and choose the best expression to fill in the blank on <strong>line 8</strong> so that the method will behave correctly:
<pre lang="text/x-java">/**
* Takes a string reference and counts the number of times
* the character 'A' or 'a' appears in the string object.
* @param aString String reference to object containing chars.
* @precondition aString is not null (you may assume this is true).
* @return The number of times 'A' or 'a' appears in the string.
*/
public static int countAs(String aString) // line 1
{
int counter = __________; // line 2
int totalA = 0; // line 3
while (counter < __________) // line 4
{
if ( __________.equals("A") ) // line 5
{
totalA = totalA + __________; // line 6
}
counter++; // line 7
}
return __________; // line 8
}
</pre>
|
[
"<code>counter</code>",
"<code>true</code>",
"<code>false</code>",
"<code>totalA</code>"
] |
D
|
The return type of the method is <code>int</code>, so an integer return value must be provided. Since <code>counter</code> is used as a loop index, it will always end up being the total number of characters in the given string. The variable <code>totalA</code> is used as an accumulator that is incremented each time a letter A is found in the string, so it is the choice that will provide the correct return value for the method.
|
canterbury_cs
|
canterbury_cs_0000004
|
Two algorithms accomplish the same task on a collection of N items. Algorithm A performs log<sub>2</sub> N operations. Algorithm B performs log<sub>3</sub> N operations. Under what conditions does algorithm A offer better performance?
|
[
"N < log<sub>3</sub> 2",
"For no N.",
"N < log<sub>2</sub> 3",
"N < 8"
] |
B
|
For no possible collection size N is log<sub>2</sub> N < log3 N.
|
canterbury_cs
|
canterbury_cs_0000005
|
Finding the median value in a complete and balanced binary search tree is
|
[
"O(1)",
"O(log N)",
"O(N)",
"O(N<sup>2</sup>)"
] |
A
|
The median is the element that has M elements less than it and M elements greater than it. This can only be said of the root node in a complete and balanced binary tree. The root is accessed in constant time.
|
canterbury_cs
|
canterbury_cs_0000006
|
For a heap of size n, which is indexed at 0, at what position will its last child be?
|
[
"2n + 1",
"n / 2",
"n - 1",
"floor(n / 2) + 1"
] |
C
|
The last element will be at the end of the array.
|
canterbury_cs
|
canterbury_cs_0000007
|
What design stategy does Quicksort use?
|
[
"Greedy",
"Divide and conquer",
"Dynamic programming",
"Brute force"
] |
B
|
Quicksort is divide and conquer.
|
canterbury_cs
|
canterbury_cs_0000008
|
If you did not have a base case in a recursive function in C, and were working on a modern Unix-based system, what would most likely happen?
|
[
"Segmentation fault",
"Stack overflow error",
"C wouldn’t complain, but your computer would crash",
"Nothing, that’s fine"
] |
C
|
It really depends on the program for whether it would be B or C. Both can be argued to be correct.
|
canterbury_cs
|
canterbury_cs_0000009
|
The following Python method determines whether or not a list of values, passed in as a parameter, has any duplicate values.
What is the Big-Oh running time of this algorithm?
def duplicates(lov):
dupCount = 0<br> outer = 0<br> while (outer < len(lov)):<br> inner = outer + 1<br> while (inner < len(lov)):
if (lov[inner] == lov[outer]):
dupCount = dupCount + 1
inner = inner + 1
outer = outer + 1
if (dupCount == 0):<br> print "there are no duplicate values"<br> else:<br> print "there are ", dupCount, " duplicate values"
|
[
"O(1) ",
"O(n)",
"O(n log<sub>2</sub> n)",
"O(n<sup>2</sup>)"
] |
D
|
Each item in the list is compared against each other item in the list: a classic example of the<em> all-pairs</em> programming pattern. The first item is compared against n-1 other values. The second item is compared against n-2 other values, etc. The total number of comparisons is <img src="img/2.png" alt="" title="latex">
|
canterbury_cs
|
canterbury_cs_0000010
|
What is printed when the following program runs?
<pre lang="text/x-java">public class Main {
public static boolean getTrue() {
System.out.print("T");
return true;
}
public static boolean getFalse() {
System.out.print("F");
return false;
}
public static void main(String[] args) {
getTrue() || getTrue();
}
}
</pre>
|
[
"TT",
"T",
"F",
"TF"
] |
B
|
If the first operand for || is true, as is the case here, the second is not evaluated.
|
canterbury_cs
|
canterbury_cs_0000011
|
You are storing a complete binary tree in an array, with the root at index 0. At what index is node i's parent?
|
[
"(i - 1) / 2",
"2i + 1",
"i + i + 2",
"i / 2 + 1"
] |
A
|
(i - 1) / 2
|
canterbury_cs
|
canterbury_cs_0000012
|
Which of the following abstract datatypes would be the best choice for part of the implementation of the part of a compiler that determines whether the parentheses in a program are balanced?
|
[
"A Stack",
"A Queue",
"A List",
"A PriorityQueue"
] |
A
|
A close parenthesis must match the most recently entered open parenthesis. So for example, the sequence )()( doesn't match, while ()() and (()) do, even though they all have two open and two close parentheses. To make this work, you can push each open parenthesis on a Stack, and pop it off each time you see a close parenthesis. The last-in-first-out nature of a Stack makes it easy to determine whether the parentheses are balanced.
|
canterbury_cs
|
canterbury_cs_0000013
|
What is printed when the following program runs?
<pre lang="text/x-java">public class Main {
public static boolean getTrue() {
System.out.print("T");
return true;
}
public static boolean getFalse() {
System.out.print("F");
return false;
}
public static void main(String[] args) {
getTrue() || getFalse();
}
}
</pre>
|
[
"TF",
"F",
"T",
"TT"
] |
C
|
If the first operand for || is true, as is the case here, the second is not evaluated.
|
canterbury_cs
|
canterbury_cs_0000014
|
Kexin is hashing the values 9, 45, 22, 48, 38 into a hash table of size 20. Which hash function will give her no collisions?
|
[
"h(k) = k % 10",
"h(k) = k / 10",
"h(k) = (k % 10) + (k / 10)",
"h(k) = (k % 10) - (k / 10)"
] |
D
|
A will collide on the 48/38; B will collide with 45/48; C will collide with 9/45.
|
canterbury_cs
|
canterbury_cs_0000015
|
For the Insertion sort algorithm; what is its best case and worst case performance?
|
[
"Best: O(n) \n Worst: O(n<sup>2</sup>)",
"Best: O(n)<br>Worst: O(n)",
"Best: O(log<sub>2</sub> n)<br>Worst: O(n<sup>2</sup>)",
"Best: O(n<sup>2</sup>)<br>Worst: O(n<sup>2</sup>)"
] |
A
|
Insertion sort, if given an already sorted list, will still perform O(n) comparisons to ascertain the list is sorted. If the list is "reverse sorted," then the first pass will require 1 exchange. The second pass will require 2 exchanges, etc. Hence, in the worst case, O(n<sup>2</sup>) exchanges.
|
canterbury_cs
|
canterbury_cs_0000016
|
For the selection sort algorithm; what is its best case and worst case running time?
|
[
"Best: O(1)<br>Worst: O(n)",
"Best: O(n)<br>Worst: O(n<sup>2</sup>)",
"Best: O(log<sub>2</sub> n)<br>Worst: O(n)",
"Best: O(n<sup>2</sup>) \n Worst: O(n<sup>2</sup>)"
] |
D
|
Selection sort repeatedly runs the Find-largest algorithm as its helper function. So, regardless of the list's initial ordering, Find-largest will cost n-1 comparisons for the first pass, n-2 for the second, etc. Hence selection sort's run time performence is independent of the list's initial ordering: O(n<sup>2</sup>)
|
canterbury_cs
|
canterbury_cs_0000017
|
You see the expression <code>n = 100000</code> in some code that successfully compiles. What type can <code>n</code> not be?
|
[
"int",
"short",
"float",
"double"
] |
B
|
Shorts can only hold values in [-32768, 32767].
|
canterbury_cs
|
canterbury_cs_0000018
|
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?
|
[
"7",
"1",
"9",
"15"
] |
D
|
The answer is 15. The first check will look at 7. 15 is greater than 7, so we search to its right. The second check will look at 9. 15 is greater than 9, so we search to its right. The third check will look at 24. 15 is less than 24, so we look to its left. However, our range has just been inverted and our searching stops, not having found 15.
|
canterbury_cs
|
canterbury_cs_0000019
|
Fill in the single missing line of code:<br><code>int p, *r, **q;</code>
<pre lang="text/x-c">p = 27;
r = &p;
</pre>
// MISSING LINE<br><code>printf("The value is %d", **q); // prints 27.</code>
|
[
"*q = *r;",
"q = &r;",
"**q = p;",
"q = &&p;"
] |
B
|
B gets q to point to r, which points to p.
|
canterbury_cs
|
canterbury_cs_0000020
|
What would be the performance of removeMin and insert methods in a priority queue if it is implemented by a sorted list?
|
[
"O(1) , O(1)",
"O(1) , O(n)",
"O(n) , O(1)",
"O(n) , O(n)"
] |
B
|
O(n) , O(1)
|
canterbury_cs
|
canterbury_cs_0000021
|
What is the value of j after this code is executed?
int i = 6, j = 10;
j += i;
|
[
"4",
"6",
"10",
"16"
] |
D
|
The value of variable i (6) is added to that of variable j (10) resulting in 16 as the new value of j
|
canterbury_cs
|
canterbury_cs_0000022
|
Suppose q is an instance of a queue that can store Strings, and I execute the following statements starting with q empty:
<pre lang="text/x-java">1. q.enqueue("Sweden");
2. q.enqueue("is");
3. q.enqueue("my");
4. String w = q.dequeue();
5. String x = q.peek();
6. q.enqueue("neighbor");
7. String y = q.dequeue();
8. String z = q.dequeue();
</pre>
What is the value of z after executing these expressions in order?
|
[
"<code>\"Sweden\"</code>",
"<code>\"is\"</code>",
"<code>\"my\"</code>",
"<code>\"neighbor\"</code>"
] |
C
|
If we consider the contents of the queue after each expression (listing contents from head to tail), we have
1. ["Sweden"]
2. ["Sweden" "is"]
3. ["Sweden" "is" "my"]
4. ["is" "my"] (and w gets set to "Sweden")
5. ["is" "my"] (and x gets set to "is")
6. ["is" "my" "neighbor"]
7. ["my" "neighbor"] (and y gets set to "is")
8. [ "neighbor"] (and z gets set to "my")
|
canterbury_cs
|
canterbury_cs_0000023
|
Which of the following parts of a process’ memory is the largest?
|
[
"The code area",
"The globals area",
"The heap",
"The stack"
] |
C
|
Heap is the largest.
|
canterbury_cs
|
canterbury_cs_0000024
|
Prim’s Algorithm is used to solve what problem?
|
[
"Finding the lowest parent of a heap",
"Minimum spanning tree",
"Shortest path in a graph from a source",
"Sorting integers"
] |
B
|
Prim's is used for MST.
|
canterbury_cs
|
canterbury_cs_0000025
|
Suppose you have a tree with a maximum depth of d and an average branching factor of b (i.e. each node has b children). You are searching for a particular node S located at depth m (m <= d). You don't know where the node S is located, just that it is at depth m.
What is an upper bound on the <em>space</em> complexity of breadth-first search (i.e. big-O notation) to find the node S starting from the root?
|
[
"O(d * b)",
"O(b<sup>d</sup>)",
"O(d<sup>b</sup>)",
"O(b * m)"
] |
B
|
In the worst case, we need to store all of the nodes, because the very last node we check at the maximum depth will be S. The deepest nodes of the graph will have O(b<sup>d</sup>) nodes, and in the worst case we would need to store all of these nodes.
<img src="img/7.png" alt="" width="579" height="436">
|
canterbury_cs
|
canterbury_cs_0000026
|
Which of the following abstract datatypes would be the best choice for part of the implementation of the back button on a Web browser?
|
[
"a Stack ",
"a Queue",
"a Priority Queue ",
"a List "
] |
A
|
When you click on the back button, you should see the last page you visited, so the datatype that stores the previously visited webpages must be last-in-first-out. Of the abstract datatypes listed, Stack is the only one that is last-in-first-out.
|
canterbury_cs
|
canterbury_cs_0000027
|
Which of the following abstract datatypes would be the best choice for part of the implementation of a program modeling the arrival of patients to an emergency room in a hospital?
|
[
"a Stack",
"a Queue",
"A List",
"a PriorityQueue"
] |
D
|
In an emergency room, you want to serve patients in the order of how urgent their condition is, and if two patients have equally urgent conditions, in the order that they arrived. A PriorityQueue is the only abstract datatype listed that meets both of these conditions.
|
canterbury_cs
|
canterbury_cs_0000028
|
Two algorithms accomplish the same task on a collection of N items. Algorithm A performs N/2 operations. Algorithm B performs N log N operations. Under what conditions does algorithm A offer better performance?
|
[
"N <= 4",
"N > 8",
"N > 2",
"For all N."
] |
D
|
For all legal collection sizes, N/2 < N log N.
|
canterbury_cs
|
canterbury_cs_0000029
|
When is an adjacency matrix a good choice for implementing a graph?
|
[
"When the graph is undirected.",
"When the graph is nearly complete.",
"When a graph has few edges.",
"When the graph contains no cycles."
] |
B
|
The adjacency matrix will compactly and efficiently store edges when it contains little wasted space. In a complete graph, each vertex shares an edge with each other vertex, meaning all elements in the adjacency matrix will be used.
|
canterbury_cs
|
canterbury_cs_0000030
|
What is true about the pivot in quicksort?
|
[
"Before partitioning, it is always the smallest element in the list",
"After partitioning, the pivot will always be in the centre of the list",
"After partitioning, the pivot will never move again",
"A random choice of pivot is always the optimal choice, regardless of input"
] |
C
|
As the pivot will be to the right of all smaller elements and to the left of all larger elements, it is in the same position it will be when the array is sorted.
|
canterbury_cs
|
canterbury_cs_0000031
|
When is an adjacency list a good choice for implementing a graph?
|
[
"When the graph is undirected.",
"When the graph is nearly complete.",
"When a graph has few edges.",
"When the graph contains no cycles."
] |
C
|
With adjacency lists are used, each vertex stores its own list of vertices it's connected to. When a graph contains few edges, these lists will be very short and will likely consume less memory than the adjacency matrix.
|
canterbury_cs
|
canterbury_cs_0000032
|
You've got an algorithm that is O(N<sup>2</sup>). On the first run, you feed it a collection of size M. On the second run, you feed it a collection of size M / 2. Assuming each run has worst-case performance, how much time does the second run take?<span style="font-size: small;"><br></span>
|
[
"1/4 of the first",
"1/2 of the first",
"2/3 of the first",
"3/4 of the first"
] |
A
|
The first run took time proportional to M<sup>2</sup>. The second run took (M/2)<sup>2</sup>, or M<sup>2</sup>/4. The second run is 1/4 of the first.
|
canterbury_cs
|
canterbury_cs_0000033
|
Two algorithms accomplish the same task on a collection of N items. Algorithm A performs N<sup>2</sup> operations. Algorithm B performs 10N operations. Under what conditions does algorithm A offer better performance?
|
[
"N < 10",
"N < 100",
"N > 10",
"For all N."
] |
A
|
The two algorithms offer equal performance when N = 10. For N greater than 10, N<sup>2</sup> > 10N.
|
canterbury_cs
|
canterbury_cs_0000034
|
<pre lang="text/x-java">1. public BallPanel extends javax.swing.JPanel {
2. private Ball[] _balls;
3. public BallPanel(int numberOfBalls){
4. ??????
5. for (int i=0;i<_balls.length;i++)
6. _balls[i] = new Ball();
7. }
8. }
</pre>
We need to add something at line 4 above to avoid an error in line 5. Which of the following line 4 expressions fix the error in line 5?
|
[
"<code>super();</code>",
"<code>_balls.setLength(numberOfBalls);</code>",
"<code>_balls = new Ball[numberOfBalls];</code>",
" <code>_balls.length = numberOfBalls;</code>"
] |
C
|
The problem with line 5 (without adding line 4) is that _balls is declared, but not instantiated as an array, so _balls is null. The code compiles fine (assuming you have a class Ball that has a constructor with no parameters), but will crash at run time if you instantiate a BallPanel.
B and D wouldn't help: B would crash at run time for the same reason as 5, and D gives a compile-time error since length is not directly settable for a Java array. A would work, but would have no effect on the problem.
|
canterbury_cs
|
canterbury_cs_0000035
|
Which of the following makes an appropriate pre-condition for this code?<br>double calculate_percentage(double sum, double n)<br><code>{</code>
<pre lang="text/x-c"> // calculates and returns a percentage given a sum and a length (n)
// <missing pre-condition>
// POST: none
return (sum / n) * 100;
}
</pre>
|
[
"PRE: sum < 100",
"PRE: n != 0",
"PRE: sum != NULL and n != NULL",
"PRE: none"
] |
B
|
The code will faill if n = 0, as it will divide by 0.
|
canterbury_cs
|
canterbury_cs_0000036
|
Consider writing a program to be used by a farm to keep track of information about the fruits and vegetables they sell. For each sale, they would like to keep track of the type of item (eggplant, tomato, etc.), the quantity sold, the price, and the market at which the sale was made. Which of the following is the best way to represent the information?
|
[
"Define one class, <code>FarmSale</code>, with four fields: <code>type<span style=\"font-family: arial, helvetica, sans-serif;\">,</span></code> quantity<span style=\"font-family: arial, helvetica, sans-serif;\">, price<span style=\"font-family: arial, helvetica, sans-serif;\">, and market.</span></span>",
"Define one superclass, <code>FarmSale</code>, with four subclasses: <code>Type</code>, <code>Quantity</code>, <code>Price</code>, and <code>Market</code>.",
"Define five unrelated classes: <code>FarmSale</code>, <code>Type</code>, <code>Quantity</code>, <code>Price</code>, and <code>Market</code>.",
"Define five classes: <code>FarmSale</code>, <code>Type</code>, <code>Quantity</code>, <code>Price</code>, and <code>Market</code>.. Make <code>Market</code> a subclass of <code>Price</code>, make <code>Price</code> a subclass of <code>Quantity</code>, make <code>Quantity</code> a subclass of <code>Type</code>, and make <code>Type</code> a subclass of <code>FarmSale</code>."
] |
A
|
Which classes you define depends generally on the needs of the software. It might be good to have <code>Market</code> be a class of its own, with the address of the market, contact information for the organizers, etc. The item type might be modeled with a <code>Product</code> class, with information about the date it was planted, for example.
But of the choices given, A is the best. We can rule out choices B, C, D, and E because price and quantity don't need data and associated methods of their own and are most appropriately modeled as fields in the <code>FarmSale</code> class. That leaves A.
|
canterbury_cs
|
canterbury_cs_0000037
|
Suppose you are writing a Java program to be used to manage information about the inventory in a store. The store’s products include pagers, cell phones, and cameras. The cell phones are used for both communication and taking pictures, the pagers are only used for communication, and the cameras are used for taking pictures.
Assume that a <code>Product</code> class has been defined. Which of the following is the best way to represent the remaining data?
|
[
"Define two subclasses of the <code>Product</code> class: <code>Communicator</code> and <code>PictureTaker</code>. Define two subclasses of the <code>Communicator</code> class: <code>Pager</code> and <code>CellPhone</code>; and define two subclasses of the <code>PictureTaker</code> class: <code>CellPhone</code> and <code>Camera</code>.",
"Define three subclasses of the <code>Product</code> class: <code>Pager</code>, <code>CellPhone</code> and <code>Camera</code>. Also define two interfaces: <code>Communicator</code> and <code>PictureTaker</code>. Define the <code>Pager</code> and <code>CellPhone</code> classes to implement the <code>Communicator</code> interface, and define the <code>CellPhone</code> and <code>Camera</code> classes to implement the <code>PictureTaker</code> interface.",
"Define five new classes, not related to the <code>Product</code> class: <code>Pager<span style=\"font-family: arial, helvetica, sans-serif;\">,</span></code> CellPhone<span style=\"font-family: arial, helvetica, sans-serif;\">, Camera<span style=\"font-family: arial, helvetica, sans-serif;\">, Communicator<span style=\"font-family: arial, helvetica, sans-serif;\">, and PictureTaker.</span></span></span>",
"Define five subclasses of the <code>Product</code> class: <code>Pager<span style=\"font-family: arial, helvetica, sans-serif;\">,</span></code> CellPhone<span style=\"font-family: arial, helvetica, sans-serif;\">, Camera<span style=\"font-family: arial, helvetica, sans-serif;\">, Communicator<span style=\"font-family: arial, helvetica, sans-serif;\">, and PictureTaker.</span></span></span>"
] |
B
|
Answer A is the easiest to rule out -- it gives <code>CellPhone</code> two superclasses, which is not permitted in Java.
C is not the best choice because it doesn't capture the relationships among the various items. D captures some of the relationships but not all (for example, it's missing the relationship between <code>PictureTaker </code>and <code>Camera</code>).
Answers B and E are very similar -- they focus on the question of which items should be modeled by interfaces and which by classes. B is a better choice for several reasons. Pagers, phones, and cameras all have both behaviors and data -- for example, the list of phone messages for a phone and the ability to take pictures for both phones and cameras -- while PictureTaker and Communicator correspond to behaviors. In addition, defining PictureTaker as an interface allows us to capture the fact that a cell phone is a product, a picture taker, *and* a communicator.
|
canterbury_cs
|
canterbury_cs_0000038
|
Consider the following short program, which does not meet all institutional coding standards:
void vCodeString(char szText[ ]); /* First line */
#include <stdio.h>
#include <string.h>
#define MAX_LEN 12
int main(void)
{
char szData[MAX_LEN];
printf("Enter some text to code: ");
scanf("%s", szData);
vCodeString(szData); /* Line 8 */
printf("Coded string is %s\n", szData);
}
void vCodeString(char szText[ ])
{
int i = -1;
while(szText[++i])
{
szText[i] += (char)2;
}
}
I would like to combine lines 8 and 9 into
printf("Coded string is %s\n", vCodeString(szData));
Unfortunately, this gives me a syntax error. Why?
|
[
"The parameter to vCodeString should be szText",
"vCodeString does not return a value.",
"The parameter to vCodeString should be shown as szData[ ].",
" printf can only match %s to a variable, not to a function."
] |
B
|
The printf function cannot take as a parameter a function which does not return a value
|
canterbury_cs
|
canterbury_cs_0000039
|
The binary value 11011101 when coverted into a decimal value from two's complement notation is:
|
[
"-35",
"35",
"221",
"-221"
] |
A
|
Conversion of negative numbers in two's complement into decimal requires a bit flip, followed by the binary addition of 1. This value is then interpreted as an unsigned binary value.
|
canterbury_cs
|
canterbury_cs_0000040
|
Note draft only topics and explanation tba
Consider the following short program:
#include <stdio.h>
void f1(void);
int a;
void main(void)
{
int b;
a = b = 1;
f1();
printf("%d %d", a, b);
}
void f1(void)
{
int b = 3;
a = b;
}
The output from the print statement will be:
|
[
"1 1",
"1 3",
"3 1",
"3 3"
] |
C
|
Explanation to be completed
|
canterbury_cs
|
canterbury_cs_0000041
|
Finding the minimum value in a complete and balanced binary search tree is
|
[
"O(1)",
"O(log N)",
"O(N)",
"O(N<sup>2</sup>)"
] |
B
|
The minimum is the root's left-most descendent, which can be reached in log N steps.
|
canterbury_cs
|
canterbury_cs_0000042
|
An interface in Java can appropriately be used to model
|
[
"Abstract classes",
"Unrelated classes that share particular capabilities",
"Related classes that share particular attributes",
"Classes that communicate using the same network protocol"
] |
B
|
Interfaces allow us to specify common capabilities in unrelated classes: a way to say that two classes have the same methods without specifying the implementation (and allowing completely different implementations). For closely related classes (near each other in inheritance hierarchy) we can get common capabilities by having them in a common ancestor. Abstract classes provide a method to specify common capabilities via inheritance. Interfaces cannot be used to specify that two classes share a set of attributes (i.e. instance variables), which can be done by having classes inherit from a common ancestor with those attributes.
|
canterbury_cs
|
canterbury_cs_0000043
|
Suppose you are defining a Java <code>ProductItem</code> class to store information about the inventory in a store, and you want to give the class an instance variable for the number of those items currently in stock. Choose the best datatype for modeling this number:
|
[
"<code>double</code>",
"<code>float</code>",
"<code>int</code>",
"a user-defined <code>NumberInStock</code> class"
] |
C
|
A and B are wrong because you want to model an integer, not a floating point number.
E is wrong because you probably want to use this number for adding and subtracting, not just for display.
D is less good than C, because the built-in operations on ints will most likely be sufficient for the purposes of this variable.
|
canterbury_cs
|
canterbury_cs_0000044
|
Suppose you have a tree with a maximum depth of d and an average branching factor of b (i.e. each node has b children). You are searching for a particular node S located at depth m (m <= d). You don't know where the node S is located, just that it is at depth m.
What is an upper bound on the runtime complexity of breadth-first search (i.e. big-O notation) to find the node S starting from the root?
|
[
"O(d * b)",
"O(b<sup>d</sup>)",
"O(d<sup>b</sup>)",
"O(b * m)"
] |
B
|
In the worst-case, you would keep choosing sub-tree containing S last, and have to keep searching. Thus the worst-case is O(b<sup>d</sup>).
The following picture may help:
<img src="img/9.png" alt="" width="579" height="436">
|
canterbury_cs
|
canterbury_cs_0000045
|
What wil the following code print, assuming that N is a positive integer?
<pre lang="text/x-java">int count=0;
for (int i=0; i<<strong>N</strong>; i++) {
if (i % 2 == 0) {
count++;
}
}
System.out.println(count);
</pre>
|
[
"N",
"N/2",
"N/2+1",
"(N+1)/2"
] |
D
|
If N is even, for example N=12, N/2 works. However, suppose N is odd, for example N=13. Here the result should be 7, which is (N+1)/2. However, for N=12, (N+1)/2 also works. (N+1)/2 works for all positive integer.
|
canterbury_cs
|
canterbury_cs_0000046
|
Two algorithms accomplish the same task on a collection of N items. Algorithm A performs (N/2)<sup>3</sup> operations. Algorithm B performs N<sup>2</sup> operations. Under what conditions does algorithm A offer strictly better performance?
|
[
"N <= 7",
"N <= 8",
"N > 8",
"For all N"
] |
A
|
For N <= 7, (N/2)<sup>3</sup> < N<sup>2</sup>.
|
canterbury_cs
|
canterbury_cs_0000047
|
Identify the bug in the following Java code (if any):
<br><code>public boolean search(T item,ListADT<T> list){ // 1</code>
<pre lang="text/x-java"> if (list == null) // 2
return false; // 3
else if (list.first()==item) // 4
return true; // 5
else // 6
return this.search(item, list.rest()); // 7
} // 8
</pre>
|
[
"There is no base case",
"The problem is not self-similar",
"The problem does not get smaller",
"There are no bugs"
] |
D
|
For a recursive solution to a problem, you need three things:<br>(1) a base case (where the problem can be solved without recursion)<br>(2) a self-similar problem (one that contains similar problem(s) to itself)<br>(3) a way of making the problem smaller so you get closer to the base case
Here (2) is satisfied -- lists contain smaller lists. (1) is satisfied by lines 2-5 of the method. And (3) is satisfied because line 7's recursive call takes the rest of the list as a parameter, rather than the whole list.
|
canterbury_cs
|
canterbury_cs_0000048
|
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)",
"O(log<sub>2</sub> n)",
"O(n)",
"O(n<sup>2</sup>)"
] |
A
|
If you keep a pointer to the last element of the queue, then the enqueue method just needs a fixed number of statements, which are the same independent of the size of the queue.
|
canterbury_cs
|
canterbury_cs_0000049
|
What terminates a failed linear probe in a full hashtable?
|
[
"Revisiting the original hash index",
"A deleted node",
"A node with a non-matching key",
"A null entry"
] |
A
|
A null entry will not appear in a full hashtable. Seeing the end of the array isn't correct, since we need to examine all elements, including those that appear before our original hash index. A node with a non-matching key is what started our probe in the first place. The purpose of leaving a deleted node in the table is so that probing may proceed past it. Revisiting the original hash index means we've looked at every entry and determined the item doesn't appear in the table.
|
canterbury_cs
|
canterbury_cs_0000050
|
Which of the following assertions is <em>incorrect</em>?
|
[
"A Python statement may return a value",
"A Python expression may return a value",
"A Python statement may produce a side effect",
"A Python expression may produce a side effect"
] |
A
|
Basically, a statement in Python is a special kind of function that doesn't return a value. Statements are things like <code>print</code> (in Python 2.x but not Python 3) and <code>import</code>.
I think this is not a great question to put on a CS-1 exam beacuse it relies on terminology (statement, expression, side-effect) that doesn't really mean much until CS-2 or later.
|
canterbury_cs
|
canterbury_cs_0000051
|
What is<strong> not</strong> a property of a max-heap?
|
[
"It is complete",
"A node’s value is less than or equal to that of its parent",
"Its values are sorted in when printed in level order",
"Its root is the maximum element in the tree"
] |
C
|
A max-heap need not be sorted.
|
canterbury_cs
|
canterbury_cs_0000052
|
Barack Obama wants to know the most efficient way to sort a million 32-bit integers. He knows it’s not bubble sort. What is?
|
[
"Heapsort",
"Insertion sort",
"Mergesort",
"Radix sort"
] |
D
|
Radix sort will be O(n) and works nicely on integers; at such a large scale it will outperform the O(nlgn) sorting algorithms.
(question is a reference to http://www.youtube.com/watch?v=k4RRi_ntQc8 )
|
canterbury_cs
|
canterbury_cs_0000053
|
Read the following method skeleton and choose the best expression to fill in the blank on <strong>line 2</strong> so that the method will behave correctly:
<pre lang="text/x-java">/**
* Takes a string reference and counts the number of times
* the character 'A' or 'a' appears in the string object.
* @param aString String reference to object containing chars.
* @precondition aString is not null (you may assume this is true).
* @return The number of times 'A' or 'a' appears in the string.
*/
public static int countAs(String aString) // line 1
{
int counter = __________; // line 2
int totalA = 0; // line 3
while (counter < __________) // line 4
{
if ( __________.equals("A") ) // line 5
{
totalA = totalA + __________; // line 6
}
counter++; // line 7
}
return __________; // line 8
}
</pre>
|
[
"0",
"1",
"aString.size()",
"aString.length"
] |
A
|
This method must examine each character in the given string to see if it is 'A' or 'a', and uses a loop to do so. The variable <code>counter</code> is being used as a loop index, and by imagining what will fill in other blanks, is also being used to keep track of the position of the current character in the string that is being examined. Since line 7 methodically increases <code>counter</code> on each loop iteration, it must be traversing left-to-right through the string, so zero is the best choice for its initial value.
|
canterbury_cs
|
canterbury_cs_0000054
|
You are writing a depth-first search on a platform that doesn't support recursion. What data structure can help you complete your task?
|
[
"stack",
"queue",
"priority queue",
"hashtable"
] |
A
|
As you visit nodes, if you push their neighbors on a stack, the neighbors will be the first popped off when you need to backtrack. This behavior is what makes a depth-first search depth-first.
|
canterbury_cs
|
canterbury_cs_0000055
|
The worst-case time complexity of radix sort is:
|
[
"O(1)",
"O(n)",
"O(k n)",
"O(n<sup>2</sup>)"
] |
C
|
n is the number of items to be sorted, as usual, and k is the number of digits in the largest number in the list. Radix sort processes the entire list (n numbers) once for each of the k digits in the largest number in the list, so the work done is proportional to n*k.
|
canterbury_cs
|
canterbury_cs_0000056
|
A chained hash table has an array size of 512. What is the maximum number of entries that can be placed in the table?
|
[
"1024",
"512",
"There is no maximum.",
"511"
] |
C
|
In a hashtable with chaining, each element is assigned to a particular cell in the array (a "bucket") using the hash function. Each bucket has a pointer to the start of a linked list, and the elements assigned to that bucket are stored in the linked list.
|
canterbury_cs
|
canterbury_cs_0000057
|
Read the following method skeleton and choose the best expression to fill in the blank on <strong>line 6</strong> so that the method will behave correctly:
<pre lang="text/x-java">/**
* Takes a string reference and counts the number of times
* the character 'A' or 'a' appears in the string object.
* @param aString String reference to object containing chars.
* @precondition aString is not null (you may assume this is true).
* @return The number of times 'A' or 'a' appears in the string.
*/
public static int countAs(String aString) // line 1
{
int counter = __________; // line 2
int totalA = 0; // line 3
while (counter < __________) // line 4
{
if ( __________.equals("A") ) // line 5
{
totalA = totalA + __________; // line 6
}
counter++; // line 7
}
return __________; // line 8
}
</pre>
|
[
"0",
"1",
"<code>counter</code>",
"<code>aString.length()</code>"
] |
B
|
The variable <code>totalA</code> is being used as an accumulator to keep track of how many A's have been seen so far as the loop progresses. The if condition inside the loop is intended to detect whether the current character is an "A", and so the variable <code>totalA</code> should be incremented each time the condition is true. Therefore, the best answer for Line 6 is 1, so that <code>totalA</code> is incremented.
|
canterbury_cs
|
canterbury_cs_0000058
|
The following code for a method "minVal" contains a logic error on a single line in the method body, on one of the four lines indicated by comments:<br><br><code>public static int minVal(int[] y, int first, int last) {</code>
<pre lang="text/x-java">/* This method returns the value of the minimum element in the
* subsection of the array "y", starting at position
* "first" and ending at position "last".
*/
int bestSoFar = y[first]; // line 1
for (int i=first+1; i<=last; i++)
{
if ( y[i] < y[bestSoFar] ) // line 2
</pre>
<code> bestSoFar = y[i]; // line 3</code><br><br><code> } // for</code><br><br><code> return bestSoFar; // line 4</code><br><br><code>} // method minVal</code><br><br><br>Which one of the four lines indicated by the comments contains the logic error?
|
[
"line 1",
"line2",
"line3",
"line4"
] |
B
|
line 2 should be<code> if ( y[i] < bestSoFar )</code>
<span style="font-family: arial,helvetica,sans-serif;">The other three lines use bestSoFar to remember the best VALUE seen thus far, whereas the buggy line is using bestSoFar as if bestSoFar contains the POSITION seen thus far.</span>
|
canterbury_cs
|
canterbury_cs_0000059
|
What is the size of the largest max-heap which is also a BST?
|
[
"2",
"1",
"4",
"3"
] |
A
|
You can have a left child of the root, but as soon as you add the right child, it falls apart.
|
canterbury_cs
|
canterbury_cs_0000060
|
The following code for a method "minVal" contains a logic error on a single line in the method body, on one of the four lines indicated by comments:<br><br><code>public static int minVal(int[] y, int first, int last) {</code>
<pre lang="text/x-java">/* This method returns the value of the minimum element in the
* subsection of the array "y", starting at position
* "first" and ending at position "last".
*/
int bestSoFar = y[first]; // line 1
for (int i=first+1; i<=last; i++)
{
if ( y[i] < bestSoFar ) // line 2
</pre>
<code> bestSoFar = i; // line 3</code><br><br><code> } // for</code><br><br><code> return bestSoFar; // line 4</code><br><br><code>} // method minVal</code><br><br>Which one of the four lines indicated by the comments contains the logic error?
|
[
"line 1",
"line2",
"line3",
"line4"
] |
C
|
line 3 should be <code>bestSoFar = y[i];</code>
<code>The buggy code is remembering an array position, but the correct code remembers the value.</code>
|
canterbury_cs
|
canterbury_cs_0000061
|
How many objects and object reference would we have if the following code is executed?
Student first_st = new Student();
Student second_st = new Student();
Student third_st = second_st;
|
[
"3, 2",
"2, 3",
"2, 2",
"3, 3"
] |
B
|
2, 2
|
canterbury_cs
|
canterbury_cs_0000062
|
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?
|
[
"3",
"4",
"5",
"6"
] |
C
|
7, 4, 9, 24, and 1 will be found if searched for. 15 and 3 will not, since they lie to the wrong side of a subrange's midpoint.
|
canterbury_cs
|
canterbury_cs_0000063
|
How many number will be printed if n = 5?
public static void cSeries(int n) {
System.out.print(n + " ");
if (n == 1) return;
if (n % 2 == 0) cSeries(n / 2);
else cSeries(3*n + 1);
}
|
[
"3",
"4",
"5",
"6"
] |
D
|
5
|
canterbury_cs
|
canterbury_cs_0000064
|
For Club Scripting, to be a member a person must be aged 15 or older, but less than<br>50. What values would you use to boundary test a script designed to check if a<br>person was a suitable age to join?
|
[
"14, 15, 50, 51",
"15, 16, 50, 51",
"<br>15, 16, 49, 50",
"<br>14, 15, 49, 50"
] |
D
|
The boundary values are those at the boundary and those respectively one before and one past the boundary
|
canterbury_cs
|
canterbury_cs_0000065
|
Read the following method skeleton and choose the best expression to fill in the blank on <strong>line 5</strong> so that the method will behave correctly:
<pre lang="text/x-java">/**
* Takes a string reference and counts the number of times
* the character 'A' or 'a' appears in the string object.
* @param aString String reference to object containing chars.
* @precondition aString is not null (you may assume this is true).
* @return The number of times 'A' or 'a' appears in the string.
*/
public static int countAs(String aString) // line 1
{
int counter = __________; // line 2
int totalA = 0; // line 3
while (counter < __________) // line 4
{
if ( __________.equals("A") ) // line 5
{
totalA = totalA + __________; // line 6
}
counter++; // line 7
}
return __________; // line 8
}
</pre>
|
[
"<code>aString.substring(counter, counter + 1).toUpperCase()</code>",
"<code>aString.substring(counter).toUpperCase()</code>",
"<code>aString.substring(counter)</code>",
"<code>aString.charAt(counter).toUpperCase()</code>"
] |
A
|
While both <code>charAt()</code> can be used to examine a single <code>char</code> in a string, <code>char</code> is a primitive type without any methods. Since the condition on Line 5 uses the <code>equals()</code> method to compare against another String value, the expression used to fill in the blank must produce a String object, so the <code>substring()</code> method is a better fit. The <code>substring()</code> method takes two parameters--a starting index and an ending index one past the end of the substring--and since the method counts both upper case and lower case A's, the result should be converted to upper case form before testing for equality against <code>"A"</code>. Thus, the best answer is <code>aString.substring(counter, counter + 1).toUpperCase()</code>.
|
canterbury_cs
|
canterbury_cs_0000066
|
You need to traverse a singly-linked list in reverse. What's the best worst-case performance you can achieve?
|
[
"O(1)",
"O(log N)",
"O(N)",
"O(N log N)"
] |
C
|
Iterate through the list in the forward direction, but prepend each node on a second list as you do. Then iterate through the second list, which will be in the desired reverse order and traversable in O(N) time.
|
canterbury_cs
|
canterbury_cs_0000067
|
Which data structure can be used to implement an abstract datatype such as the StackADT or QueueADT?
|
[
"an array",
"a linked list",
"both",
"neither"
] |
C
|
StackADT and QueueADT can both be implemented with either an array or a stack. Either may be the better choice, depending on the purpose of the program and the nature of the data being stored.
|
canterbury_cs
|
canterbury_cs_0000068
|
How many objects are created in the following declaration?
String[] names = new String[10];
|
[
"0",
"1",
"10",
"11"
] |
B
|
None of the above
|
canterbury_cs
|
canterbury_cs_0000069
|
We say indexing is fast if it's done in O(1) time, searching is fast if done in O(lg N) time, and inserting and deleting are fast if done in O(1) time. Compared to other data structures, unsorted linked lists offer:
|
[
"slow indexing, slow search, slow insertions and deletions.",
"fast indexing, fast search, slow insertions and deletions.",
"fast indexing, slow search, slow insertions and deletions.",
"slow indexing, slow search, fast insertions and deletions."
] |
D
|
Linked lists do not support fast indexing. To get at element i, one must traverse the list i steps. Slow indexing makes for slow searching, as the binary search relies upon fast indexing to retrieve the middle element. Insertions and deletions, on the other hand, can be done in constant time, as only one or two neighboring links are affected.
|
canterbury_cs
|
canterbury_cs_0000070
|
Consider the following code snippet that copies elements (pixels) from one 2-d array (called pict), with maximum dimensions of maxWidth and maxHeight into another 2-d array called canvas.
canvas = [][]<br>for row in range (0, maxHeight):<br> for col in range (0, maxWidth):<br> origPixel = pict[col][row]<br> canvas[width-1-col][row = origPixel
If one were to display canvas, how would it compare to the orignal picture (as represented by pict)?
|
[
"Rotated 180 degrees around the vertical center line/column.",
"Rotated 180 degrees around the horizontal center line/row.",
"Rotated left 90 degrees.",
"Rotated right 90 degrees."
] |
A
|
Each pixel remains on the same row (line) that it originally was on. For any given row, the leftmost pixel swaps positions with the rightmost. The second pixel in a row swaps positions with the second last pixel in that row, etc. Hence, the picture is rotated across the vertical center line.
|
canterbury_cs
|
canterbury_cs_0000071
|
An example of something that could be built using a QueueADT is a structure that models:
|
[
"The undo operation in a word processor",
"the back button in a web browser",
"the customers waiting to talk to an online helpdesk",
"a hundred names in alphabetical order, where names are added and removed frequently"
] |
C
|
Choices A and B are applications where when you delete, you need to delete the item that was added most recently (a LIFO structure). This is not possible in a queue, where you always delete the item that was added *first*.
Choice D is an application where you need to be able to delete from the beginning, middle, or end of the structure, something that is also impossible in a queue.
Choice E is an application where a element (an intersection) could be connected to several other elements. This is also impossible in a queue.
Choice C is the only one where it makes sense to retrieve the elements in the order in which they arrived.
|
canterbury_cs
|
canterbury_cs_0000072
|
This sorting algorithm splits the collection into two halves, sorts the two halves independently, and combines the results.
|
[
"insertion sort",
"quick sort",
"bubble sort",
"merge sort"
] |
D
|
Merge sort splits the collection, sorts the two halves, and merges them.
|
canterbury_cs
|
canterbury_cs_0000073
|
Locating a new node's insertion point in a binary search tree stops when
|
[
"We reach a null child.",
"We find a node greater than the node to be inserted.",
"We reach the tree's maximum level.",
"We find a node lesser than the node to be inserted."
] |
A
|
Finding nodes less than or greater than the new node happens frequently as we traverse the tree. Tree's don't have maximum levels. The insertion point isn't necessarily a leaf node. The remaining option of stopping when we reach null is the correct answer because we have found the new node's parent node.
|
canterbury_cs
|
canterbury_cs_0000074
|
What are hash functions<strong> not</strong> used for? (Or at least, should not be used for.)
|
[
"Storing values in hash tables",
"Checking file integrity",
"Encrypting passwords",
"Digital signatures on files"
] |
C
|
Hash functions should be used to store passwords, but not to encrypt them!
|
canterbury_cs
|
canterbury_cs_0000075
|
How many objects are created in the following declaration?
<code>String name;</code>
|
[
"0",
"1",
"This declaration causes a run-time error",
"It is not legal to write this declaration in Java"
] |
A
|
It is not legal to write this declaration in Java
|
canterbury_cs
|
canterbury_cs_0000076
|
Nathan is on the run (apparently the US is about to invade Canada). He needs to grab food.<br>Each piece of food around him has a nutritional value, and a weight. He wants to put the<br>most calories in his backpack, but it can only hold up to certain weight. What should he<br>optimize for when deciding which foods to bring?
|
[
"The value of food",
"The value / weight ratio of food",
"The weight / value ratio of food",
"The weight of food"
] |
B
|
Greedy approach to fractional knapsack.
|
canterbury_cs
|
canterbury_cs_0000077
|
Suppose you are defining a Java <code>ProductItem</code> class to store information about the inventory in a store, and you want to give the class an instance variable for the price of that item. Which of the following is the best datatype for the instance variable that models the price?
|
[
"<code>String</code>",
"<code>float</code>",
"<code>int</code>",
"a user-defined <code>Money</code> class"
] |
D
|
Arguments can be made for any of these choices (except perhaps "int"). I would give <code>Money</code> an edge, because a user-defined class allows you to write methods to display the value properly, do arithmetic on it, and perhaps convert it to different currencies. But I'm going to tag this as a question with more than one answer.
|
canterbury_cs
|
canterbury_cs_0000078
|
<pre lang="text/x-java">1.public class FirstApp extends wheels.users.Frame {
2. private wheels.users.Ellipse _ellipse;
3.
4. public FirstApp() {
5. _ellipse = new wheels.users.Ellipse();
6. }
7.
8. public static void main(String[] args) {
9. FirstApp app = new FirstApp();
10. }
11.}
</pre>
What does line 2 accomplish (cause to happen)?
|
[
"<code>wheels.users.Ellipse</code> is given <code>_ellipse</code> as an alias",
"An invisible <code>Ellipse</code> is drawn on the screen",
"<code>_ellipse</code> is declared as a <code>wheels.users.Ellipse</code>",
"<code>wheels.users.Ellipse</code> is set to be a <code>private</code> object"
] |
C
|
Remember that in Java we need to declare variables, and then instantiate them (using new). Line 2 is simply a declaration -- the variable gets instantiated (in line 5) when a FirstApp gets instantiated.
|
canterbury_cs
|
canterbury_cs_0000079
|
We say indexing is fast if it's done in O(1) time, searching is fast if done in O(lg N) time, and inserting and deleting are fast if done in O(1) time. Compared to other data structures, unsorted arrays offer:
|
[
"slow indexing, slow search, slow insertions and deletions.",
"fast indexing, fast search, slow insertions and deletions.",
"fast indexing, slow search, slow insertions and deletions.",
"slow indexing, slow search, fast insertions and deletions."
] |
C
|
Unsorted arrays can be indexed in constant time (which is fast), searched in O(N) time (which is not as good as O(lg N)), and restructured in O(N) time (which is not as good as O(1) time).
|
canterbury_cs
|
canterbury_cs_0000080
|
One of the things in Java that allows us to use polymorphism is that the declared type and actual type of a variable may be different.
In Java, the actual type of a parameter or variable’s value can be any concrete class that is
|
[
"the same as the declared type, or any subclass of the declared type (if the declared type is a class)",
"any class that <code>implements</code> the declared type (if the declared type is an interface)",
"any subclass of a class that <code>implements</code> the declared type (if the declared type is an interface)",
"A, B, and C above."
] |
D
|
The rule of thumb is that the declared type is the same or more abstract than the actual type. If the declared type is a class, the things that are equally or less abstract are its descendants -- a subclass specializes a class. If declared type is an interface, it is an abstraction of any class that implements it, or by the relationship between classes and its descendants, any class that is a subclass of something that implements it.
Java wants a guarantee that the actual type will have the declared type's methods. That can be via inheritance or implementing an interface, or a combination of the two.
|
canterbury_cs
|
canterbury_cs_0000081
|
An example of something that could be implemented using a Stack is:
|
[
"The undo operation in Word",
"The back button in a web browser",
"A postfix calculator",
"All of the above"
] |
D
|
Anytime you're solving a problem where you're adding and removing data and you always need to remove the item that was added most recently is suited to a Stack. This is called a last-in-first-out property, or LIFO. Back buttons, the undo operation, and postfix calculators all have the last-in-first-out property.
|
canterbury_cs
|
canterbury_cs_0000082
|
Suppose you are writing software for a helpdesk. Each request is entered into the system as it arrives.
Which of the following abstract datatypes would be the best choice to ensure that the requests are handled in exactly the same order in which they arrive?
|
[
"A Stack",
"A Queue",
"A List",
"A PriorityQueue"
] |
B
|
A Queue is the only abstract datatype where elements are removed in exactly the same order that they arrived in.
|
canterbury_cs
|
canterbury_cs_0000083
|
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?
|
[
"DEBFCA",
"DBFACE",
"ACBEFD",
"DBACFE"
] |
C
|
DBACFE
|
canterbury_cs
|
canterbury_cs_0000084
|
What is not true about a binary search tree?
|
[
"It is a binary tree",
"It is a perfect tree",
"The leftmost node is the smallest node in the tree",
"When printed with inorder traversal, it will be sorted"
] |
B
|
BSTs need not be perfect.
|
canterbury_cs
|
canterbury_cs_0000085
|
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. ",
"Linked lists provide more efficient access to individual elements. ",
"A and B only"
] |
D
|
Array elements can be accessed in constant time, but access to an element of a linked list is O(n), so B is correct and C is incorrect. A is also correct, because arrays require you to guess how much memory will be needed and set aside a fixed amount, while linked lists use memory as needed for the data that are being stored. Since A and B are correct and C is not, the answer is D.
|
canterbury_cs
|
canterbury_cs_0000086
|
The insertion sort operates by maintaining a sorted list. When a new element is added, we traverse the list sequentially until will find the new element's appropriate location. Suppose instead that the new location was found using a binary search instead of a sequential search. What is the complexity of this new binary insertion sort?
|
[
"O(N<sup>2</sup>)",
"O(log N)",
"O(N * log N)",
"O(N + log N)"
] |
A
|
The binary search will indeed speed up finding the location of the newly added object. However, we still have the problem of shifting all subsequent elements. This algorithm, like the regular insertion sort, is O(N<sup>2</sup>).
|
canterbury_cs
|
canterbury_cs_0000087
|
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?
|
[
"5",
"0",
"1",
"2"
] |
C
|
Only the middle element will be found. The remaining elements will not be contained in the subranges that we narrow our search to.
|
canterbury_cs
|
canterbury_cs_0000088
|
Which data structure used to implement <code>Set</code> yields the worst performance for <code>Set.contains</code>?
|
[
"Binary search tree",
"Linked list",
"Sorted array",
"Hashtable"
] |
B
|
Implementing Set.contains involves a search of the data structure. A binary search tree and a sorted array are searched in O(lg n) time, and a hashtable in O(1), assuming a sane hash function. A linked list is searched in O(n) time.
|
canterbury_cs
|
canterbury_cs_0000089
|
For a graph with N nodes, what's the minimum number of edges it must have for it to contain a cycle?
|
[
"N + 1",
"N",
"N - 1",
"1"
] |
D
|
A vertex with an edge to itself is a cycle.
|
canterbury_cs
|
canterbury_cs_0000090
|
Read the following method skeleton and choose the best expression to fill in the blank on <strong>line 8</strong> so that the method will behave correctly:
<pre lang="text/x-java">/**
* Takes a string reference and counts the number of times
* the character 'A' or 'a' appears in the string object.
* @param aString String reference to object containing chars.
* @precondition aString is not null (you may assume this is true).
* @return The number of times 'A' or 'a' appears in the string.
*/
public static int countAs(String aString) // line 1
{
int counter = __________; // line 2
int totalA = 0; // line 3
while (counter < __________) // line 4
{
if ( __________.equals("A") ) // line 5
{
totalA = totalA + __________; // line 6
}
counter++; // line 7
}
return __________; // line 8
}
</pre>
|
[
"<code>counter</code>",
"<code>true</code>",
"<code>false</code>",
"<code>totalA</code>"
] |
D
|
The return type of the method is <code>int</code>, so an integer return value must be provided. Since <code>counter</code> is used as a loop index, it will always end up being the total number of characters in the given string. The variable <code>totalA</code> is used as an accumulator that is incremented each time a letter A is found in the string, so it is the choice that will provide the correct return value for the method.
|
canterbury_cs
|
canterbury_cs_0000091
|
Two algorithms accomplish the same task on a collection of N items. Algorithm A performs log<sub>2</sub> N operations. Algorithm B performs log<sub>3</sub> N operations. Under what conditions does algorithm A offer better performance?
|
[
"For no N.",
"N < log<sub>2</sub> 3",
"N < log<sub>3</sub> 2",
"N < 8"
] |
A
|
For no possible collection size N is log<sub>2</sub> N < log3 N.
|
canterbury_cs
|
canterbury_cs_0000092
|
Finding the median value in a complete and balanced binary search tree is
|
[
"O(1)",
"O(log N)",
"O(N)",
"O(N<sup>2</sup>)"
] |
A
|
The median is the element that has M elements less than it and M elements greater than it. This can only be said of the root node in a complete and balanced binary tree. The root is accessed in constant time.
|
canterbury_cs
|
canterbury_cs_0000093
|
For a heap of size n, which is indexed at 0, at what position will its last child be?
|
[
"2n + 1",
"n / 2",
"n - 1",
"floor(n / 2) + 1"
] |
C
|
The last element will be at the end of the array.
|
canterbury_cs
|
canterbury_cs_0000094
|
What design stategy does Quicksort use?
|
[
"Greedy",
"Divide and conquer",
"Dynamic programming",
"Brute force"
] |
B
|
Quicksort is divide and conquer.
|
canterbury_cs
|
canterbury_cs_0000095
|
If you did not have a base case in a recursive function in C, and were working on a modern Unix-based system, what would most likely happen?
|
[
"Segmentation fault",
"Stack overflow error",
"C wouldn’t complain, but your computer would crash",
"Nothing, that’s fine"
] |
C
|
It really depends on the program for whether it would be B or C. Both can be argued to be correct.
|
canterbury_cs
|
canterbury_cs_0000096
|
The following Python method determines whether or not a list of values, passed in as a parameter, has any duplicate values.
What is the Big-Oh running time of this algorithm?
def duplicates(lov):
dupCount = 0<br> outer = 0<br> while (outer < len(lov)):<br> inner = outer + 1<br> while (inner < len(lov)):
if (lov[inner] == lov[outer]):
dupCount = dupCount + 1
inner = inner + 1
outer = outer + 1
if (dupCount == 0):<br> print "there are no duplicate values"<br> else:<br> print "there are ", dupCount, " duplicate values"
|
[
"O(1) ",
"O(n)",
"O(n log<sub>2</sub> n)",
"O(n<sup>2</sup>)"
] |
D
|
Each item in the list is compared against each other item in the list: a classic example of the<em> all-pairs</em> programming pattern. The first item is compared against n-1 other values. The second item is compared against n-2 other values, etc. The total number of comparisons is <img src="img/2.png" alt="" title="latex">
|
canterbury_cs
|
canterbury_cs_0000097
|
What is printed when the following program runs?
<pre lang="text/x-java">public class Main {
public static boolean getTrue() {
System.out.print("T");
return true;
}
public static boolean getFalse() {
System.out.print("F");
return false;
}
public static void main(String[] args) {
getTrue() || getTrue();
}
}
</pre>
|
[
"TT",
"T",
"F",
"TF"
] |
B
|
If the first operand for || is true, as is the case here, the second is not evaluated.
|
canterbury_cs
|
canterbury_cs_0000098
|
You are storing a complete binary tree in an array, with the root at index 0. At what index is node i's parent?
|
[
"(i - 1) / 2",
"i / 2 + 1",
"2i + 1",
"i + i + 2"
] |
A
|
(i - 1) / 2
|
canterbury_cs
|
canterbury_cs_0000099
|
Which of the following abstract datatypes would be the best choice for part of the implementation of the part of a compiler that determines whether the parentheses in a program are balanced?
|
[
"A Stack",
"A Queue",
"A List",
"A PriorityQueue"
] |
A
|
A close parenthesis must match the most recently entered open parenthesis. So for example, the sequence )()( doesn't match, while ()() and (()) do, even though they all have two open and two close parentheses. To make this work, you can push each open parenthesis on a Stack, and pop it off each time you see a close parenthesis. The last-in-first-out nature of a Stack makes it easy to determine whether the parentheses are balanced.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.