0% found this document useful (0 votes)
10 views

algo pyq

This document is a question paper for a B.Sc. (H) Computer Science course on Design & Analysis of Algorithms, containing various questions related to algorithm analysis, data structures, and graph theory. It includes instructions for candidates, a compulsory question, and a selection of additional questions to be attempted. The paper is structured to assess knowledge on topics such as sorting algorithms, tree operations, and optimization problems over a duration of three hours for a maximum of 75 marks.
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)
10 views

algo pyq

This document is a question paper for a B.Sc. (H) Computer Science course on Design & Analysis of Algorithms, containing various questions related to algorithm analysis, data structures, and graph theory. It includes instructions for candidates, a compulsory question, and a selection of additional questions to be attempted. The paper is structured to assess knowledge on topics such as sorting algorithms, tree operations, and optimization problems over a duration of three hours for a maximum of 75 marks.
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/ 16

[This question paper contains 8 printed pages.

Your Roll N0.....

Sr. No. of Question Paper: 2208 IC

Unique Paper Code : 32341401


Name of the Paper Design & Analysis of
Algorithms
Name of the Course : B.Sc. (H) Computer Science
Semester : IV

Duration : 3 Hours Maximum Marks: 75

Instructions for Candidates


1. Writeyour RollNo. on the top immediately on receipt
of this question paper.
2. Question No. 1is compulsory.
3. Attempt any four of Questions Nos. 2 to 7.

1. (a) Consider an input of nnumbers that are all equal.


What would be the running time of the following
algorithms for the input
(i) Merge Sort

(ii) Heap Sort (4)


P.T.0.
2208 2
(0) Give a 2208
3
recurrence for the running
time of the
following algorithms to sort n () Give an
example graph with 5 nodes
elements. two different gives that
(i) Maxheapify Minimum Spanning Trees when
computed with Prim's algorithm and
(i) Quicksort algorithm. Kruskal's
(2) (4)
(c) Can (g) Consider the
Insertion Sort be used as an following recurrence relation
for Radix sort?
Explain why or why not.
intermediate sort computing the sum of nnatural for
(3) numbers.
(d) Compare the F(n) = F(n-1)+n. n>1
worst case running
following operations with respect to times of the F(1) = 1
and binary search red-black trees
trees. What is the
running time of
the
(i) Searching a given
key rccursive
implementationthe of the above recurrence?
(i)
memoizing recursive solution Would
Inserting a given key (4) running time? Explain. improve the
(e) (4)
Recall that the usual (h) In a
implementation quicksort certain
nodes adj acentapplication
of is it
to a given required find the
makes two recursive calls. to
Consider a variant that
optimizes on stack space as follows. It
recurses Which of the two node in a sparse graph.
on the smaller
needs to
subarray as usual, but whenever it
recurse on the larger subarray, it uses an
adjacency representations, namely
list and
suitable? Justify. adjacency matrix, is more
iterative module instead. What would be (4)
of recursion for this the depth (i) Can
variant? Depth First Search
depth of recursion for usual Compare
it to the
determine shortest
a algorithm be used to
quicksort. implementation of to a path from a
source node
(4) destination node in an
Justify. unweighted graph?
(3)
P.T.O.
2208 4 2208 5
G) Consider the Interval Schcdulin problen vwhercin
WC arc givcn a resOurcc and a sct of rcqucsts
cach having a start tíme and a finish time. The
goal is to mazímize the nurnber of request
schcdulcd. Show that the following grccdy strategy
docs not gíve an optirnal solutíon for the above
problem: sclcct the requcst with fewest number
of inconpatiblc requcsts. (3)

2. (a) Let T be ared-black tree and %be a node in it.


Let h be the height of the node %in T and d be u
its depth. Left rotate operatíon is perforrned on
the node x to give resultant tree T".
(i) How does the height of x change post
rotatíon?
y

(ii) How does the depth of x change post


