You are on page 1of 2

CS1020E: Data Structures and Algorithms I

Tutorial 8 Complexity Analysis


(Week starting 20 October 2013)
1. Designing an Algorithm
Given a set S of size n and an integer X, you need to find a pair
1
and
2
such that
1
+
2
= .
For example, given the following set = [2, 5, 6, 11, 1, 0, 25, 3, 1, 8] and = 22, one
possible solution is
1
= 3 and
2
= 25. Note that the set S need not be sorted (as shown in the
example above), but the elements in the set is unique (by definition of set). If there are multiple
solution, just print any solution.

a. Design an algorithm to solve this problem navely which should run in (
2
).
b. Design a more efficient algorithm to solve this problem in ( log ).
Hint: Would sorting the array helps? Sorting an array can be done in ( log ) time.

2. Big-Oh Analysis
Compare the following functions in terms of Big-Oh notation. Use the following symbols:
1

2
means that (
1
) is smaller than (
2
). Use = to show that (
1
) to be equal to (
2
).
Arrange the following functions from the smallest to the largest in terms of Big-Oh.

a.
1
= 7
2
,
2
=
7
3
,
3
=

3
1000
,
4
=
2.5

b.
1
= 2

,
2
= 2
2
,
3
= 3

,
4
= 2

2

c.
1
= 2 log ,
2
= 2
log
2

,
3
= log ,
4
= 1020
2


3. Data Structure Design
In Question 1, we are using a set of integer. From Tutorial 4 Question 3 set is a mathematical
object that holds unique elements (i.e. there are no duplicates). Our set should provide the
following simplified functionalities: insert, union, and intersection. The skeleton for the
set is in the Java file. Assuming that the maximum size of the sets are 1,000, the size of the first
set is and the size of the second set is , these functions should satisfy the following time
constraints:

a. In the 1
st
design, insert is (), union is (max( log , log )), intersection is
(max( log , log )).
b. In the 2
nd
design, insert is (), union is ( +), intersection is ( + ).
Hint: Can you keep the set sorted?

CS1020E: Data Structures and Algorithms I
4. Further Algorithm Analysis
Given the following functions, what is the time complexity of the function foo?




















Challenging Problem
Zero Problem: there is a problem called zero in which you are given a non-ordered list of random
integers (may contain duplicates); you are to find three distinct (may be duplicate, if there are
duplicates, but not to use the same number twice) numbers such that the sum of these three
numbers is zero. A nave implementation is to have a triple nested for-loop to enumerate all
possible number combination and see if the sum is zero. This will solve the problem in (
3
)
time.

Develop an algorithm to solve the problem in (
2
) with no extra space allocated.
int foo(int a[], int u, int l, int x) {
while(l <= u) {
int s = (u-l+1)/3, f = l+s, b = f+s;

if(a[f] == x)
return f;
else if(a[b] == x)
return b;
else if(a[f] > x)
u = f-1;
else if(a[b] > x)
l = b+1;
else {
l = b-1;
u = f+1;
}
}

return -1;
}

You might also like