0% found this document useful (0 votes)
42 views8 pages

CM20254 Exam 2020 Solution

Uploaded by

Yufan Ye
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views8 pages

CM20254 Exam 2020 Solution

Uploaded by

Yufan Ye
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

CM20254 Exam 2020 with Solution

7 easy Qs (6+3+6+2+6+6+6 = 35 marks)


7 intermediate Qs (5+3+3+6+4+5+4 = 30 marks)
6 hard Qs (6+6+5+6+6+6 = 35 marks)
Overall 20 Qs, 35+30+35 = 100 marks

Notes for students: Many questions have a word limit. If you write more words than
allowed for a question, then only the first words up to the limit can be marked.
Answer texts will be checked for plagiarism.

Q1 [Easy, 6 marks] Given the following class implementing a set of integers. Imagine
the parts marked with /* … */ contain correct implementations.

public class Set {


int n = 0; // size of set
int[] a = new int[100];

int size() { return n; }


void add(int x) { /* adds x to the Set */ }
void resize() { /* resizes the array used to store elements */ }
boolean isInSet(int x) { /* tests whether x is in the Set */ }
}

In order to make this class an abstract data type, which parts should be marked as
public and which parts as private? First list all the parts that are private and then all
the parts that are public by their name.

Answer:
Private: n, a, resize [3 marks]
Public: size, add, isInSet [3 marks]

Q2 [Easy, 3 marks] Given the following array of numbers: 1, 5, 10, 17, 20, 50, 70, 80,
90, 100. Which numbers would binary search consider when trying to find 10?
Assume that the algorithm rounds down the array index when determining the middle
element of a list. Name each number in the right order.

Answer: 20, 5,10


Q3 [Easy, 6 marks] Given the following functions:
f(n) = n! , g(n) = 101000 n log n , and h(n) = 10-1000 n1.7. For each pair of f, g, h, use
the O(…) notation to express the relationship between the functions in the pair (e.g. f
and g, f and h, …). Then, use the Ω(…) notation to express the relationships
between the functions in each of the pairs.

Answer (1 mark each):


g = O(f) f = Ω(g)
h = O(f) f = Ω(h)
g = O(h) h = Ω(g)

Q4 [Easy, 2 marks] Consider an algorithm that takes 20s to process an input of


n=80, 30s for n=160 and 40s for n=320. Which asymptotic complexity does it likely
have?

Answer:
ϴ(log n) (2 marks)

Q5 [Easy, 6 marks] Given a closed hashtable of size 7 with hash function h(k)=k%7
and linear probing in the direction of ascending indices, as discussed in the lectures.
How does the hashtable look like after inserting the numbers 1, 11, 99, 4, 6, 7, 100?
List the numbers in ascending order of the buckets’ indices.

Answer:
7, 1, 99, 100, 11, 4, 6 (1 mark for each except the last)

Q6 [Easy, 6 marks] Given the binary search tree illustrated in the image.

Assume the following operations are performed in the given order: remove 4, add 3,
add 6, remove 8, remove 7, remove 5. Assume the tree uses an element from the
left subtree if an element needs to be replaced in a remove operation. After these
operations, how will the tree look like? Briefly state what the root is and what the
children of each node are.

Answer (1 mark each):


Root 3 with children 2 and 6 (3 marks)
6 has right child 9 (3 marks)

Q7 [Easy, 6 marks] Consider the graph G in the image. Assume that we use
Dijkstra's algorithm to find shortest paths from node s to any other node in G. In
which order could Dijkstra's algorithm consider the nodes of G when computing the
shortest paths that start at s?

Answer:
s, 5, 3, 4, 1, 2 (1 mark per correctly ordered node)
s, 5, 4, 3, 1, 2 is also correct

Q8 [Intermediate, 5 marks] Assume there are two algorithms that could be used to
solve a given problem: a logarithmic one and a quadratic one. In practice, could it
sometimes be better to use the quadratic algorithm instead of the logarithmic one?
Explain your answer in two concise sentences, giving two reasons. The word limit is
60 words.

Answer (any two explanations out of three below work):


