0% found this document useful (0 votes)
13 views14 pages

Sample Midterm1 Sols

The CS161 Midterm Exam is a closed-book, take-home exam lasting three hours, where students can use a single two-sided sheet of notes. It includes multiple-choice questions, short answer tasks, and algorithm analysis, with a focus on understanding and applying concepts from the course. Students must adhere to the Stanford Honor Code and complete the exam independently without external resources.

Uploaded by

pooja0100
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)
13 views14 pages

Sample Midterm1 Sols

The CS161 Midterm Exam is a closed-book, take-home exam lasting three hours, where students can use a single two-sided sheet of notes. It includes multiple-choice questions, short answer tasks, and algorithm analysis, with a focus on understanding and applying concepts from the course. Students must adhere to the Stanford Honor Code and complete the exam independently without external resources.

Uploaded by

pooja0100
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/ 14

CS161, Winter 2020 Page 1 of 14

CS161 Midterm Exam


Once you turn this page, your exam has officially started!
You have three (3) hours for this exam.
Instructions: This is a timed, closed-book take-home exam:

• 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.

The following is a statement of the Stanford University Honor Code:


1. The Honor Code is an undertaking of the students, individually and collectively:
(1) that they will not give or receive aid in examinations; that they will not give or receive unpermitted aid
in class work, in the preparation of reports, or in any other work that is to be used by the instructor as
the basis of grading;
(2) that they will do their share and take an active part in seeing to it that others as well as themselves
uphold the spirit and letter of the Honor Code.
2. The faculty on its part manifests its confidence in the honor of its students by refraining from proctoring exam-
inations and from taking unusual and unreasonable precautions to prevent the forms of dishonesty mentioned
above. The faculty will also avoid, as far as practicable, academic procedures that create temptations to violate
the Honor Code.
3. While the faculty alone has the right and obligation to set academic requirements, the students and faculty will
work together to establish optimal conditions for honorable academic work.

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

1 Multiple Choice (36 pts)


No explanation is required for multiple-choice questions. Please clearly mark your
answers; if you must change an answer, either erase thoroughly or else make it very clear which
answer(s) you have chosen. Ambiguous answers will be marked incorrect.
1.1. (1 pt.) Suppose that f (n) = O(n) and g(n) = O(n log n). True or false: f (n) + g(n) =
O(n log n).

O
True False

1.2. (2 pt.) Which of the following expressions correctly describe T (n) = n2 log n? Circle all that
apply.

(A) O(n) (B) O(n2 ) (C) ⇥(n2 )


O (D) ⌦(n2 ) (E) ⇥(n3 )

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.3.1. (2 pt.) d : T (n) = 3T (n/2) + n3/2


1.3.2. (2 pt.) b : T (n) = T (n/2) + n
1.3.3. (3 pt.) e : T (n) = T (n 1) + n2
1.3.4. (4 pt.) b : T (n) = T (n/2) + T (n/10) + T (n/20) + n
1.3.5. (4 pt.) a : T (n) = T (n1/2 ) + log n

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.4.1. (2 pt.) C : Expected running time of QuickSort


1.4.2. (2 pt.) B : Running time of InsertionSort
1.4.3. (2 pt.) D : Time to search for an item in a Red-Black tree with n items
1.4.4. (2 pt.) C : Running time of RadixSort with base r = 10, assuming all items are
integers between 0 and n100
1.4.5. (2 pt.) A : Time to find the median element of an unsorted array.
Name: Page 3 of 14

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 )

The number of "


*
printed by this algorithm basically
"
s is

the same as the number


of comparisons done by Quick Sort .

"

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
,

the same as the


expected number of comparisons in
Quick sort .

The worst number of * 's


-

printed
case

out is 0 ( n 2) , same as the worst -

case number
of comparisons for QuickSort .
Name: Page 4 of 14

2 Can it be done? (Short answers) (24 pts)


