Sample Midterm1 Sols
Sample Midterm1 Sols
• You must complete this exam within 180 minutes of opening it.
• You may use one two-sided sheet of notes that you have prepared yourself. You may not
use any other notes, books, or online resources. You may not collaborate with
others.
• If you have a question about the exam: Try to figure out the answer the best you can,
and clearly indicate on your exam that you had a question, and what you assumed the answer
was.
You may cite any result we have seen in lecture or in the textbook without proof, unless otherwise
stated. There is one blank page at the end for extra work. Please write your name at the top
of all pages.
Advice: If you get stuck on a problem, move on to the next one. Pay attention to how many
points each problem is worth. Read the problems carefully.
By signing your name below, you acknowledge that you have abided by the Stanford Honor Code
while taking this exam.
Signature:
Name: SOLUTIONS
SUNetID:
Name: Page 2 of 14
O
True False
1.2. (2 pt.) Which of the following expressions correctly describe T (n) = n2 log n? Circle all that
apply.
1.3. (15 pt.) For each recurrence relation, choose the expression (a)-(e) below which most accu-
rately describes it and write your choice (a)-(e) in the blank.
Note that not all options need toPbe used, and some options may be used more than
once. If it helps, log2 (3) ⇡ 1.6, and ti=0 i2 = ⇥(t3 ). Assume that T (1) = O(1) and don’t
worry about floors and ceilings.
(a) ⇥(log n) (b) ⇥(n) (c) ⇥(n log n) (d) ⇥ nlog2 3 (e) ⇥(n3 )
1.4. (10 pt.) For each quantity, choose the expression (A)-(E) below which most accurately
describes it and write your choice (A)-(E) in the blank.
Note that not all options need to be used, and some options may be used more than
once. Unless specified otherwise, all inputs are arrays of length n, and all running times refer
to worst-case running times of the best possible algorithms.
(A) ⇥(n) (B) ⇥(n2 ) (C) ⇥(n log n) (D) ⇥(log n) (E) ⇥ (1)
1.5. (8 pt.) Consider the followed randomized algorithm, which prints out some number of smiley
faces (:)) and some number of asterisks (*):
def randomizedSmiles(A):
n = len(A)
if n <= 1:
print ":)"
return
for i in {0,...,n-1}:
print "*"
Choose a uniformly random integer p in {1,....,n-1}
randomizedSmiles(A[:p])
randomizedSmiles(A[p:])
For the following parts, circle the tightest big-Oh bound that applies.
is
:*
:÷÷y
1.5.1. (2 pt.) What is the expected number of :)’s that randomizedSmiles prints out?
this
prints one
(a) O(1) (b) O(log n) 0
(c) O(n) (d) O(n log n) (e) O(n2 )
1.5.2. (2 pt.) What is the maximum number of :)’s that randomizedSmiles can print out,
) for each
" "
:
if you got to choose how p is selected?
element in the
00
:wq
"an:c:
" (a) O(1) (b) O(log n) (c) O(n) (d) O(n log n) (e) O(n2 )
1.5.3. (2 pt.) What is the expected number of *’s that randomizedSmiles prints out?
(a) O(1) (b) O(log n) (c) O(n) (d) O(n log n) (e) O(n2 )
[
1.5.4. (2 pt.) What is the maximum number of *’s that randomizedSmiles can print out, if
you got to choose how p is selected?
(a) O(1) (b) O(log n) (c) O(n) (d) O(n log n)
0 (e) O(n2 )
"
To be if to throw in an extra
"
PARTITION step
you
were
more
precise ,
above , would basically get Quick Sort plus some print statements
the
algorithm you
,
in
.
modified al would
Moreover ,
that
y print out exactly
the
same number of
"
*
"
'
s as the version without PARTITION
( printing * doesn't depend on the contents of A ) ,
and the number
of * 's
printed
out would be
roughly the same as the number
of comparisons made by PARTITION .
So the
expected of * is printed out is Oln log )
number n
,
printed
case
case number
of comparisons for QuickSort .
Name: Page 4 of 14
2.1. (0 pt.) Find the maximum of an unsorted array of length n in time O(n log n).
I would use MergeSort to sort the array, and then return the last element of the sorted array.
2.2. (0 pt.) Find the maximum of an unsorted array of length n in time O(1).
This cannot be done, because since the maximum could be anywhere, we need to at least look
at every element in the array, which takes time ⌦(n).
2.3. (6 pt.) Suppose you have access to a magic box which, given an array A, does the following
in time O(n):
and
This can
be done by calling the magic box 10 times
for i - I
, . . .
,
10 :
A
'
box CA )
(
←
magic -
if A is sorted : in
the
L by stepping through array
'
return A
"
return couldn't sort A
"
Name: Page 5 of 14
2.4. (6 pt.) Suppose you have access to a magic box that can circularly shift any contiguous
sub-array by 1, in-place, in time O(1). (For example, given the array A = [0, 1, 2, 3, 4, 5],
after an O(1)-time call magicbox(A[1:5]), we have A = [0, 2, 3, 4, 1, 5]). Sort an array A of
n elements using a comparison-based algorithm with additional access to this magic box, in
time O(n).
it doesn't do comparisons .
Even with the magic box ,
we still
saw
login ) comparisons
as we
need to make sun ,
2.5. (6 pt.) You are given an array A of length n, where n is a perfect square. Suppose you
p
have access to a magic box which, given any array B of length k n, returns the index
of a minimum element of B in time O(1). Sort A using a comparison-based algorithm with
additional access to this magic box, in time O(n).
can be done
by iteratively peeling off the minimum .
Finally ,
we can
merge
the rn sorted lists in line Oln ) : the
algorithm
from class have rn lists and the
is the same as the MERGE al except we use
g ,
magic box to identify the min of all rn pointers and increment the appropriate one .
2.6. (6 pt.) Suppose that k n. Given an array A containing n distinct elements, use a
comparison-based algorithm to return all of the smallest k elements of A, in any order, in
time O(n). (Notice that the running time should not depend on k).
go through
Then like PARTITION to the
we use an
algorithm
n elements of A and return the ones smaller than
or
equal to the kth .
Name: Page 6 of 14
def findMajority(A):
n = len(A) // assume that n is a power of 2.
if n == 1:
return A[0]
a = findMajority(A[:n/2])
b = findMajority(A[n/2:])
if isMajority(A,a):
return a
else:
return b
3.1.1. (10 pt.) Prove by induction that findMajority correctly returns an element of the
majority flavor.
[We are expecting: A formal proof by induction. Make sure to clearly label your
inductive hypothesis, base case, inductive step, and conclusion.]
lnductiveltypothes.is :
For
any array
A- of length n
,
if A has
majority It
a
,
then find
Majority returns it .
the I.H .
holds for n
-
- I .
Indudireslepi Let k > I ÷÷and suppose that the l H holds for all -
.
n E k -
1 .
A has
Let A be an
array
of length n
,
and
suppose
that a
majority It ,
x .
A would be hy th E would
of x in at most so it not be strict
majority
-
-
a
,
.
Then
by the I. H .
,
either a - x or
)
b - x
,
where a =
And Majority ( Alin KD and b. And
Majority ( Alma :3) as in the
pseudocode .
If a
-
. x
,
then is
Majority A ,
a will beTRUE and find
Majority will return a .
established for =L
Either
way ,
the inductive
hypothesis is n .
A- of
Conclusion.
By induction ,
for all n > I
,
find
Majority returns majority element
of
array length
More space on next page!
a an n .
Name: Page 7 of 14
p
3.1.2. (2 pt.) Suppose that isMajority runs in time O( n) on an array of length n. What
is the big-Oh running time of findMajority?
[We are expecting: Your answer and an explanation. You should give the best big-Oh
bound you can.]
4.1.1. (10 pt.) Give an algorithm that will find the median element in a ModifiedRedBlackTree
containing n elements in time O(log n). The algorithm should take as input a pointer to
the root of the ModifiedRedBlackTree. You can use any methods that you could use
on a regular Red-Black tree. You may assume that n is odd.
[We are expecting: Pseudocode and a clear English description of what your algorithm
is doing. You do not need to prove that your algorithm is correct.]
k
To implement MEDIAN, we will implement a more
general - SELECT
line
The basic idea is like the linear
modified RB Trees
-
algorithm on .
in the subtree
class if there Ck nodes
K SELECT
alg from are
:
III:)
.
f
-
the Otherwise , we
left ,
-
the we reverse on .
on
smallest
thing on the right .
)
1) 12 odd
f. size Of Subtree )
is
return SELECT ( r
-
Has sunning n
def SELECT ( r, k) :
kth smallest
.
D ther r is the
if leftSize = k -
1 :
return r
else :
size Of Subtree C )
y, then the
kin smallest lies to the
right
and is the k left size -1 smallest
n = r .
-
-
there .
return SELECT (r .
right ,
k -
left size -
1)
More space and another part on next page!
Name: Page 9 of 14
4.1.2. (3 pt.) Explain why your algorithm runs in time O(log n). You should explicitly use
the properties of Red-Black trees in your answer.
[We are expecting: A short explanation which explicitly invokes the properties of
Red-Black trees.]
time 0
Clog n ) .
Name: Page 10 of 14
4.2. (15 pt.) For this problem, suppose that A is an array containing n distinct items. There
is some order on the items, but you do not have direct access to a way to compare
them. Instead you have access to a genie named Middle. When you call the genie on three
distinct items, it will tell you which of the three is in the middle. For example, if a < c < b,
then Middle(a, b, c) will return c. If you call the genie on the same item multiple times, for
example, Middle(a, a, b), the genie will return the repeated element a.
If it helps, you can alternatively assume that Middle outputs 1, 2, or 3 to indicate if the 1st,
2nd, or 3rd parameter, respectively, was the middle element: in the example where a < c < b,
Middle(a, b, c) could return 3; and Middle(a, a, b) would return either 1 or 2 arbitrarily.
You may do standard array operations like accessing entries, swapping entries and so on. You
may copy items, and you can tell whether or not two items are equal.
4.2.1. (6 pt.) Suppose that A has size n. (If it helps, you may assume that n is a power
of two). Give an algorithm getMinAndMax which takes A as input, uses O(n) calls to
Middle, and returns two elements a and b in A, so that one of a, b is the minimum of
A, and the other is the maximum of A. Your algorithm does not need to say which is
the minimum and which is the maximum.
[We are expecting: Pseudocode and a clear English description of what your algorithm
is doing. You do not need to justify the running time or the correctness.]
Iosisesitinankdifyouersouoncase
-
Note .
The
problem
was not well defined if net
required for credit )
-
(
Here two solutions
only
,
:
are one is
Max 4( A)
get Min And i://aasggmf.si 'T (A )
'
:3 ] )
MIDDLE ( AC l
} When are current candidates
) net { Aco ] Asif our
=
a
all the items in A- except for a
=
MIDDLE (
,
,
for i- 2,3, . . .
,
n -
1 :
:
"
"
" ":* :÷÷¥±:÷÷¥a÷
Yi:÷¥÷÷÷?
"
:
.
I
) This algorithm
return
getMin
AndMax 41A
steps through the array , keeping a set ret of candidates .
gettin
EIEineaitnen.es: Estimation:c: :O
=
I
Fannin min:* :c .
a could not have biren the Max or min of A .
sin
it
Then for a
finds the
general
array of length n ,
min
N
✓
Tofino
¥ ← .
Noieidinosavrdrawingnot
|reqviredfrcre)
'
4.2.2. (9 pt.) Describe how to use part 4.2.1. to implement an algorithm SortOfSort which
takes A as input, and returns a version of A which is either sorted from smallest to
largest or sorted from largest to smallest. It is okay if your algorithm does not know
which direction the output is sorted in.
Your algorithm should use O(n log n) calls to the Middle genie. Partial credit will be
given for an algorithm that makes O(n2 ) calls to the the Middle genie.
You may use the algorithm described in part 4.2.1., even if you did not complete that
part.
[Hint: Can you use part 4.2.1. and Middle to mimic a comparison-based algorithm?]
[We are expecting: A clear English description of what your algorithm would do. It
is okay to refer to an algorithm that we have seen in class. You do not need to write
pseudocode to receive credit for this part, although you may if that makes it easier to
be clear. You do not need to justify the running time or the correctness.]
sea
COMPARE ,
code
pseudo pseudo
is
The
:
-
get
COMPARE ( )
def
)¥i÷÷÷÷÷÷
x :
,
y
MIDDLE ( )
y
:
a x ,
Z = ,
if z = x :
÷:: : : : ::
Max then COMPARE
,
e.
is backwards
calls to compare ,
hence this makes Oln login ) calls to
MIDDLE -
a ,
Name: Page 13 of 14
to
-
i
,
j s .
t .
Agg .
'
)
ACTUAL ANSWER ( A
than that
def :
.g
is of L
\ (A) hassome power
n a
ten
Il Replace the elements of A
n
their orig value
-
them w/
A [ ( AG I i ) for iinrangelnl ]
to
tag . .
lexicographic order)
(
=
-
, "
(When Ali 's
'
3
using
'
Ag
we now are
GI ] say
> -
we .
B [O for
,
i in
=
range
A B )
PROBLEM FVE ( ,
return B
(A) X assume is
power
of 2
1¥:÷:÷÷:÷÷÷÷÷÷÷÷÷÷÷::÷
a
n =
Len n
halves
)
}
both
PROBLEM FIVE ( ACE :3 ,
BCE :] "This recursively sorts ,
: ::::::÷:*:'
""
know sort A- in -
place
: s
This is the end!
#t÷¥mµ
MERGE ( AC is
: "
ACK :3 )
ANOTHENREfffffff.ie
,
]
AYY!
Name: Page 14 of 14
This page intentionally blank for extra space for any question.
Please indicate in the relevant problem if you have work here that you want graded, and label
your work clearly.
AH.solnfr5.tt
Modified RBTree haven't how to do the modification )
Alternative Solh
using a (
we
accepted this even
though we seen .
B =L ]
1- =
MRB Tree from problem 4.1
for i in 0
,
. . .
,
n -
1 :
( T insert ( Ali ] )
.
H Ollogn ) garden
for i in 0, . - -
,
n -
1 :
"
( ÷ "" ) 11 from 4.1 to do this
Modify
Than solar
get Num Bigger
17p19!Y¥
:
our
m ←
defnumif.ir?:I:.rs://OClogln
(
, ) ) L return 0
If x > r :
( return num
Biggerthan ( x
,
r
-
right )
q
.
left)
BiggerThan (
.
. .
,
in line
.
runs
indices '
any larger i i
>
.