Yes (1 mark)
The quadratic algorithm could be faster for the expected size of the problem (small
n) due to very large coefficients or constants in the runtime function of the
logarithmic algorithm. (2 marks)
The runtime difference may not matter for the expected size of the problem (small n)
and the quadratic algorithm may be much easier to implement. (2 marks)
The quadratic algorithm may use a lot less memory, but still have an acceptable
runtime for the given application. (2 marks)
The quadratic algorithm may run faster specifically for certain desired inputs, or
avoid common worst cases of the other algorithm. (2 marks)

Q9 [Intermediate, 3 marks] Assume you are using an open hashtable of size 100.
You want find operations (i.e. finding a given key in the hashtable) to take no more
than 3 steps on average. According to the lecture, after inserting how many elements
would the hashtable need to be resized (just state the number)?
Answer:
400 (3 mark)
Workings (not marked): Average number of steps = 3 = 1 + L/2 => Load factor L = 4

Q10 [Intermediate, 3 marks] The runtime for the following code fragment is ϴ(f(m,n)).

for (int i=m/(2*2*2)*2; i>0; i--)


for (int j=0; j<1024*i; j++)
for (int k=1; k<n+10; k=2*k)
System.out.println("yay");

Specify f as concisely as possible.

Answer:
f(m,n)= m^2 * log n (3 marks)

Q11 [Intermediate, 6 marks] Imagine you are measuring the runtime of a method
call. Name three things you could do to improve accuracy and/or precision of the
measurement. For each thing, say what is improved (accuracy and/or precision) and
explain in one concise sentence (no more) how it is improved. The word limit is 60
words.

Answer (1 mark for accuracy/precision and one for how):


Improve precision by repeating and averaging over several measurements.
Improve precision by making sure nothing else is happening on the computer, e.g.
by warming up cache, initialising objects, shutting down other programs before
measuring.
Improve accuracy (and potentially precision) by using a timing method with good
resolution (e.g. nanoTime).
Improve accuracy by trying to keep overheads of measuring low, e.g. unroll loop
when measuring several times.
Improve accuracy and precision by removing outliers in the measurements.

Q12 [Intermediate, 4 marks] Inserting an element into an ArrayList can take linear
time. Briefly give two possible reasons (one concise sentence each) of why this may
be the case. The word limit is 50 words.

Answer:
If an element is inserted somewhere in the middle or at the beginning, then most
elements need to be shifted to make space. (2 marks)
If the list is full, then all elements need to be copied into a new list. (2 marks)

Q13 [Intermediate, 5 marks] Assume a hashtable containing n elements is resized to


1.5 times its current size whenever adding an element would make it too full
according to some given load factor. What would be the amortised runtime of the
add operation (i.e. adding a new element into the hashtable)? Give the asymptotic
complexity of the amortised runtime and explain it in no more than two concise
sentence. The word limit is 50 words.

Answer:
ϴ(1) (1 mark)
After resizing 0.5n elements can be added before the maximum load is reached
again. (2 marks)
The n steps of the resize operation can be amortised over these 0.5n adds, which
take constant time each. (2 marks)

Q14 [Intermediate, 4 marks] Imagine you are given the following hash function for
hashing a string s of length n: h(s) = (s[0] * s[n/2] * s[n-1]) % 17
s[0], s[n/2] and s[n-1] are the numerical codes of the first character, the middle
character (index rounded down) and the last character of the string, respectively.
Name one thing the hash function is doing well and one thing the hash function is
doing not so well, with one short sentence of explanation each. The word limit is 40
words.

Answer:
Dividing by a prime number helps to avoid collisions due to multiples. (2 marks)
Different strings that have the same first, middle and last characters cause collisions.
(2 marks)
Alternative “bad thing” answers:
Different strings that have the same first, middle and last characters but in different
order cause collisions. (2 marks)
If first, middle or last characters have code 0, then the overall value is 0 so the other
codes are not considered. (2 marks)

Q15 [Hard, 6 marks] Analyse the asymptotic best case and worst case runtimes of
the following code fragment.

for (int k = n; k > 1; k = k / 2) {


if (n != 2020) {
for (int i = 0; i < k; i++)
System.out.println("Jazz!");
} else
System.out.println("Gabriel!");
}

Specify the asymptotic runtimes as concisely as possible and provide a brief


explanation, no longer than one concise sentence for each case. The word limit is 60
words.