For each of the following tasks, either explain briefly and clearly how you would accomplish
it, or else explain why it cannot be done in the worst case. If you explain how to accomplish
it, you do not need to prove that your algorithm works. You may cite any result or algorithm we
have seen in class, but don’t make any assumptions that are not explicitly stated. Unless stated
otherwise, all running times refer to deterministic worst-case running time.
The first two have been done for you to give an idea of the level of detail we are expecting.

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):

• With probability 1/2, the box outputs a sorted version of A.


• With probability 1/2, the box outputs an array with the same elements as A, which may
or may not be sorted.

Sort an array A of n elements using a comparison-based randomized algorithm with additional


access to this magic box, which succeeds with probability 1 1/210 , in time O(n).

and
This can
be done by calling the magic box 10 times

if the result sorted :


checking
is

for i - I
, . . .

,
10 :

A
'
box CA )

(

magic -

A Canche ok this line Ocn )


'

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).

This cannot be done .


The
magic
box just manipulates the
array ,

it doesn't do comparisons .
Even with the magic box ,
we still

saw
login ) comparisons
as we
need to make sun ,

decision tree class


in the
argument in .

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).

This can be done i divide A into in lists of length rn .

the box to sort each in line Ocrn ) this


;
Then use magic one

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).

This can be done .


We find the kth smallest element of A
in Oln ) time
using
the SELECT
algorithm from class .

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

3 Algorithm Analysis / Proving Stu↵ (12 pts)


3.1. (12 pt.) Suppose that A is an array of n elements. Each element of A has some flavor; you
cannot tell the flavors apart, but you know that one flavor is a strict majority. That is, there
are strictly more than n/2 elements that have this one flavor. You have access to a genie
called isMajority so that isMajority(A, x) returns True if x is an element of A with the
majority flavor, and False otherwise.
You develop the following algorithm to return an element of the majority flavor, when n is a
power of 2:

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 .

Since this is what findMajority returns,


Basecasei If n=1 , then the majority element is A COI ,
the
only element .

the I.H .
holds for n
-

- I .

Indudireslepi Let k > I ÷÷and suppose that the l H holds for all -
.
n E k -

1 .

We want to show it holds for n =L .

A has
Let A be an
array
of length n
,
and
suppose
that a
majority It ,
x .

A link] Acme :] otherwise , the total number of copies


Then majority ett of either :
x must be a or

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 .

and find will return b


On the other hand if then b
Majority
-
x
at x , , .

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

More space for 3.1.1.

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.]

time Th ) of satisfies the


In this case
,
the
running
is
Majorly
recurrence relation Rn ) = 2 Rn k ) t
OC in ) .

By the Master Theorem ,


Tnt = 041 .
Name: Page 8 of 14

4 Algorithm Design (28 pts)


4.1. (13 pt.)
Suppose that there is a data structure ModifiedRedBlackTree which is r
just like a Red-Black tree, except that additionally, each node N has a
method sizeOfSubtree() which returns the size of the subtree under N a b
in time O(1). For example, in the tree to the right, a.sizeOfSubtree()
would return the number of nodes in T1 , including a, and not including
NIL nodes. T1 T2

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
-

look for the 1


left
-

the Otherwise , we
left ,
-

the we reverse on .

on

smallest
thing on the right .

def MEDIAN Lrt :

)
1) 12 odd
f. size Of Subtree )
is
return SELECT ( r
-

Has sunning n

def SELECT ( r, k) :

left size Of Subtree )


left Size = r .

kth smallest
.

D ther r is the
if leftSize = k -

1 :

return r

lithe the kth smallest lies to the left


if left size > f -
1 :

return SELECT ( r left , k )


.

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.]

Thisalgorithm traverses the


unique path from the
root of the tree to the median .
Since RBTrees

have depth 0 Clog ) n


,
this path has
length
at most ④ ognl ,
and this algorithm runs in

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

.eu#a/lk: 7i:fti: t*i


Solution
① Divide t
Conquer :
② Iterative Solution :