rotation? (4) Por cach of the graphs, specify whether the graph
is bipartite or not. If ít ís bipartíte then give the
naive string
(b) Give a scenarío in which the two partitions else justify. (4)
case
rnatching algorithrm dermonstrates íts worst
(3) (b) Recall the scheduling problem wherein we are
behaviour.
given a single resource and a set of requests
havíng deadlines. A request is said to be late if it
for solvíng the subset
(c) Give a recurrence relation rnisses the deadline. Our goal is to Tninirnize the
(3)
sum problern. Tnaxímurn lateness. With respect to a schedule S,
we define idle tirne as the time during whích the
: resource is idle, in between two requests. S is
3. (a) Consider the following graphs
P.TO.
2208
2208 7
said to have an inversion when request i has
been (b) Is the following recurrence for the Knapsack
scheduled before i, and d(i) > d(G) (d(k) being the
deadlinc of a request k). Argue that all schedules problem correct? If not, give the correct
With no idle time and no inversions have the same recurrence. Justify your answer in either case.
maxinmum lateness. (6) If w < w, then OPT(i,w) = OPT(i-1,w)
Otherwise, OPT(i, w) = max(OPT(i-1),w), v, +
4 (a) Consider the Heapsort Algorithm. Fill in the OPT(i-1, w) (4)
missing details correctly. (3) (c) Give an
Assume A[l....length) be the array to be sorted
algorithm to determine if a given
undirected graph is connected. (3)
MaxHeapify(A,i)
1=2*i 5. (a) Consider a stack that supports the operations Push,
2*j+1 Pop and Multi-push (pushes k items onto the
ifl<= Aheapsize and A[1]|>A[r] stack).
largest =1 Suppose a sequence of n operations is performed
on the stack. Would the
else largest =i amnortized cost of an
if K=A.heapsize and A[r] >A[largest] operation be O(1)? Explain. (4)
largest =r
if largest !=i (b) If quick sort is run on an n
sized array such that
exchange A[i] and A[largest] the array is always divided into 2
Maxheapify(A, equal halves.
How many times is the partition
algorithm called?
Explain briefly. (3)
BuildMaxHeap(A)
A.heapsize =A.length (c) Consider the weighted interval
for i= scheduling
problem. Will the following greedy
MaxHeapify (A,i) work? strategy
Justify.While requests remain, Choose
and add a request to
Heapsor(A) solution that has the
BuildMaxHeap (A) largest starting time and delete all
for i = A.lengthdownto 2 requests. non-compatible
exchange A[_]with A[i] (3)
A.heapsize = A.heapsize -1 6. (a) In
MaxHeapify (A, _) randomized-selectis
partition subroutine
algorithm randomized
used. If we replace the
P.T.0.
2208 8

randomizcd partition by a partition subroutine which


chooses the last clement of the list as pivot and
call the modificd algorithm as the select algorithm.
What afrfcct docs it have on the running time of
the sclcct algorithm? (3)

(b) Show that any directed graph havíng a topological


ordering must be acyclic. (4)

(c) For the elements 6. 2. 8, 3, 10: give a valid Red


Black tree. (3)

except that
7. (a) A d-ary heap is like a binary heap, children.
two
nodes may have d children instead of
Consider a 3-ary heap represented using an array,
three children of a
how would the indices of the
(3)
node be computed?
all the gold dust from
(b) A thief wants to steal
kg of it. The thief has n
a store having W
capacities. Give an
sacks having different sacks
thief to fill his
efficient algorithm for the
that the number of sacks used is
with dust so
(3)
minimized.
function:
time of the following
(c) Discuss the running
func(A)
for i = 0to A.length -2
A.length 1
for j = itl to
if (A[[-1] > Aj]) (4)
exchange (A[j-1] and Aj] )
(1400)
This question paper contains 8+2 printed pagcs];
Rol|No.}
3 s S.No, ofQuestion Paper 6512
p Unique Paper Code%323414011 HC

Nanie ofthe PapersanDesigu.and Analysis.ofAlgorithm_


Name ofthe Course, B.Sc (H), Computer-Scicnce
Semester. IV

Duration3.Hours Maximum Marks:75


Write your Roll No. on the top.immediately on receipt o thisquestion paper.)

Question. No 1of 35 marks1s compusory

Attempt anyfour questions from QNo 2to Q:cNo.

1 (a)Arrange the following functions. in thesincreasing


order of their tate of growthnlog n)2 22An
ng(n)

(6)Consider a variationof the merge sort algorithm that


solvesa problemof size n bydividing it into two.

subproblems of sizs 2n/3and n73:and then merging


the solutioFs. Pind the recurrece for the ånning time
of the above algorithm: and, solve it;

PTO.
( 2 ) 6512
(3 ) 6512

() A thie wants to steal all the. gold dust from a store