Answer:
Best case: ϴ(log n) (1 mark)
For n==2020, only first loop active with log n iterations due to halving. (2 marks)
Also marks if answer argues that n==2020 is only a single n so does not change
overall runtime behaviour over n.
Worst case: ϴ(n) (1 mark)
Steps in first two loops sum up to 2n, due to the exponential decrease of inner loop
iterations (as in Quickselect). (2 marks)

Q16 [Hard, 6 marks] Given the following array of numbers: 1, 5, 10, 21, 40, 50, 70,
80, 90, 100. Assuming an equal distribution of numbers between 0 and 100, which
numbers would interpolation search consider when trying to find 21? Name each
number in the right order and very briefly explain why, with just one short sentence
per number (no more). The word limit is 60 words.

Answer (2 marks for each step, one for number and one for explanation):
5 because 21 is estimated to be in position 10*(21-1)/(100-1)=2 of the initial array.
10 because 20 is estimated to be in position 8*(21-10)/(100-10)=1 of 10, 21, 40, 50,
70, 80, 90, 100.
21 because 21 is estimated to be in position 7*(21-21)/(100-21)=0 of 21, 40, 50, 70,
80, 90, 100. Alternatively, the algorithm has simply found it at that stage as it is
looking at the lower end of the remaining array.
If the positions are slightly off, give marks if explanation looks ok.
Marks are also given if slightly different formulations of interpolation search are used.

Q17 [Hard, 5 marks] Imagine you need to sort a large array of numbers in ascending
order. You know that when you get the numbers, they are most of the time almost in
the right order already. Just sometimes the order will be random. If you had to
choose a single sorting algorithm to accomplish the task most efficiently, which one
would it be? Explain your answer in no more than two concise sentences. The word
limit is 60 words.
Answer:
Shellsort (1 mark)
If numbers are mostly sorted, it will be fast, approx. linear time, similar to Insertion
Sort. (2 marks)
If numbers are random, then Shellsort is much faster than Insertion Sort and has a
reasonably good runtime still. (2 marks)
Partial marks (up to 2 marks) for Quicksort or Mergesort or Heapsort, and even
Insertion Sort, if there is a reasonable explanation.

Q18 [Hard, 6 marks] Insertion Sort, as described in the lecture, finds the right
position for a new element in an array of sorted elements and inserts the new
element at that position. Can we speed up Insertion Sort by using a better algorithm
for finding the right position for the new element in the array? Explain briefly in one
sentence each: a) how a better search algorithm could be used in Insertion Sort (e.g.
what algorithm, when to use it), b) how this would affect the asymptotic average
runtime of finding the right insertion position, and c) how it would affect the overall
asymptotic average runtime of Insertion Sort. The word limit is 80 words.

Answer:
a) Use binary search (or interpolation search) on the already sorted subarray to find
the right position before each of the n insertions. (2 marks)
b) Given a sorted sublist of size m, binary search would need log m (for linear search
log log m). (1 mark)
c) Still need to move on average m/2 elements to make space (linear time) in each of
the n insertions, so overall average runtime is still ϴ(n2). (3 marks)

Q19 [Hard, 6 marks] You are given lists of n numbers to sort. All you know is that the
numbers may be either almost sorted (ascending or descending) or in random order.
Assume you are using Quicksort and can pick one specific index 0…n-1 of the
element to use as a pivot (the same for all the lists). Which index would be the best
choice? Explain your choice briefly in at most 3 brief sentences. The word limit is 60
words.

Answer:
Pick a middle index, e.g. n/2. (1 mark)
If the list is almost sorted, then this is likely close to the median, leading to similarly
sized partitions and ϴ(n log n) runtime. (2.5 marks)
If the order is random, then this picks a random element, which is sometimes good
and sometimes bad, so on average a reasonable choice. (2.5 marks)
Use your discretion to allocate the half marks; could also give 2 and 3 etc.
Q20 [Hard, 6 marks] Given the AVL tree illustrated in the image.

Imagine you are inserting elements 1, 6, 8, 10, 99 and 5 into the AVL tree in the
given order. List the rotations performed during the insertions, e.g. something like
“After inserting x rotate clockwise around y.” The word limit is 50 words.

Answer:
After inserting 1 rotate clockwise around 3. (2 marks)
After inserting 5 rotate clockwise around 9 (2 marks) and then counterclockwise
around 4. (2 marks)

You might also like