Max 4( A)
get Min And i://aasggmf.si 'T (A )
'

def def gettin AndMax


:

:3 ] )
MIDDLE ( AC l
} When are current candidates
) net { Aco ] Asif our
=
a
all the items in A- except for a
=

MIDDLE (
,
,

Im the two items


in A that are neither amor
b .

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 .

And Max ( AC mid ) :

gettin
EIEineaitnen.es: Estimation:c: :O
=

I
Fannin min:* :c .
a could not have biren the Max or min of A .
sin

This algorithm first implements the case for


m=4 in
gettin Max 4 .

it
Then for a
finds the
general
array of length n ,
min

and Max in the left half and the ,


min
More space on next page!
right half
and max in the ,
then uses the
size 4 to return the min
and
case
againthose
Max of 4 .
Name: Page 11 of 14

Blank space for 4.2.1.

N

Tofino
¥ ← .

Noieidinosavrdrawingnot
|reqviredfrcre)
'

Another part on next page!


Name: Page 12 of 14

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.]

and MIDDLE to implement


The idea is to use getMax Or Min
and then to standard
sorting algorithm
.

sea
COMPARE ,

code
pseudo pseudo
is
The
:
-

b Max And Min (A) HOW calls to MIDDLE


a ,
=

get

COMPARE ( )
def

)¥i÷÷÷÷÷÷
x :
,
y
MIDDLE ( )
y
:
a x ,
Z = ,

if z = x :

÷:: : : : ::
Max then COMPARE
,
e.
is backwards

Use MERGESORT with this version of COMPARE .

MERGES ORT makes Ocn )


log
n
We saw in class that

calls to compare ,
hence this makes Oln login ) calls to

MIDDLE -

If a was the min , this sorts A .

the this sorts 1- in reverse order


If was Max .

a ,
Name: Page 13 of 14

5 Harder problem (5 pts)


Note: This problem may be trickier and it is only worth 5 points. You might want to try the rest
of the exam first.

5.1. (5 pt.) (May be more difficult)


Design an algorithm that does the following. Given an input array A of length n containing
distinct positive integers, output an array B so that B[i] contains the number of values
j 2 {0, ..., n 1} so that j > i and 3 · A[j] > A[i].
For example, if the input were A = [6, 2, 4, 1, 7], then the output would be B = [2, 3, 1, 1, 0].
Your algorithm should run in time O(n log n). If it helps, you may assume that n is a power
of 2.
[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.]

We will modify MERGE SORT to build B .


Bette we MERGE , we update
B to account for all the pairs i CE Ej .
We do a linear scan
through the ( now sorted )
ACE ] and ACE :] find, for each the last Afi ] Then we update corresponding ell of B
the -

to
-
i
,
j s .
t .

Agg .

by the number of things ACM I larger


in :

'

)
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

def PROBLEM FIVE ( A ,B )


:
.

(A) X assume is
power
of 2

1¥:÷:÷÷:÷÷÷÷÷÷÷÷÷÷÷::÷
a

n =
Len n

halves
)
}
both
PROBLEM FIVE ( ACE :3 ,
BCE :] "This recursively sorts ,

and fills in B to account for all the pairs


( AC ng y Bf : ng] y
PROBLEM AVE
:

jan and EE icj


,
is -

Yup date B to account for the


pairs is E Ej

: ::::::÷:*:'
""

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
.

Thi q, aeemeiwms.nanppg.me mµ+. oµµm ,


,
puts
modification If
w/ the 4.1
xcr :

left)
BiggerThan (
.

right size Of Subtree)


t nom x r
return r
.

. .
,

Then for each i :O it uses the RBTree to


Ollogn)
.int ,
This
. .

in line
.

runs

how Its than Ali 313 and


see
many
are
larger ,

that's what in Bci ] ; it then memories Ali ]


goes
from T so that Aci] won't show up in the count for
,

indices '

any larger i i
>
.

You might also like