Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

COMP201 SI Worksheet 3 – Week 4

Question One
For each of the following, state whether the statements are true or false. If false, provide a reason.

1. If two strings s1 and s2 are equal, then their hash codes are the same.
True

2. It is possible to traverse from index 0 to index n-1 in a set, where n-1 is the last element in the
set.
False. You cannot traverse a set via indexes. To traverse a set, you must first obtain an iterator,
which will then allow you to traverse the set from beginning to end.

3. If you need to store non duplicate elements in the order of insertion, the best option is to use a
HashSet.
False. You should rather use a LinkedHashSet.

4. If you need to frequently insert and delete elements at the beginning of a list, the best option is
to use an ArrayList.
False. A LinkedList will be more appropriate.

5. Suppose there is a method that loops through each item in a list to find a specific value. In this
case, the estimated worst time complexity is O(n).
True

Question Two
For the code snippets below, calculate the number of times the printing code will be displayed if n=10,
n=20 and n=30. Thereafter, use the Big O notation to estimate the time complexity.

1.

N=10. Loops 10 times


N=20. Loops 20 times
N=30. Loops 30 times
In general, it is looping n times. Therefore, O(n)
2.

N=10. Loops 10 * 10 * 10 = 1000 times


N=20. Loops 10 * 20 * 20 = 4 000 times
N=30. Loops 10 * 30 * 30 = 9 000 times
In general, 10 * n * n = 10 * n2 = O(n2)

3.

N=10. Loops 10 * 10 = 100 times


N=20. Loops 20 * 20 = 400 times
N=30. Loops 30 * 30 = 900 times
In general, n * n = n2 = O(n2)

Question Three
For the code below, work out the time complexity.

I will take on k+1 values from n/20, n/21, n/22, …, n/2k


T(n) = k* c* n, where k+1 is the number of values I will take on.
For each I, the inner loop executes n times

Solve for k T(n) = c.n log2(n)


n/2k = 1 T(n) = O(n.log2(n))
k= log2(n)

You might also like