2013T2 Exam
2013T2 Exam
T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I
NOTE!!
THIS EXAMINATIONS – 2013
CONTAINS
SOLUTIONS
***** TRIMESTER 2
COMP 103
INTRODUCTION TO
DATA STRUCTURES
AND ALGORITHMS
Questions Marks
1. General questions [11]
2. Using collections [25]
3. Implementing a Collection [28]
4. Recursion and Sorting [16]
5. Linked Structures [22]
6. Trees [26]
7. Binary Search Trees [20]
8. Priority Queues and Heaps [20]
9. Various other questions [12]
SPARE PAGE FOR EXTRA ANSWERS
(a) [3 marks] A Queue differs from a Set in three main ways. What are these differences?
(b) [2 marks] What is a natural data structure to use, in order to reverse the order of items
in a collection?
Stack.
(c) [2 marks] What is wrong with using the length attribute of a String as its hash code?
(d) [2 marks] For a SortedArraySet, the complexity of contains() is O(log n). Why?
Being sorted, the Binary search algorithm can be used to FIND where the item is, or
should be.
(e) [2 marks] For a SortedArraySet, is the complexity of the remove operation the same as
for contains? Explain why or why not.
No it is not. Like contains, Removing starts with find, but we must then shift the
items above the removed one down, to keep the array continuous and sorted. So it’s
O(n) instead.
The figure below shows the first few rows of a pattern known as Pascal’s triangle, which has
many interesting mathematical properties. Each row is formed by summing 2 numbers from
the row above, except at the edges, where there’s a 1.
(b) [10 marks] Complete the method below, that constructs a Pascal’s Triangle with a certain
number of lines. It should take the number of lines as an argument, and should return the
Pascal’s Triangle as a List of Lists.
Your method should make use of the generateNextList() method described in (a).
(c) [5 marks] Complete the method below, which prints a Pascal’s triangle. For example,
when called as displayTriangleNums(6) it should generate the output shown below.
You should make use of the generateTriangleNums() method described in (b).
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
public void displayTriangleNums(int numlines){
The space agency NASA wants to send a probe into deep space, and the probe’s onboard
code uses Java arrays. Unfortunately cosmic rays occasionally corrupt the contents of these
arrays, changing their values at random. Since the mission has very high cost, NASA opts
to use an ArrayList implementation that is very robust: it will keep three arrays for a List
instead of the usual one.
Here is partial code for their RobustArrayList implementation of the List interface.
The questions will ask you to complete the code for the methods isEmpty, add, get and
ensureOneCapacity.
public RobustArrayList() {
data1 = (E []) new Object[INITIALCAPACITY];
data2 = (E []) new Object[INITIALCAPACITY];
data3 = (E []) new Object[INITIALCAPACITY];
}
:
:
:
// Other public methods (isEmpty, size , set , get , add, remove, etc ) would go here
:
:
:
(b) [8 marks] Complete the method get() for RobustArrayList. If the same value occurs
in any two of the three arrays, that value that should be returned. Otherwise the method
should return null.
ensureCapacity();
for ( int i =index+1; i<count; i++) data1[i ] = data1[i −1];
for ( int i =index+1; i<count; i++) data2[i ] = data2[i −1];
for ( int i =index+1; i<count; i++) data3[i ] = data3[i −1];
data1[index] = item;
data2[index] = item;
data3[index] = item;
count++;
return;
(d) [5 marks] Complete the method ensureOneCapacity(). If the array in the argument has
room, a reference to it can be returned. Otherwise the method should return a reference to a
new array that is larger but contains the original items.
(e) [4 marks] The above used three arrays to store each List. Suppose NASA wanted to make
this even safer by allowing a mission-specific number of array copies to be maintained. The
number of arrays could be passed as an argument to a new constructor, like this:
(a) [4 marks] A method recHalf is supposed to print larger and larger chunks of a String
passed as an argument. For example, recHalf(“ABCDEFGH”) should print the following:
A
AB
ABCD
ABCDEFGH
(b) [2 marks] QuickSort is a much faster algorithm than InsertionSort in most circumstances.
However, there is one case in which InsertionSort will work faster: what is that case?
If the list is already almost sorted, InsertionSort will completely sort it in only about
n comparisons.
(c) [5 marks]
The figure on the right shows SelectionSort part of the way through the
sorting operation. The figure shows a snapshot of the whole array being
sorted, with the height of the dark bars representing the values of the
respective array cells.
Suppose there are 32 items in the whole array.
(d) [5 marks]
The figure on the right shows QuickSort part of the way through the sort-
ing operation. Again, suppose there are 32 items in the array being sorted.
Indicating your argument by words or a diagram, estimate
how many more item-to-item comparisons QuickSort will need to
carry out from this point onwards, for it to finish the sorting operation
completely.
For simplicity, you may assume that the pivot is almost always about half
way through the relevant segment being sorted.
Note: The snapshot shown here was not taken at the same stage as the one
for SelectionSort, so the number of steps to go is not necessarily going to
be lower than your answer for (c).
Splitting according to the pivot takes n operations for a segment that is n items long.
QuickSort has to do 2*16=32 of these. Each of THOSE has 2*8, ie 32 more. Each of
THOSE has 2*4, ie 32 more. Each of THOSE has 2*2, ie 32 more. Each of THOSE has
2*1, ie 32 more. So QuickSort has about 5*32 = 160 comparisons still to go.
As usual, an IntegerNode can be regarded as the head of a linked list that is terminated by a
null value in the next field of the last node in the list.
Your colleague Sam shows you the code he has drafted for a method to be added to the
IntegerNode class that is supposed to add up the numbers in a linked list of IntegerNodes,
at odd positions (i.e., 1, 3, 5, . . .), with the first node being at position 1.
public int skippy() {
int result = this.value;
return result ;
}
(a) [6 marks] There are several problems with his code. Very briefly point out all problems
you can identify.
(a) [8 marks] For each of the following four structures state which term – binary tree, binary
search tree, partially ordered binary tree, general tree, or not a tree – best describes it and
briefly justify your answer.
(b) [4 marks] Your colleague Sam has written the following method contains for class
GeneralTreeNode to check whether the subtree formed by the receiver contains the argu-
ment node:
public class GeneralTreeNode {
private String name;
...
Briefly point out any bugs you identify and suggest the correction required.
needs to return false at the end needs to check result of recursive ”contains” and
return if it is true.
(c) [3 marks] Briefly explain why it is easier to implement a method that removes a node for
class GeneralTreeNode compared to class BinarySearchTreeNode.
parent node can just accept all the children of the removed node A BST potentially
requires restructuring.
Consider the following (incomplete) binary search tree that stores integer values:
(a) [1 mark] Assuming the top node is referenced by root, what is the value of root.left().left().getValue()?
13
(b) [3 marks] Fill in the missing integer numbers into the blank nodes above.
(c) [2 marks] Write down the sequence of vales produced by a post-order traversal, assuming
values have been filled in as necessary.
(d) [2 marks] Briefly describe a method of returning the largest value stored in a binary
search tree without ever comparing two values with each other.
Start at the root and move down to the right as long as possible
(e) [2 marks] Your colleague Ben has implemented a remove method for a binary search tree
implementation. For some reason he did not follow the COMP 103 notes and hence does
not replace a node that has two children with the leftmost child of its right subtree. Instead
he replaces it with the rightmost child of its left subtree.
Briefly state your response to Ben’s design.
Ben, you are alright, bro. Whether you are using the in-order predecessor or the
in-order success does not matter.
(f) [10 marks] Consider the following implementation for a binary tree containing integers:
In the box below, complete a method “isBinarySearchTree” for this class. The method tests
whether a tree satisfies the conditions for being a binary search tree.
You may assume that the range of values contained only spans 1 − 99.
if ( left != null)
if (! left .isBinarySearchTree(min, value))
return false;
if ( right != null)
if (! right .isBinarySearchTree(value, max))
return false;
return true;
(a) [2 marks] Your colleague Pete has started to write an implementation of a generic Priori-
tyQueue class. He has required the element type to implement interface “Comparable”.
Briefly discuss whether his requirement is reasonable.
(b) [2 marks] Pete now suggests to extend class PriorityQueue with a constructor that accepts
a comparator object.
Do you think Pete’s suggestion is a good one? Justify your answer.
(c) [3 marks] Pete is excited about using a heap for his priority queue implementation. He
thinks he can use one of the four standard traversal strategies to traverse the underlying
partially ordered tree so that the elements are yielded in the order of descending priority.
Do you think Pete’s plan is going to work? Justify your answer.
(d) [3 marks] Pete wants to add a constructor to class PriorityQueue that takes a collection
of elements as an argument and populates the queue with them. Pete thinks he cannot beat
O(n log n) as the asymptotic complexity for this constructor.
Do you think Pete is right? Justify your response.
For Pete’s sake, have you forgotten about “heapify” and its O(n) complexity?
Pete is not sure whether his implementation is correct and asks you for help. He shows you
the following state of his priority queue which uses an internal array to store items in a heap.
In his implementation elements with larger values have higher priority.
(e) [5 marks] Provide Pete with the values after one poll() operation.
Count = 11, 55, 33, 31, 18, 22, 14, 11, 6, 9, 12, 15,
(a) [2 marks] It is possible to build and use linked lists by using no more than class LinkedNode.
Why does it make sense to also provide a class LinkedList?
clients do not have to deal with null values isEmpty() supported can support
“count” place for special cases natural place for invoking recursive methods on
linked nodes.
(b) [2 marks] Your colleague Sally suggests replacing your company’s current LinkedList-
based implementation of a Set data structure with a BinarySearchTree-based implementa-
tion.
What speed-up in terms of asymptotic complexity should Sally expect for the operation
“remove” in the average case?
O(n) → O(logn)
(c) [2 marks] What speed-up in terms of asymptotic complexity should Sally expect for the
operation “remove” in the worst-case and when would this worst-case occur?
(e) [2 marks] What approach would you use to efficiently print the hundred largest numbers
out of an unsorted collection of one billion elements?
(f) [2 marks] How would you determine whether two binary search trees contain the same
values?
***************
class Collections
public static void sort( List <E>)
public static void sort( List <E>, Comparator<E>)
public static void shuffle ( List <E>, Comparator<E>)
class Arrays
public static <E> void sort(E[ ] ar, Comparator<E> comp);
class Random
public int nextInt ( int n); // return a random integer between 0 and n−1
public double nextDouble(); // return a random double between 0.0 and 1.0
class String
public int length ()
public String substring( int beginIndex, int endIndex)
***************