
ECS 122A Spring 2009 Quiz 1 Solutions
1. (10 points) Prove that (n+2)2=O(n2) by giving the constant n0and cin the definition
of O-notation.
Answer:c= 2 and n0= 5.
Need (n+ 2)2≤cn2for all n≥n0.
Let c= 2, then (n+ 2)2≤cn2if 4n+ 4 ≤n2, which is true for all n≥5 = n0.
2. (10 points) Order the following functions into a list such that if fcomes before gin the
list then f=O(g). If any two (or more) of the same asymptotic order, indicate which.
n3n! lg2n8lg nµ4
5¶n
Answer: Here is the ordering
µ4
5¶n
lg2n n3= 8lg nn!
3. (20 points) Solve the following recurrences using the master theorem
(a) T(n) = 3 ·T³n
2´+n
Answer: Since n
nlog23=n1−lg 3 =n−ǫfor some const. ǫ > 0.
By the master theorem, case 1, T(n) = Θ(nlog23)
(b) T(n) = 2 ·T³n
4´+√n
Answer: Since √n
nlog42=√n
n1/2= 1.
By the master theorem, case 2, T(n) = Θ(nlog42lg n) = Θ(√nlg n).
4. (20 points) Consider a set of Sof n≥2 distinct numbers given in unsorted order.
Each of the following problem asks you to give an algorithm to determine two distinct
numbers xand yin the set Ssatisfy a stated condition. In as few words as possible,
describe your algorithm and its running time. (Note: To keep your answer brief, use
algorithms from lectures and homeworks as subroutines, no pseduocodes necessary, just
describe your algorithmic idea.)
(a) Determine x, y ∈Ssuch that |x−y| ≥ |w−z|for all w, z ∈S.
Answer:xand yare two farthest apart. Use MinMax algorithm in PS 1 to find min
and max, which are the desired xand y. This takes O(n) time.
(b) Determine x, y ∈Ssuch that x6=yand |x−y| ≤ |w−z|for all w, z ∈Ssuch that
w6=z.
Answer:xand yare the two cloest numbers.
First sort with MERGESORT – Θ(nlg n); then scan the sorted numbers for the two
adjacent numbers with the minimum differences – Θ(n). Total: Θ(nlg n).