(e)Cana red-black tree havej
having W kg of i The thËef :has n sacks having
(0 a black node without any sibling ? Justify.
different capacjties.;Give an efficient algoritbm for the
thief -to fill his sacks; wËth dust so that the number of ()a red node'without an÷ sibling ? Justify.

sacks usedis minimized. Consider an algorithm A with run time O(n). What is

the condition on iA for it to be usable. as the inter


Consider. an instance of the:weighted interval scheduling
problerin with 6 intetvals as specified below:: mediate sort in Radix sort ? Explain.

Interval number. Start tím (s) Finish time (f) Weight (v) (e) Let G = (V,E) be an-undifccted pathgraph with n
nodes. We call :a graph a 'path if its nÍdes, can be

written as :V| V2; with an cdge between

v, and v,; if and oDly if the numbersi and j difer by


exactly 1. With cach node :v, we associae a positive
integer-weight. denoted :by , A 'subset, of the nodes
is çalled an independent set, if no two of them are joined
by. an edge. Consider the following greedy algorithm
for finding an independent set of maximum total weight
With the helpof ther àbove example argue that
sins: a path graph
the 'memorized recursive algorithm solves lesser number
of subproblems. than,the .corre_ponding iteratiyë Start with S=empty set

algorithm. While some. node remains in G

PT.O.
6512
6512
(4 )
(). Would you use DPS.to find, the, shoetes-path
Pick a node v, of maximm1 weight
di_tance: between two nodes in 'a graph ? Justify your
Add v, lo S
answer:
Delete v; and its neighbors fromG
(9) Consider an adjacency list representation of a directed
Endwhile anhwhereia an array of the outgoing edges (and not
graph
Return S the incoming edges) for each vertex is: maintained.
Give an example to show that the above algorithm does Give an algorithm to compute the indegree. for each
vertex and discuss the timecomplexíty of the.
not `always tind an' optimal 'solution.
complevibai: algorithm.
(ü) Discuss the run time of the narve string

matching.algorithm. () For each of the following operations does, a Red BIlack


Tre work. faster than a Binary Search Tree ? Elaborate
Consider a directed graph G .(V, E)::Given twovertices
your answer.
sand t in V, mention the nane of an
algorithm that

exists at least
()Insertion
can be used to determine if there
the iy Preorder traversal. 5
one s-t path in G. What is the running time of
algorithm ?
3 (a Consider.the following. álgorithm. that takesias input an
oRarray,:of n: integersand anineger S. It finds: whether
element
Give an eficient algorithm to.find the maximåm
of the there exi_t, two elements in the, array tlhat: suin up to.
in a min-heup. Giye the exact running, time
S) and returFs l on: suçcess and0 on failure.
al:orithm.
PT.O.
6512
(. ) 6512
4.
FindPair (Arr, n, S) (a) Consider,astackS that,supports the following
operations
Quicksort (AT, 1, n) Push(S,x)pushelement x onto stack S
for, i = | to n
Pop(S): pop the top element from stack S and. returnit
tlag = BinarySearch(Art, i+l;.n, |S-ArT[ill
/f ilag) Multipon(S K) cemové. top, k;eleménts: of stack' S
return 1
Using the aggregateamethod of;analysis, determine the
endif
amortised cost per operatjon when: ia sequence! of n,
endFor
operations is performed onan empty: stack.
return 0
(6) Foreach of the following sorting .algoithms gve: an
FindPair uses the,following algorithms
input of sizefive
Quicksort (Ariy, First, Last): forwhichitshowsworstcase
behaviour
Binary Search (Array, First, last, element)
Analyze the 'worst case running time -of EindPair )Mergesort
(b) Çan a graph G in which edge weights CDQuick sort
arennot
necessarily distinct. have more. than one mihimum For thevariant of nterval scheduling problem that
spanning trees-(MST). 1fyes, give an èxample; if no, minjmizeslateness, give an instancer with two different
justify.
optimal solutions, neither of which,has any
inver_ions.
() Is Merge sort () in place (ii)
stable:? Explain. Or idletime

PTO,
6512. (9 ) 6512
( 8 )

npdes that has two we replace each edge cost c by its square, c,", thereby
(a) Give an example graph having five
show -the creating a new-instanceof.the problem with the same
different topological orderlngs. Also,

topological orderings. graph:but different costs.Is -it necessary for. Pto still

function in be a minimum cost: s-t path for this new instance.?


Observe hat selection sort and heap sort.
in any iteration Explain.
asimilar fashion, in' the following sense
findthemaximum Why is-Bucket. sort consideYed 'to be a non-comparison
both the sórting techniques: (6)

and place
amongst the elements yet to be procëssed based sorting algorithm-(where no- comparison of keys
-
running
appropriaiely. However, they have different is -performed for sorting the list) despite,. the fact that

complexity of both
times. Give the asymptotic time insertion sort, which is used-to sort individual buckets,
theitrunning times
and comment on what makes is comparison -based ?

different. (c). What kind. of inputs(will lead to (i) best ça[e (i)
worst
successive insertions. for
Create a Red-black tree with case performance for insertion'sort algorithm ? Give the
numbers: 10;8,14,12,13.2
the following sequence of rünning time for both,thecases. 4

of the Shortest
6. Suppose we are given an instançe 7. (a) ,Show that at most 3*floor(n/2) comparisons are
sufficient
graph, G. We assume
S-t path problem on a. directed to:find-both the minimum and maximum in a given array
and distinct. Let.Pbe
all the edge costs are positive .of, size-n.
instance. Now suppose
a minimum çost $-t path for this
P.TO.
(10 ). 6512

(6) Consider the following' recursive algorithm to find an


optimal solution' to the subset sum problem

Compute_opt(i,w)
If i = 0 or w =0 then

Retutn- 0.

Else

lf _w<w, then:.

ReturH Compute opt(i-1, w)


else

Return max(w, Compute opt(-l, w W);

Compute op(i-lw)
take exponential!
) Explain why does thisalgorithm
theWorstcase.
time to rün in

the above
(i) What changes should be made to
algorithm to make it run in polynomial time.
above
i)Consider an optimal solution to the
contain
problem. Is it poSsible for this solution to
subproblem
a- sub-optimal solution to, a.
2+2+3
Explain.
10 1,400
6512
[This qucstion papcr contains 8printed pages.]

oår Roll No.........


it:
Panerg96 1 GC-4
Sr. No. of Question
Unique Paper Code 32341401

Name of the Paper Design and Analysis of Algorithms


Name of the Course B.Sc. (H) Science
CÍmputeT.e

Semester
Duration: 3. Hours Maximsm Marks : 75

Instructions for Candidates


1. Write your Roll No. on the top immeditely on receipt of
this qåestion paper.

Question No. 1 of 35 marks is çompulsory:si*


3. Attempt any four questions from Q. No. 2. tÍ Q. NÍ. 7.

1. (a) Arrange th folló wing fynctions in the incréasing orVer


of their rate of growth:22^n, 2n, n'log(n), n2^n (2)

(b) Consider the ternary search algorithm for searching an


element in a given array: divide the array into three
equal parts by taking. two mid points, viz., left mid and
right mid. If the search element is:equal to the left-mid,
Qutput left mid; if it is equal to the right mid, gutput the

P.T.O.
2796 2/796 3

right mid; if it is smaller than the left mid, perform (c) A'shopkeeper has W marbles and n empty bottles.
recursive scarch in the lcftmost partition; if it is grcater Let c, Cgi... c, respectively denote the number of
than thc right mid, perform a recur_ive search in the marbles the bottles can contain. The shopkeeper wants
rightmost partition; clse porform n recursive search in to store the marbles in the bottles.
the middle partition. Thus, thc algdrithm performs 4
comparisons in cach iteration and reourses on one-third (i) Describe a greedy algorithm which minimizes the
number of bottles used.
of the array. \Write thc rccurrcnce rolation for thc running
time of the algorithm and isolve it. .!(4): (ü) How would you modify your algorithm if bottle i
also has an associated cost' price p, and the
(c) Consider an instance of the subsct sum problem gÍalis.tÍ minimize. the total cost of the bottles
where bound W = 6, Items with weights w, =2, w, = 2, used.
1i (4) (3+4)
W 2.

() Suppose an input to the båcket sort algorithm is


With the belp of thc above oxamplo arguc that the
nÍt uniformly distributed. Then: (i) will the sort still
memorized recursive algorithm solves lesser number of give:correçt output? (ii) what will be the impact of
subproblems than the corresponding iterative algorithm. 'relaxing this condition on the running time ? Justify.
(3)
(d) Consider a linear chain of 3 nodes shown below :
(g) Discuss the rån time complexity of the naive string
matching algorithm. (2)

or
3."(h) Compare the space requirements of adjacency list and
adjacency matrix representations of a graph having m
edges and n vertices. (3)
(i) Give an efficient algorithm to find the minimåm element
Arguc that such a chain cannot form a red-black trec.
in a max-heap. Give the exact running time of the
For each possible coloring of the three nodes, mention
(4) algorithm. (3)
thc property that is violatcd.

P.T.0.
2796 5
2796 4

() Would you use BS to fnd the shortest path betwe (b) Suppose agraph G has two edge-disjoint spanning trees
(two spanning trees that have no edges in common).
two nodes in a weighted graph with arbitrary cdge
(3) Argue that in this graph G, every pair of nodes forms
weights ? Justify vour answer. (4)
part of a cyclc.

(a) Give en efficient algorithm to check if a given undirected


4. (a) Consider the following recursive algorithm to find an
eraph has n cycle Dircuss the time complexity of your optimal schedule for weighted ínterval scheduling
algorithm. (5)
problem:

(b) For each of the following operations does a Red Black Compute_optG)
Trec work faster than a Binary Scarch Trce ? Elaborate
If j = 0 then
your answver

Return 0
(i) Search
Else
(ii) Postorder traversal
(5)
Retun max(v, + Compute opt(p), Compute_ opt(j-1))
different ways () Explain why does this algorithm take exponential
3 (a) A prioTity qucuc is implemented in two
max heap and an array sorted in decreasing
time to run in the worst case.
USing
order of key values (higher key value indicates higher (ü) What changes should be made to the above
following
priornty). Compare the time complexity of the
algorithm to make it run in polynomial time.
operations when performed on the two different
(6)
implementations of the priority qucuc.
(b) Suppose that an n x n array A consists of 1?s and 0°s
i) Finding the maximum element such that in any row of A all the 1's come before any
0's in that row. Give an O(nlgn) algorithm for counting
(ü) Deleting the maximum element the number of 1's in A. (4)
(6)
(iii) Increase the priority ofacertain element
P.T:0.
2796
2796 7
5.
(a) Give an cxample graph having four nodes that doos
have a dccidcd not to give fractional marks while grading the
topological ordering. (3) test. The instructor wishcs to sort thc n intcgcr scorcs
(b) Suppose a large array is in descending order. Design a linear time algorithm to
maintaincd with the
policy: the list is initially sorted. When new following perform this task. Also list all assumptions (if any) that
added, thcy are inserted at the end of elements are you, make to solvc the problcm. (4)
the array and
counted. Whenever the number of new
10, the array is resorted and the elements reaches
counter is 7. (a) Considet a k bit binary counter implemented using an
What strategy would be good tÍ use cleared. array Ansuch that AfO] stores the lowest order bit and
for the resorting of
the array? Why ? A[k-1] stores the highest order bit. The only operation
(4)
that can be performed on the counter is increment'.
(c) We use
Randomized-Select to select the minimum Using the aggregate method of analysis, determinc the
element of the array A =<3, 2,9, 0, 7>. amortised costper increment operation when a sequence
Describe a
sequence of partitions that would result in the worst of ninchements isis performed:' (3)
case performnanc- of the algorithm.
(3)
(b) A certain input to the merge sort algorithm is such that
6. (a) Which red-black tree properties may be violated when a the merging step always depicts the worst case behaviour.
node is deleted ? Determine the running time of the merge sort algorithm
(2)
for this instance. (3)
(b) Will
E Dijkstra's
.U msStill givc shÍrtest path between
two vertices if the edge weights are allowed to be (c).Consider the following algorithm that takes as input
an array of n integers and an integer T. It finds
negat+ve. If yes, justify yosr answer with an argument.
If no give an example. whether there exist two elements in the array that
(4)
Sum up to T and returns 1 on success and On

(c) An instructor has given a test to her class of n students. failure. (4)
",.

The maximum marks for the test is 100. The instructor

P.T.O.
2796

Targetsum (A, n, T)
Heapsort (A, I, n)
for i 1to n

flag BinaryS carchA, i1, n, T-A[]1)


if (flag)
return 1
cndif
cndfor
return 0

TargetSum uses the followiny algorithms:


Heapsort (Array,First, Last)
BinaryScarch(Array, First, last, clenent)
Analyze the worst case running tíme of TargetSum.

(1200)

You might also like