Professional Documents
Culture Documents
GATE - CSE Made Easy 342 392
GATE - CSE Made Easy 342 392
SyllabUS 3 Analysis, Asymptotic notation, Notions of space and time complexity, Worst and average case
analysis; Design: Greedy approach, Dynamic programming, Divide-and-conquer; Tree and graph traversals,
Connected components, Spanning trees, Shortest paths; Hashing, Sorting, Searching. Asymptotic analysis (best,
worst, average cases) of time and space, upper and lower bounds, Basic concepts of complexity classes - P, NP,
NP-hard, NP-complete.
1990 1 2 2AO7 2 B 18
1991 4 8 2008 11 22
1992 3 6 2009 3 5 13
1993 1 1 7
24fi 1 3 7
19S4 3 2 16
20X1 1 3 7
1995 3 1 I
1996 1 5 2 21
2012 3 3 I
1997 2 1 2 14 2013 4 3 10
1999 4 1 1 9 2014S;et-z 2 2 6
2000 1 1 3 2014 Set-3 1
a
J 5
3 5
2001 1
2015 Set-1 3 3 I
2W2 2 5. 12
I
2015 Set-2 3 3
E 13
2003 3
2044 I 7 15
2015 Set-3 2 3 I
2005 2 7 16 2016 Set-1 2 J I
2006 7 5 17 2016 Set-2 2 2 6
Algorithm Analysis and
Asymptotic Notations
1.1 Solve the recurrence equations L.7 Let f(n) = n2 logn and g(n) = n(logn)lo be two
T(n)=T(n-1)+n positive functions of n. Which of the following
T(r; = 1 statements is correct?
[1987:2 Marks] (a) f(n) = O(g(n)) and g(n) + O(f(n))
&) g(n) = O(f(n)) and f(n) + O(g(n))
1.2 What is the generating function G(z) for the (c) f(n) + O(g(n)) and g(n) + O(f(n))
sequence of Fibonacci numbers? (d) f(n)=a1g(n)) and g(n) = O(f(n))
[1987:2 Marks] [2001 : l Mark]
1.3 ) O("), where O(h) stands for order n is 1.8 In the worst case, the number of comparisons
1-<k(n needed to search singly linked list oflength n for
L.zl Let T(n) be a function defined by the recurrence (a) val(j) = o (1og n) &) val (i) = o (Jn )
T(n) = 2T(nl2) + Ji fo, n > 2 and T(1) = 1. Which (c) val 0) = @ (n) (d) val (j) = O (n log n)
1.30 Consider the following C code segment : (a) f (n) = O(g (n)); g (n) = O(h(n))
int IsPrime(n) 0) f(n) = a(g(n)); s(n) = O(h(n))
{ (c) g (n) = O(f (n)); h (n) = O(f (n))
int i, n; (d) h(n) = O(f (n));g(n) = a(f(n))
for(i = 2;i<= sqrt(n);i ++) [2008:2 Marks]
{
if(n%i==0) 1.34 The minimum number of comparison required
to determine if an integer appears more than n/
printf ("Not Prime\n");
2 times in a sorted array of n integers is
return 0;
(a) @(n) @) @(logn)
)
(c) @(og2n) (d) o(1)
return 1;
)
[2008 : 2 Marks]
Let T(n) denote the number of times the for loop Common Data Questions Q.1.35 and Q.1.36
is executed by the program on input n. Which of Consider the following C functions:
the following is TRUE? int f1(int n)
{
(a) r(n) = o(Jn) and r(n) = n(.,6)
if(n = - 0 | I n = = 1) return n;
else
(b) T(n) = O(Jn)and T(n) = Q(1)
return (2* f1(n-1) + 3 * f1(n- 2));
(c) T(n) = O(n)and T(n) = n(r[) i
int f2( int n)
(d) None of these
f
i
{2007 :2 Marksl
inti;
1.31 Arrange the following functions in increasing int X[N] , YlNl , Z[N] ;
)
relation T(n) = J, T$12)+ J; , T(1) = 1 evaluates
1.35 The running time of f1(n) and f2(n) are
to:
(a) @(n) and@(n) &) @(2) andO (n)
(a) Jn Gog n+1) &) Jt log t G) o(n)and@(2") (d) @(29and@(2")
1.38 The running time of an algorithm is represented 1.43 Suppose we have a balanced binary search tree
by the following recurrence relation: Tholding n-numbers. We are given two numbers
L andlf and wish to sum up all the numbers in
[n n<3 Tthat lie between Z and 1L Suppose there are m
r(n)= such numbers in 7.
. t'(;)."
otherwise
If the tightest upper bound on the time to
Which one of the following represents the time compute the sum rs O(n" logbn + m" logdn), tine
complexity of the algorithm? value of o + 10b + 100c + 1000d is
[2014 (Set-3):2 Marks]
(a) o(n) O) @(nlogn) -.
(c) @(n1 (d) @(n21og n) L.44 Consider the following C function.
[2009:2 Marks] int funl (int n)
{ inti,j,k,p,q=0;
1.39 LetW(n) andA(n) denote respectively, the worst for (i = 1;i<n; ++i)
case and average case running time of an { p=o;
algorithm executed on an input of size n. Which for fi=p' j>7; j=jl2)
of the following is,A,LWAYS TRUE? ++p;
(a) A(n) = a0M(n)) @) A(n) =@(w(n)) for (k=1;kcP;k=k*2)
(c) A(n)=o@(n)) (d) A(n)=o0M(n)) ++q;
[20L2:1Mark] ) return q;
)
l.4O The recurrence relation capturing the optimal
Which one of the following most closely
execution time of the Towers of Hanoi problem
approximates the return value of the function
with n discs is funl?
(a) T(n) = 2T(n -2) + 2 (a) n3 (b) n(og n)2
&) T(n) = 2T(n- 1) + n (c) n log n (d) n log (log n)
(c) T(n) = 2T(nJ2) + | [2015(Set-l):2Marks]
(d) T(n) = 2T(n - 1) + 1
l Markl 1.45 An algorithm performs (loglrDt/2 find operations,
12012:
N insert operations, (logN)1/2 delete operations,
l.4L Consider the following function: and (oglrl;1/2 decrease-key operations on a set of
int unknown (int n) data items with keys drawn from a linearly
{ ordered set. For a delete operation, a pointer is
inti,j,k=0; provided to the record that must be deleted. For
for (i = nl2;i<= n; i++) the decrease-key operation, a pointer is provided
for(j -2;j<=n;j=j*2) to the record that has its key decreased. Which
k=k+n/2; one of the following data structures is the most
return (k); suited for the algorithm to use, if the goal is to
achieve the best total asyrnptotic complexity
)
The return value of the function is considering aII the operations?
(a) o(n1 (b) @(nzlogn) (a) Unsorted array
(b) Min-heap
(c) o(n3) (d) O(n3logn)
(c) Sortedarray
[2013:2 Marks] (d) Sorted doubly Iinked list
L.42 Which one of the following correctly determines [2015 (Set-l):2 Marks]
the solution of the recurrence relation with 1.46 Consider a complete binary tree where the left
T(t1= 17 and the right subtrees of the root are max-heaps.
The lower bound for the number of operations to
r(n) = 2rf+l+logn
\2) convert the tree to a heap is
(a) @(n) &) @(n.log n) (a) a Gogn) @) ei (n)
(c) @(n1 (d) @(log n) (c) A (nlogn) (d) ei (n2)
[2014 (Set-2):1Mark] [2015 (Set-2): l Mark]
MADE EASY I Algorithms I 347
L.47 An unordered list contains n distinct elements. O(1) time complexity. If the words case time
The number of comparisons to find an element complexity of this function is O(n"), then the least
in this list that is neither maximum nor possible value (accurate up to two decimal
minimum is positions) of o is
(a) @(n log n) (b) @(n) Flow chart for Recursive FunctionA(ru)
(c) @(log n) (d) @(1)
E$+rl,
By using substitution method we get following The generating function for the Fibonacci
series: numbers G(z) is
n+ (n- 1) + (n-2) + (n- 3) ... 3 + 2 + l
Which is sum of 'n'natural numbers. G(z) =
l-z-22
n(n + 1)-n/-z\
- 2 - "\" /
348 I
GATE PreviousYears Solved Papers: [ft I MADE EASY
EG} @tut
f(n) = nz 1o*
"
I
1lk(n
o(") = o(1) + o(2) + o(B) + ... + o(n) g(n) = n(ogn)10
n(log n)10 < n2 log n
I n(n + 1)\ g(n) = o(f(n)
= ol -rn--- Ii =o(r,,) Whereas
f(n) * O(g(n)) because
n2 log n f n(log n)ro
Ero
Worst case of searching singly linked list is when
given element doesn't present at all in the singly
linked list. Using linear search then require "n"
comparisons in worst case.
Eco
100 10000 f(n) = 3n'/", g(n) = 2vilosr'
Therefore; --z f ^ loe- b -u
--,n loe.'
g(n)=n - I
r-loga
n2<n3forN>10000 -a - _]
'ProbabilitY = 1in.
100nlogn< 10000r":l:?"
100 Case-II If A[i] if found in the second attempt,
for k = 10000 Number of comparisons = 2
^ r nlognl (n -t) 1
.'. 100n1ogn='[l*-] ProbabilitY = -;-*;
n-\njlI n )
p=x s=1*x
,
E=n x x-
P=x' 2
s=1+x+- 2
Therefore, option (a) is correct.
x' *2 *3
Et"l P= T' ;.l
x
s=1*x+-+-
26
Recursive relation for procedure A(n) is
x- x
T{n; = t(Vn)+ c1 if n > 2
,6
D=
-. 4
x2 x3 xn xu
= t(.'6) = r(z-la)= s(m/2) s=1+x+-+ O*U*tn
For large value of y assume y --) - then i also
T(n) = ,(.,6)+ c1 if n > 2
tends to infinite it means increment of for loop
may tends to infinite. In the given function we
S(m) = af +.l + cl = O(Iog m) choose y as a large integer but not infinite. The
\2)
return value ofthe function fis s.
= O(Iog iog n) [.' n=2m + m = logrn]
=) T(n) = S(m) = O(1og log n) x2 x3 x' x5
s=1+x+-+-+-+-...+@
Option (c) is correct. 2 6 24720
*' "' xo x'
@t"l s=1*x+-+-+-+-*...*e
t2 !3 14 15
Consider each statement separately ^-^x
s-c
I. f(n) = (n + k)*
so, f(n) - (1 + n)- @t*t
(Assume k = 1 is constant) Any decision tree that sorts n distinct elements has
f(n) = 1+ mCrn + mCrn2+...'C-r- height at least log l4 . So the tightest lower bound on
f(n) = 61t '; the number of comparison based sorting is log ln
f(n)=2n+r
but from starling's approximation.
f(n) = 2n'2r
f(n)=72 1, = (n/e)"
Taking log both sides
f(n) = 912";
m. f(n) = lzn+ r
logln = log(n/e)"
f(n)=2zn'21 login = nlog(n/e)
f(n) = 2'2zn logln = n(logn-loge)
f(n) = 9122"1 1ogl4 = n(logn-1.44)
Therefore I and II are correct.
logl_q -nlogn-7.44n
So logln = O(nlogn)
3so I GATE Previous Years Solved Papers : (f,t I MADE EASY
@t"l
T(n) = 2T(nl2) +"',6' foo(0) foo(1) foo(2) foo(S) foo(n-1)
T\n) = 2' T(n t 2l + ",ti ...( 1) Even storing foo(i), 0 <= i < n the space
complexity is O(n).
= zlz.r(n t4\* Jin)*,E
lNote: Time complexity = Qlrr;1
= (z)' .T(n'. t 2'z1* Jr(r * nlz) ..,(z)
@tol
= (2)s .T(n t *7 +,tEe + ii + 2) ...(:B) The frequency of the for loop is i = i/2 = n/2 so
:
after termination of for }oop voIO = O(n) on
= \2), .rrn t2h7- o[iroi"l
1;t t )
average.
nnn
= O(n) j = n+r+7+"'1"e2" =o(n)
@,{p, @(ty
T(0)=T(r;=1 n= 2^
T(n) = 2T(nl2)+n
T(n) be computed as follows
T(2-) = T(2(ml2))+7
Let T(2'; = g1*1
log n
/\
T1n; = rlllztz)i
i=0
Then, S(m) = zSl
til
11l+r
logn Using Master's theorem
r(n) = "I(1)', S(m) = 61-;
i=0
T(n) = @(nlogn)
= @(Iog n) since rt= 2^
Now, T(n) = T(Z-1= g1*;
[T(n) can also proved by Master Theorem]
If T(n) = @(n log n) then it is aiso O(n log n) and
= O(ogn)
Therefore, option (b) is correct.
O(nz) but it is not A(n2).
@&t @(d)
Let the increment of j is 20, 27,...,2i for some value
of i so according to the question for while loop: 2i
(noriSlogrn.
" One extra comparison required for the
foo(O) foo(1) foo(2) foo(3) foo(n-1) termination of while loop. So total number of
I
foo(0)
./l
foo(0) foo(1)
,/ ]\
foo(0)
foo(1) foo(Z)
l
GJ; =
"'rlJr.T@
t g + J,rt z)* Ji
nlt1 .............. n ti1 n1r4.............. n 1,4
= (Jr)' .r(ntz,)+zJi .."(2)
@,tul where0<e<1<c<n
T(n) denote the number of times the for loop is
,rlogn 4 C'< n!
executed by the program on input n. = q 2" < n!
,rlogn
=
T1n.; = J"*r Assume c = 2
When n = 1 then best case occurs so T(n) takes h(n)<f(n)<s(n)
constant time i.e., T(n) = q111.
In worst case,
Ttn;= u6+1 soT{ni= O(n/,-)
@t"l
A<CandA<D
E<B and C, D < E as E is exponential function.
Now, we just need to see if C or D is larger^ h(n)'= O(f(n))
= h(n) < k.f(n) is true
In C, term n3/4 and correspondingly in D we g(n) = Q(f(n))
-n_ + C(n)> k.f(n)is also true
have loge n.
n3/4 is larger than loge x. @ttr
So,D<C. Consider an array of n elements which stored
integers in sorted order, A[1], A[2], ..., A[n]. If
we want to search an element x with the help of
MADE EASY I Algorithms I 3s3
=T(n)=2T(n-1)+1
@tcl
T(o; = I @,ru.'t
T(t) = 1
Outerloop execute for 1 + 1 iterations. Innerloop
T(n) - 2T(n-1)+3T(n-2) 2
T(2) = 2T(1) + 3T(01 ="2.1+ 3.0 = 2 executes for log rn iterations. In every iteration
T(3) = 2T(2)+ 3T(1)=2.2+3.7-7 n
ofinnerloop,2I is addedto k.
T(4) = 2T(3) + 3T(2) = 2.7 + 3.2=20
T(5) = 2T(4,\+ 3T(3)=2.20+3.7=61 n
Return value = ; x number of outer ioops x
2
T(6) = 2T(5) + 3T(4) = 2.61+ 3.20 = 182
number of inner loops
T(7) = 2T(6) + 3T(5) = 2.782+ 3.67= 547
T(8) = 21(7) +3T(6) = 2.547 +3.182 = 1640 - n2\2
*[1*t)nos'l
)
So f(8) returns t640, fr(n) is the nonrecursive
= O(n21og n)
version offr(n) so the output offr(S) is 1640.
@t"l @bt
T(n) = 2.7(nl2) +logn.
In each pass there can be at most one swap. There
are n such passes in selection sort i.e. maximum fby master's theorem casel]
n swap will happen in worst case. =O(ru)
@t"l @s"t.
Complexity is decided for large values of n only, O(rn + iogn) = O(n'l|ogtn + mL logan)
So, T(n) = T(n/3) * cn for n > 3 - a= 0, b= 1, c=7,d=O
using master's theorem + a+ 10b + 100c + 1000d
here & = 1,b=3,logoa=logr1=0 =10+100=110
f(n)=6r.=@(n1)
since ,1oss
u
= n0 is below f(n) = 61,rt1
@'tE),
int funl(int n)
this belongs to case III of master's theorem, It
where the solution is T(n) = @(f(n)) = @(n)
inti,j,k,p,q=20
for (i = 1; i < n; ++i)
{
3s4 i GATE Previous Years Solved Papers : lfl I MADE EASY
P=0;
for (=n; j<7; j=jl2) iog n times for
@e.l
= X- 1+23+33 + 43 + ..". tLB
eachi=+Total=nxlogn
++p;
I n(n,+711" (n +7\2
for (k=1; kcp; k=kx2) = log log n X_ l-e I
,l
= tn2 =O(nr)
times for each i + Total = n log n
++q;
x- @(na)
X_ o(n5)
)
return q; + Return value = O(n log log n)
x- a(n3)
)
Time complexity of above program = O(n
@tol
1og n)
When ever the vaiue of 'sin n'va1ue is -1, then
Return value q = O(n log log n)
g(n) = 1. {sin n value ranges lrorn -1 to +1}.
@r"l Hence f(n) = O(g(n)) is violated. Hence I is false.
o(N!-rqN )
Hence f(n) = Q(g(n)) is violated. Hence II is
NInr heap O(N )oelO o
$,{;s r ) O(1ogN)j' O(l- logN)
false.
Soted bsN
array
Olloslilr': oorl o$1rqr) orN'zt
Soted
doubly
linked list
o(N.,i..n) orxl o(,G*r) o (".r,ur
) oixl @sot,
as.-*l
+,
.'. Unsorted array is best. l {lr.zr I
-1.-/\ V
IIII
Divide and Conquer
2.1 Let P be aquicksort program to sort numbers in (d) Depth-first search can be used to find
ascending order. Let t1 and t2 he the time taken connected components of a glaPh
by the program for the inputs 17 2 3 4l and [5 4 3 [1994:2 Marks]
2 11, respectively. Which of the follorn'ing holds? 2.7 Merge sort uses
(a) t, = t, (b) tr > tz (a) Divide and conquer strategy
(c) t, < t, (d) tr=tz+5log5
@) Backtrackingapproach
[1987:2 Marks] (c) Heuristic search
oo (d) Greedyapproach
Find a solution to the following recurrence
equation [1995:1Mark]
2.8 For merging two sorted lists of sizes m and n
r(n) = ,[;)." into a sorted list of size m*n, we required
comparisons of
T(t; = 1 (a) O(m) ft) o(n)
[1987:2 Marks] (c) O(m + n) (d) O(logm + logn)
2.3 Assume that the last element of the set is used [1995: l Mark]
as partition element in Quicksort. If n distinct
2.9 Which of the following statements is true?
elements from the set [1.....n] are to be sorted,
give an input for which Quicksort takes
I. As the number of entries in a hash table
increases, the number of collisions increases.
maximum time.
II. Recursive programs are efficient
lLggz:2 Marksl
III. The worst case complexity for Quicksort is
2.4 Following algorithm (s) can be used to sort n o(n)
integers in the range [1 ... n3] in O(n) time? IV. Binary search using a linear linked list is
(a) Heap sort @) Quick sort effrcient.
(c) Merge sort (d) Radix sort (a) I and II (b) II and III
[1992:2 Marks] (c) I and IV (d) I and III
2.5 The recurrence relation that arises in relation [1995: l Mark]
with the complexity of binary search is 2.L0 The recurrence relation
(a) T(n) = T(nl2) + k, k is a constant
T(r; =2
(b) T(n) = 2T(n/2) + k, k is a constant
(c) T(n) = T(n/2) + Iog n r(n) = ,r[;)."
(d) T(n) = T(n/2) + n
Has the solution T(n) equal to
[1994:2 Marks]
(a) O(n) 0) O(Iogn)
2.6 Which one of the following statements is false? (c) O(n3/a) (d) None of these
(a) Optimal binary search tree construction can [1996:2 Marks]
be performed efficiently using dynamic
programming z.Ll Quicksort is run on two inputs shown below to
cannot be used to find sort in ascending order
ft) Breadth-first search
connected components ofa graph (, 1,2,3 ..... n
(c) Given the prefix and postfix walks over a (ii) n, n - 1, n - 2, ...,2, 1
binary tree, the binary tree cannot be uniquely Let C, and C, be the number of comparisons made
constructed for the inputs (i) and (ii) respectively. Then,
3s6 I GATE Previous Years Solved papers : !f,t I MADE EASY
2.21 Which of the following sorting algorithnis has If p = 10, q = 100, r = 2O.s = 5 and t = 80, then
the low'est worst-case compiexity? the minimum number of scalar multipiications
(a) Merge sort needed is
&) Bubble sort
(a) 248000 (b) 44000
(c) Quick sort (d) Selection sort
(c) 19000 (d) 25ooo
12$07 : l Markl
[2011 :2 Marks]
2.22 In the following C function. let n > m. 2.26 The worst case running time to search for an
int gcd (n, m) element in a balanced binary search tree witli
(
1 n2" elements is
if (n%m - - 0) return m; (a) @(n log n) (b) o(n2)
n = n9'6m; (c) @(n) (d) o(Iogn)
return gcd (m, n); 12A12: l Markl
)
2.27 A iist of n strings, each of length n, is sorted into
How many recursive calls are made bv this
lexicographic order using the merge sort
function? algorithrh. The rvorst case running time of this
(a) O(ogrn) (o) e2(.r) computation is
(a) O(n log n) @) O(n2log n)
(c) @(ogrlogrn) (d 0(J;)
(c) O(n2 + log n) (d) O(n2)
12007 z 2 Marksl l20l2z 2 Marksl
2.23 Consider the Quicksort algorithm. Suppose there 2.28 S/hich one of the following is the tightest upper
is a procedure for finding a pivot element which bound that represents the tirne complexity of
splits the list into sub-lists each of which contains inserting an object into a binary search tree ofn
at least one-fifth of the elements. Let T(n) be the nodes?
(a) o(1) (b) O0og rc)
number of comparisons required to sort n
(c) O(ru) (d) O(n iog ru)
elements. Then
(a) T (n) S 2T (n/5) + n [2013: l Mark]
(b) T(n) < T (n/5) + T( 4nl5) + n 2,29 Let P be a quicksort program to sort numbers in
(c) T (n) S 2T (4nl5) + n ascending order using the first elemerrt as the
(d) T(n) <2T (nl2) + n pivot. Let l, and l, be the number of comparisons
[2008:2 Marks] made by P for the inputs 17 2 3 4 5l and [4 1 5 3
2l respectively. Mich one of the following holds?
2.24 In quick sort, for sorting n elements, the (n/4)th (a) lr=5 &) lr< lz
smallest element is selected as pivot using an (c) tr, tz (d) tr= t,
O(n) time algorithm. What is the worst case time
[2014 (Set-1): l Mark]
complexity of the quick sort?
(a) o(n) &) @(nlogn) 2.30 The minimurn number of comparisons required
(c) @(n1 (d) @(n2logn) to find the minimum and the maximum of 100
[2009:2 Marks]
numbers is
[201a (set-l):2 Marks]
2.25 Four matrices M,, M2, M3 and Mn of dimensions
p x q, q X r, r x s and s x t respectively can be 2.31 You have an -'
array of ru eiements. Suppose you
multiplied in several ways with different number implement quicksort by alwa;rs choosing the
of total scalar multiplications. For example when
central element of the array as the pivot. Then
multiplied as ((M, x Mz) x (Ms x M+)), the total the tightest upper bound for the worst case
perfbrmance is
number of scalar multiplications is pqr + rst *
prt. When multiplied as ((M, x Mz) x M3) x MJ,
(a) O(n2) (b) O(nlogn)
the total number of scalar multiplications is
(c) o(nlogn) (d) O(n)
pqr+prs+pst. [2014 (Set-3): l Mark]
3s8 i GATE PreviousYears Solved Papers: [S I MADE EASY
Eivide'drrd Conquer
Et*t {a},,
A merge sort is comparison based sorting
t1 is iess than t2
Sorting 11. 2 3 4l takes less time compared to algorithm and divide-and-conquer algorithm.
sorting 15 4 3 211 list. First list has 4 elements
and second list has 5 elements. Both lists are Et"'l
The number of comparisons required in the worst
worst cases of quick sort.
case is O(m + n).
Es*t 4ei In
By using substitution method we get following
I. hashing, as the number of entries in a
series:
hash table increases, the number of collisions
< rfa.)*-5+-:=...n+n*n
- I ok I ok-I 9k-'2
22 2"2
increases.
\a -/ a
II. It is not always true that recursive programs
So put k = 1og, n then we get
= are efficient.
," )*,|.l*l*f
rl'[2,o*r" J --L)
' "l Zo ' 2r ' 22"'2]oezn-r)
Quicksort is a comparison sort which is worst
case makes O(n2) comparisons.
@t"l @lul
Binary search only haifofthe array. Use Master Theorem ,rtoez
2
2 fi
s", r(|).N @*tl
A sorting algorithm is called stable if it keeps
EolConnected components of a graph can be
elements with equal keys in the same relative
order in the output as they were in the input.
computed in linear time by using either breadth-
first search or depth-first search.
So option @) is false.
360 i GATE Previous Years Solved Papers : lft I MADE EASY
@trl @t"l
When we uses the max heap data structure then
Given: 20, 47,15, 8, 9, 4. 40, 30, 12,77
2-way merge sort so group of 2 is taken at once. there are [lognl sorted lists of which each
2nd pass:
contains [n / Iog n ] elements. Construction of
.1, 9, 30, .10
heap takes O(Iog logn) time and if we have
I n / 1og n_l elements then worst case time
complexity is O(n log 1og n).
@or
@GD@@(D
T'he order of elements after second pass of the
If the median of n elements can be found in O(n)
time and we select the median as pivot. Then
quicksort sort n elements of an array A[1],...,
a.Igorithnr is 8, 15, 20,47.,4, 9, 30, 40,12,77. A[n] as follows. We permute the elements in the
array so that for some j all the records with key
@t"l less than v appear in A[1],..., A[] and all those
Take starting 2 elements of array, if sum of these with keys v or greater appear in A[ + 1],..., A[n].
tu'o are less than 1000 then return ihose We then apply quicksort recursively to A[1],...,
elements. otherwise return false. A[j] and to A[ + 1],..., A[n].
The recursion equation becomes for some value
@t"t ofi
Randomized quick sort worst case time
complexity = O(n2) r(n) s *>(tlt -r)+ r(n - i))
@t"l The solution of the T(n) S @(n log n)
The usual O (n2) implementation of insertion sort Given to find median O(n) time required.
to sort an array uses binary search to identify
the ponition, the worst case running time will
@t"t
Sorting Algorithm Worstcare complexity
remain O 0r2). The time required to insert an
(with n inputs)
element x into a binary search tree is bounded
Merge sort O(nlogn)
by a constant times the number of comparisons
Bubble sort O(rr2)
made between x and elements already in the tree.
Quick sort o(n2)
Thus we can measure time in terms of the Selection sort o(n2)
number of comparisons inade. In worst case
implementation of insertion sort takes O(n2). So @tat
in the worst case adding n elements to a binary Let T(m, n) be the total number of steps.
search tree could require O (n2) time. In expected So T(m, 0) = 0, T(m, n) = T(n, m mod n) on
case means element are sorted in increasing order average
T. =1.+ @tur
Irror,+...+r. 1)
The recurrence tree for merge sort will have
Tn =S, height n and O(n2) work wiII be done at each
1 level ofthe recurrence tree (Each level involves
Srr=1 +-(SoSr+... +Sn-t'.)
n comparisons and a comparisontakes O(n) time
1 in worst case). So time complexity of this merge
s, = 1 * r, *1 (so S, +... + S,) sort will be O(n2log n).
1
= 1+ n+1(n(S"_r)+S") @t*l
In the worst case length of binary search tree
11 can be 0(n).
=1+n+1 =Sn+r', 1i Soinsertion of an ohject will take O(n) time in
So T,, = O(logrn) + 0(1) worst case option (c) is correct.
T= @0ogzn)
@tol
@ol Inputl:'112 3 4 51
Input2: 14 ). 5 3 21
If we wants to sort n elements with the help of
(a) [1 2 3 4 5]: Already elements are in sorted
Qucksort algorithm. If pivot elements which split
the list into two sub-Iists each in which one list order
. 5(5-1)
comparisons are required.
contains one-fifth element or n/5 and other list ]i
contains 4nl5 andbalancingtakes n. So I fr= 10
T(n) < T(n/5) + ti+n/r)+ n (b) [4 1 5 3 2]: Elements are in random order.
n 5n-n 4n Chocsing first elernent as pivot wiil give less
I
[Notetr-b= --t
50 comparisons compared to tr.
tz< t,
@<at
The relation T(n) = T(nia) + T(3n/4) + n @s"t.
The pivot element is selected in such a way that it n=100
will divide the array into 1/4th and 3/4th always To find maximum and minimum, minimum
number of comparisons using divide and conquer
solving this relation give O(n log n).
_ [:rl-]_r_13*100'i_,
@t*l lrl
l"l
\ I )
Greedy Method
t
i
i
:
i
I
-,-***^t
(a) 29 &) 31
[1991 :2 Marks] (c) 38 (d) 41
minimum weight. Which of the following path algorithm on the following edge-weighted
statements is false? clirected graph with vertex P as the source'
(a) Every minimum spanning tree of G must
contain e-,,,
(o
(b) If e-u, is in a minimum spanning tree, then
its removal must disconnect G
(c) No minimum spanning tree contains e*u'
(d) G has a unique minimum spanning tree
P)
12002:2 Marksl
@) 1_B,2_D, 3-C,4_A 3.13 Are all tasks completed in the schedule that gives
(c) 1-C. 2-D, B-A, 4-B maximum profit?
(d) 1-8, 2_A,3-C, 4-D (a) All tasks are completed
[2005: t Mark] O) T, and Tu are left out
(c) T, and T, are left out
3.10 A undirected graph G has n nodes. Its adjacenc;, (O T* and Tu are left out
matrix is given by an n x n square rnatrix whose
[2005:2 Marks]
MADE EASY I Algorithms i 36s
3.74 What is the maximum profit earned? 3.19 The characters a to h have the set offrequencies
@) 7a7 (b) 165 based on the first 8 Fibonacci numbers as foilows:
(c) 767 (d) 175 a : 1,b : l,c:2,d : 3, e : 5, f: 8. g: 13,h : 21
[2005:2 Marks.l A Huffman code is used to represent the
characters. What is the sequence of characters
. 3.15 Consider the polynominal p(x) = &0 * arx + arx2 +
corresponding to the foliorving code?
aox3. where ai t 0, Vi. The minimum number of
110111100i11010
multiplcations needed to evaluate p on an input
xis (a) fdheg (b) ecgdf
(a) 3 (b) (c) dchfg (c) fehdg
4
(c) 6 (d) e [2006 : 2 Marks]
[2006: l Mark] 3.20 In an unweighted, undirected connected graph,
the shortest path from a norle S to every other
3.16 Consider a weighted complete graph G on the vertex
node is computed most efficientl5r, in terms of
set {v, vz, ..., vn} such that the weight of the edge
time complexity. bi,
(v,, v1) is 2li - j l. Ttre weight of a minimum
(a) Dijkstra's algorithm starting from S.
spanning tree ofG is
(a) n- 1 (b) 2n-2 &) Warshali's algorithm
(c) performing a DFS starting from S
/n) (d) performing a BFS starting from S
(c) l;l (drtr2
\z.t [2007 :2 Marks]
[2006:1Mark] 3.2L Let u be the minimum weight among all edge
3.17 To implement Dijkstra's shortest path algorithm rn'eights in an undirected connected graph. Let e
on unweighted graphs so that it runs in linear be a specific edge of weight ro. Which of the
time, then data structure to be used is followingis FALSE?
(a) Queue (b) Stack (a) There is a mjnimum spanning tree containing
(c) Heap (d) B-I\"ee e.
3.23 What is the average length of the correct answer (b) The minimum cut in G iras a least two edges
to above question? (c) There are two edges-disjoint paths between
(a) 3 b) 2.1875 every pair ofvertices
(c) 2.25 (d) 1.781 (d) There are trvo vertex-disjoint paths betu.'een
12A07 :2 Marksl every pair ofvertices.
[2008:2 Marks]
Consider n jotrs J, , J2,.. ., J. such that job J, has
execution time t, and a non-negative integer 8.27 Dijkstra's single source shor'uest path algorithm
weight w,. 'Ihe v,,eighted mean compietion time when run from vertex a in the beiow graph,
computes the corrects shortest path distance to
n ln
ofthejobsis definedtobe )' u, 7 I ),*, where
A 'l -r..
ll
that
T, is the completion time of job J,. Assuming
tD
there is only one processor availabie, in what 23
order must the jobs be exccuted in crder to
minimize the weighted mean completion time of
(a) onlir vertex a
the jobs?
(b) only vertices a, e, f, g. h
(a) Non-decreasing order of t,
(c) only vertices, a, b, c, d
&) Non-increasing order of w,
(d) all the vertices
(c) Non-increasing order of w,t,
(d) None-inci:easing order of w,/t; [2008:2 Marks]
&) (c, e), (c, 0, (f, d), (d, a), (a, b), (g, h), (h, a
,.-'
0. (s.i) '..-r' 6 \:-/
G) (d, 0, (f, c), (d, a). (a, b), (c. e), (f, h), (9, h),
' (g, i)
Which one of the fo11o-'ving is NOT the sequence
of edges added to the minimum spanning tree
(d) (h, s), (g, i), (h, 0, (f, c), (f, d), (d, a), (a, b), using Kruskal's algorithm?
(c, e) (a) (b, e) (e, 0 (a, c) (b, c) (f, g) (c, d)
[2008 : 2 Marks] (b) (b, e) (e, 0 (a, c) (f, g) (b, c) (c, d)
(c) (b, e) (a, c) (e,0 G,, c) (f, g) (c, d)
3.26 G is a graph on n vertices and 2n - 2 edges. The
(O &, e) (e,0 (b, c) (a, c) (f, S) (c, d)
edges of G can be partitioned into two edge-disjoint
spanning trees. Which of the following is NOT
[2009:2 Marks]
true for G? 3.30 The weight of a sequence a0, a1, ... , ?n_1 of real
(a) For every subset of k vertices, the incluced numbers is defined as ao + arl2 +
subgraphhas a most 2k -Z edges. an ,l2n- . A subsequence of a sequence is obtained
1
MADE EASY I Algorithms 1 367
below.
(c) SACDT (d) SACET
12012:2 Marksl
v3 ---\ Which one of the following is the tightest upper
bound that represents the number of swaps
4
required to sort n numbers usrng selection sort?
/a (a) O(log n) &) O('z)
vr) Y2
(c) O(ru log n) (d) O(nz)
[2013: l Mark]
What will be the cost of the Minimum Spanning Consider the tree arcs ofa BFS traversal frorn a
Tree (MST) of such a graph with n nodes? source node W in an unweighted, connected,
368 I GATE Previous Years Solved Papers : ffi | MADE EASY
undirected graph. The tree Tformed b5, the tree 3.41 Let G be a weighted connected undirected $aph
arcs is a data structure for computing with distinct positive edge weights. If every edge
(a) the shortest path betrn'een every pair of weight is increased by the same value, then which
vertices. of the following statements is/are TRUE?
(b) the shortest path from l7to every vertex in P: Minimum spanning tree of G does not change
'
the graph.
Q: Shortest path between any pair of vertices
(c) the shortestpaths from l4ltoonlythose nodes does not change
that are leaves of 7. (a) P only (b) Q oniy
(d) the longest path in the graph.
l Markj
(c) Neither P nor Q (d) Both P and Q
[2014 (Set-Z):
[2016 (Set-l):1Mark]
3.39 Suppose P, Q, R, -Q, 7 are sorted sequences
3.42 Let G be a compiete undirected graph on 4
having lengths They
20. 2.1, 30, 35, 50 respectivel1,..
vertices, having 6 edges u'ith weights being 1, 2,
are to be merged into a single sequence by
3, 4, 5. and 6. The maximum possibie weight
merging together two sequences at a time. The
nrimber of comparisons that wiil be needed in that a minimum weight spanning tree of G can
the worst case by the optimal algorithm for doing have is
this is [2016(Set-l):2Marks]
[2014 (Set-2):2 Marks]
3.40 The graph show:n below has 8 edges with distinct 3.43 G= (V, E) is an undirected simple graph in which
integer edge weights. The minimum spanning each edge has a distinct weight, and e is a
tree (\{ST) is ofweight 36 and contains the edges: particuiar edge of G. Which of the following
{(A, C), (8, C), (8, E), (E. F). (D. F)} The edge statements about the minimum spanning trees
weights of only those edges which are in the MST (MSTS) of G is/are TRUE?
are given in the figure shown below. ?he I. If e is the lightest edge of some cycle in G,
minimum possible sum of weights of all 8 edges ihen every,'\'tST of G includes e.
of this graph is _. iI. If e is the heaviest edge of some cycle in G,
then every MST of G excludes e.
(a) I only ' (b) II only
(c) both I and II (d) neither I nor II
[2016(Set-l):2Marks]
IIII
[2015(Set-1):2Marks]
Greedy Method
f,sot. @trl
The activities are A. B, C, D. E, F, G and H. The
starting and ending times are "a. b. cu au d" co e" f"
s eS fE hSUE
bE dCC'S e h". E
=O(mlogn) tl
@ @
@sot. Include P Include Q Include R
O(m + n), edges are sorted so no need to make
min-heap. So deletion from min. heap time is
saved.
o'-rc
:ti'/tI
o-re
O i C tY*ie
re
-ir,i
@t"t
All edges are distinct weights. include U Include R Include T
Removal of e-n" may not disconnect G, because Total Distance (from source P)
other edges may cover the vertices incident =1+1+1+2+3=8
with e-"r. Node sequence = P, Q. R, U, S, T
@rr EEIrar
Number of vertices in the graph n = 10 so after (a) and ft) produce disccnnected components
adding n- 1 = 9 edges which contains all vertices with the GIVEN order in options which is
and doesn't form a circuit in the minimum NEIVER allowed by prim's algorithm.
spanning tree of G. (c) produces connected component everyinstant
a new edge is added BUT when first vertex is
chosen(first vertex is chosen randomly) first
edge must be the minimum weight edge that
is chosen. Therefbre (a,d) MUST be chosen
BEFORE (a,b). Therefore (c) is false.
@r"l
BeIIman-Ford aigorithm : O(nn-r)
Kruskal's algorithm : O(mlog n)
Flo},d-Warshall algorithm : O(n3)
Topological sorting : O(n + m)
Totalweighl= )w(l)
i =1
@(c) @,r"1
Undirected graph G contains n nodes. Total profit earn by algorithm
123...n = 15 + 20 + 30 + 18 + 23 + 76 + 25 = L47
1 011...1 @t"l
2 i01...1 p(x) = ao * arx + arx2 * asx3
Apply Horner's rule to evaluate the p(x)
J 1i0..'1 p(x) = ao + ((arx + az)x + ar)x
:
n lil'.'0 t=a"^x
In undirected graph G, the cilagonal elements are
t=tiuz
0 means there is no self }oop of any vertex. Where
t=t*x
t=t+al
each vertex in G is connected through n - 1
t=t*x
vertices in the graph G so G is a complete graph.
t=t*ao
In a complete graph apply the Kelly's theorem So, 3 minimum number of rnultiplications needed
for the total number of minimum spanning trees to evaluate p on an input x.
in a complete graph G with n vertices is n.-2 so
G has multiple distinct MSTs. The cost of a @tol
spanning tree is sum ofali edges. IfG contains n Given vertex set of G = {v, vr. ..., v.}
vertices then we wiII must stop the algorithm Weight of an edge = Zli-j | : (v,. v,) e G
after adding the n- 1 edges so each spanning tree
Y, :, 1, I, Y,... I, i. MST.
have a cost n- 1. 2222
In the case of minimum spanning tree of a graph
@t"t G we will add upto (n - 1) vertices, so the weight
Option (a) is always true. of a minimum spanningtree of G
Option (b) is not true when e is not part of a n_1
cycle.
Option (c) is not true when e i.s part of a cycle
>2lY 'v,-,
= i=1 I
and all edge weights are same in that cycle ,-, n-1
Option (d) is need not be true when e is not part = 2> lV, - V,_, I = 2>t1l
of a cycie. i=1
Option (a) is always true as only the min weight =2In-11
edge in a cut set will be part of a minimum = 2(n-7)=2n-2
spanning tree.
@te)
@trl Heap and priority queue are very neat data
Dijkstra's implementation fqr single source structures allowing:
shortest path . Add an element to heap with an associated
(r) Using binary heap takes prioritSr.
o((lnl+lVl)log lVl) . Remove the element from the heap or priority
(ii) Using Fibonacci heap takes queue that has the highest priority, and
O(lEi+lVl log iVl) return it.
. Peak at the element with highest priority
@t*l without removing it.
A simple way to implement a heap or priority queue
The given problem is job scheduling problem 9
data t;.pe is to keep a list of elements, and search
tasks are T1, T2, ...., Tn.
through the list for the highest priority which gives
J is initially empty then according to deadlines it
O(n) time to impiement Dijkstra's shortest path
inciudes {T1, T2, TB, Tb, Tz, T8, Te}.
algorithm on unweighted graph.
So Tn and Tu can't be included in J
MADE EASY I Algorithms | 371
@tcl
The two least frequent characters are taken as
children of a newly made note and the frquencl'
of the newiy made node and the frequency of
newly made node is made equal to the sum of
those two childrens.
The same procedure is repeated till all nodes are
finished.
@rar
The average length ofthe tree is
1111
=1x _ +2x . +3x - +4x 16_ *5
-24-8
x ,:1 = 1.781
oz
@tar
The execution must follow SJF. Since we have
to minimize W, * T, where wi is a constant, so
we can cnly minimize tt,e product by atleast
decreasing the T, for a job by executing shorter
@ral jobs first because that will reduce completion
In an r.rnweighted graph performing a BFS time for the jobs that follow.
starting from S takes O(n) time if graph contains
n vertices. Dijkstra's algorithm only find the @tl
single source shortest path and takes O(n:) time First thing that we note is that Frims Algorithm,
but it is good for weighted graph. Warshall's during execution, always generates a subset of
algorithm for all pair shortest path takes O(n3) edges tirat is connected. So prim's algorithm
time but it is aiso applicable for weighted graph. always generates a connected component during
its execution.
@(d) Second thing to note is that, only getting a
Wbethe minimum weight among alledgeweights
connected graph does not suffice here. The edge
in an undirected connected graph. e is the specifi.c
chosen next must be the smallest possible edge
edge of weight w. It maybe possible that another
as per GREEDY strategy. So let's check the
edge in the graph having weight w which had
options.
been adrled to minimum spanning tree and when
372 | GATE Previous Years Solved Papers : [fl I MADE EASY
n
that adding (a, c) does not form a cycle with
anytree = d, belongsto atree ifeach d,is already added edges.
Ze
I
i=1 .'. Choice (d) is not the sequence that would be
positive and n-
but in given probiem e = 2rt
e= 1
allowed by Kruskal's algorithm.
'/
@tul
From vertex 1 to vertex 2 means from B to C. So a'D
we choose ihe path
A 16
1/\,, V. +
\ Yo: O". -.V-" - V, - Vr - Y1 - V,,)
B' Aiti'
1C
\rvi . \/\ - Jr
6-
c1
.t,
31
-
E
Sow-eigh'l=1+ 4+3-8 @tal
E.g.
@rrl 2
\Ve observe a pattern in n'eight of IIST being
fornred:
Forn=3=(1+2+3)+(1)
For n = 4 + (1+2+3+4) + (1+2) G:2
For n = 5 + (1+2+3+4+5) + (1+2+3)
For n = 6 + (1+2+3+4+5+6) + (1+2+3+4)
In general, total weight of MST for n:
d
n tu-2
= >,+)i
i=1
=n2-n*
i=1
1
4
@t"l
G':
9
374 |
GATE Previous Years Solved Papers : lft I MADE EASY
E.g. SoI;
2 1 Given files: 20, 21, 3A,35, 50
Step-I:
f3!- .r-r--6ro-l
) G G'
---r\-
!vt
1\- e9 e9
2 4 43 Comparisons
= + 24- 1 comparisons maximum]
l2A
Step-II:
64 Compzirisons
.'. we can make different as well as same MST
also.
.'. option (d) is correct.
@{d}
A B C D E F G.T
S +@ 7a
B @ i@
::) 93 Compariscn .@
A t\l
\,:-/ 7*
Step-fV:
C -/(9-
E 't @x riht
\7 = SACET
@rut,
In selection sort we starts with unsorted array,
and mark the index from where we starts. Then
we find the minimum element in the array and
swap it with marked index. Now we mark the
next index and again find the minimum in the
array and swap with marked index. 1<Q Comparisons
In every iteration there is a swapping so in the .'. 158 + 93 + 64 + 43 = 358 comparisons
worst case it will take O(n) swaps.
Option (b) is correct. @srr"
IMSTI = 36 and graph has distinct integer
@,G) edge weights.
BFS traversal from Wgives. Shortest path from B
Vllto every other vertex in the graph,
D
10+15+16=69
MADE EASY I Algorithms | 37s
re
change. here NIST is not include edge'BD'i.e..
So staternent is wrong.
@s"t"
Since graph will be compiete graph contain 4
vertex and 6 edges with weight 1. 2. 3. 4,5,6.
In second statement "if in any graph 'e' is the
d !\-L---------?6
;li\u)(',/,
heaviest edge in then every MST must exclude
it" is correct statement.
la
IITI
dE- 4
Dynamic Prograrfirming
4.8 The values of l(i,j) couid be obtained by dynamic 4.10 What is the time complexity of Bellman -Ford
programming based on the correct recursive single-source shortest path algorithm on a
definition of l(i, j) of the form given above. using complete graph of n vertices?
an array L [M, N], where M = m + 1 and N = n (a) O(n2) &) @(n21ogn)
* 1, such that L[i,j] = l(i, j). (c) @(n3) (d) @(n3iogn)
|',Bynamic
Programrning " ,
4.1 (b) 4.2 (a) 4.3 (a) 4.4 (d) 4.5 (b) (c) 4.7 (c) 4.8 (b) 4.9 (a)
a.10 (c) 4.t3 (c)
Dynamic Pr,ogramming
E[tnr @rol
The binary search tree is as follows: If an algorithm Q solves subset-sum problem in
O(nW) time rvhere w is an integer which is
constant so Q solves the subset-sum problenr in
O(n) time because Wis a constant and input must
encoded in binary.
@tur
The subset-sum problem is NP-complete
problern.
The number of nodes in the left subtree and right For example given a set S = {-7, -3, -2. 5, 8} the
subtree ofthe root respectively is (7, 4). Therefore algorithm determine rvhether the sum of the
option ft) is correct" element of S'is zero such that S'c S. For example
if S'= {- 3, - 2, 5} ihen return yes.
@;,rat In given dynamic algorithm x is a two
Be1lman-Ford algorithm is used to find all pairs dimensional Boolean array contains n rows and
shortest distances in a graph and it is dynamic W + 1 columns where W is a positive w,eight or
programming technique. sum.
x[i.j] 1(i(n,0<j<W
E("1 The ith row detprmines the element of subset of
A B-tree is similar to 2-3 tree. Consider a B-tree
S, and jth column determines the corresponding
oforder 4.
weight.
If 2<i<nanda<j<W
Let subset S'= {a,, a2, .., a,i} the weight 8s 81, ...,
a, is W.
A B-tree oforder rn contains n records and ifeach So X[i,j] =X[i-1,j] .rXli-1,j-aJ
contains b records on the average then the tree The row starts from 2"d position so
-.l i = i - 1. The column position starts from j but
has about [n I f leaves. If we split k nodes along
we will add upto a,th position so j = j - a,.
the path from leaves then
k<1+log.,, [n/bl @t"l
The entry X[n, W] is true, because we find the
In given problem n = 10, b = 3, rn = 4 So weight W of subset of S which contains n
k<1+lognr, [tO/g-l elements.
k<1+Iog24
ks1+2
k<3
MADE EASY I Algorithms tr 37e
4t"l @sar:
l(i, i) By drawing weighted undirected graph with 4
=0;ifeitheri=0orj=0 vertices from given matrix is
= l(i- 1, j - 1);
ifi, j > 0 andr[i- 1]=YLi - 1l
= max (/(i - 1, i), l(i, i - 1));
if i, j > 0 andr[i - 1] +YLr - 1l
expr 2= max(l(i - 1, j), l(i, j - 1))
By analysis given graph we see their are two
@tur paths i.e., one is'C B A D' and'C A D' having
l(i, j) values can be computed in a row major order
weight 12 and 13 respectively to reach C to D.
or column major order of L[M, N].
Since we have to find atleast 1 (means more
@t"l than 1 or 1) sortest path between Cto D. So we
The algorithm uses dynamic programming have to bonsider 12 as value ofx, by doing this
paradigm. we have atleast 1 path between C to D i.e., 7
path CBAD and 2nd path CD having weight 12
@t"l each.
In a complete graph total no of edges is
_ n(n-1)
@t":
.'2 Floyd Warshall algorithm for all pair shortest
paths computation is based on dynamic
fime complexity of Bellman-ford algo for a graph
programming paradigm.
having n vertices and m edges = O(nm)
for a complete graph tirne complexity
@sot.
(ArA2A.rAl)
^l nx-n(n-1)\j=O(n3)
0j
\2
So. option (c) is correct. A,A :)A +
(Ar-A.z)(A3Ar) Ar(A. ,Ar)
1.10x5x5x20=1000 1.10x5x5x20=1000 1.5x20x20x10=1000
@s"t. (10 x 20)
2.10x20x20x10=2000
(10 x 20)
2.20x10x 10x5=1000
(5 x 10)
2.5x10x10x5=250
A= qpqrr (10 x 10)
3.10x10x10x5=500
(20 x 5)
3.10x90x20x5=1000
(5 x 10)
3.5x10x10x5=250
(10x5) (10x5) (5 x 10) JSoo
B = pq.prqrp -;m*
LCS (4, B) = qpqr The minimum number of -multiplication required
(or) = qprr using basic matrix multiplication method will
(or) = pqrr be 1500.
r = Iength of LCS (A, 81= 4
J=#LCS(A,87=3 lrrt
.'. x+10y=4+10x3=34
P & NP Concepts
ConcelI
ffi
5.1 Aproblem in NP is NP-complete if 5.5 Suppose a polynomial time algorithm is
(a) it can be reduced to the 3-SAT problem in discovered that correctly computes the largest
polynomial time clique in a given graph. In this scenario, which
&) the 3-SAT probiem can be reduced to it in one of the following represents the ccrrect Venn
polynomial time diagrarn of the complexity classes P, NP and NP
(c) it can be reduced to any other problem in Complete (NPC)?
NP in polynomial time
(d) some problem in NP can be reduced to it in
PolYnomial time
[2006 : l Mark]
5.2 For problems X and Y, Y is NP-complete and X
reduces to Y in polynomial time. Which of the
following is TRUE?
(a) If X can be solved in polynomial time, then
so can Y NPC
&) X is NP-complete
z.--rp=Np
//--\ \
(c) X is NP-hard
1lNpc) \
(d) X is in NP, but not necessarily NP-complete (c)
l\,
\/ )
5,7 Consider two decision problems Q, Q, such that 5.8 Language Z, is polynornial time reducible to
Q, reduces in pol5rnomial tirne to S--cAT and 3- Ianguage Lr. Language .Lu is polynomial time
SAT reduces irr polynomial time to Qr. Then reducible to L, which in turn is polynomial
which one of the fbllowing is consistent with the time reducible to language ,Ln. Which of the
above statement? following is/are True?
' (a) Q, is in 5P, Qz is NP hard I. If Lne P, Lre P
(b) Q? is in NP, Q, is NP hard tr. If Lre P or L,re P, then Lre P
(c) Both Q, and Q, are in NP [.Zre P,if andonlyif Zre P
(d) Both Q1 and Q2 are NP hard n/. If. L4e P, then Lre P and, L,e P
[2015 (Set-2): l Mark] (a) II only 0) III only
(c) I and IV only (d) I onlt,
[2015 (Set-3):2 Marks]
IIII
fftlflF&rtFConcepts
5.1 (a) 5.2 (b) 5.3 (c) 5.4 (a) 5.5 (d) 5.6 (b) 5.7 (a) 5.8 (c)
@'t"l
3-SAT being an NPC problem, reducing NP By depth first search we can find whether
problem to 3-SAT would mean that NP problem
there exits a cycle in an undirected graph in
is NPC. O(n2) times so it is P problem.
Notice that choice (a) is incorrect since as Pe NP, If clique is P then P = NPC
some NP problems are actually P, and hence .'. P-NP=NPC
polynomial time algorithm can exist for these.
Choice ft) is incorrect since, If no can be solved
@tul
2CNFis P-problem.
deterministicaliy in polynomial time, it does not
generate that P=NP, unless of-course it is Therefore it is solvable in polynomial time by
additionally known that no is NP-complete. reduction to directed graph reachability.
EI't*) Etu)
Given Qi s 3-SAT and 3-SAT S Q, LL <pLz, Ls <p L2, and L, <o Ln
3-SAT is NP-complete. I. If Lne P, Lre P is true
.'.It is NP as well as NP-hard. Lr'rLn
Q, s a-Slt and 3-SAT is NP 3 Qr is NP- III. If Lre P or Lre P, then .L, e P is false
problem
Lt<pL2, and L, <" L,
3-SAT S Q2 and 3-SAT is NP-hard. + Q, is
NP-hard problem. III. ,L1 e P, if and only if Lre P is false
Sothe strongest statements is Q, is in NP and Tf L, e P we cannot say anything about .L,
Q2 is NP-hard.
fuom Lr<rL,
Since we cannot say anything about ,L,
therefore we cannot say anything about tr,
either from Lr<rLr.
So Statemeht III is false.
IV. If Lne P, then,L, e P and Lre P is true.
If Lne P then from Lr3rLnwe can get that
Lre P.
and from Lr."Lrwe can now get that ,L, e
P
also from Lr.rLrwe can get that Lre P
So Statement fV is true.
IITI
Miscellaneous Topics
6.10 If T, = O(1), give the correct rnatching for the (a) d(r, u) < d(r, v) (b) d(r, u) > d(r, v)
following pairs: (c) d(r, u) S d(r, v) (d) None of these
(-) T, = T.,_, *, (u) T" = O(n) [2001 :2 Marks]
(n) q=\+n (v) T" = O(n logn) 6.L4 The minimum number of colours required to
-2 colour the vertices of a cycle with n nodes in such
a waythat no two adjacent nodes have the same
(o) q =\ +nlogn (*) T,=O(n2)
2 coiour is
(p) T, = T,_1 + logn (*) T, = O(log2 n)
(a) 2 (b) 3
following statements is always true? (a) n(n - 1)/2 &) n(n - 1)/a
(a) {u,v} must be an odge in G, and u is a (c) n(n + 1)/4 (d) 2nfiogrn]
descendant ofv in T [2003:2 Marks]
&) {u,v} must be an edge in G, and v is a 6.16 Shat would be the worst case time complexity of
descendant ofu in T the insertion sort algorithm, if the inputs are
(c) If {u.v} is not an edge in G then u is a leaf in restricted to permutations of 1...n with at most
T n inversions?
(d) If {u,v} is not an edge in Gthenu andv must (a) @ (n2) , (b) @ (n log n)
have the same parent in T (c) @ (n15) (d) o (n)
[2000:2 Marks] [2003:2 Marks]
6.12 Consider any al'ray representation of an n element 6.17 The cube root of a natural number n is defined
binary heap where the elements are stored from as the largest natural number m such that
index index n of the array. For the element
1 to m3 < n. The complexity of computing the cube
stored at index i ofthe array (i < n), the index of root ofn (n is represented in binary notation) is
the parent is (a) O(n) but not O(no s;
lil &) O(no u) but not O ((1og n)k) for any constant
(a)i-l e) l;l k>0.
(c) O((1og n)k) for some constant k > 0, but not
Ir (i+1)
(.)
I
(a) best if A is in row-major, and B is in column- (b) Solves in linear time using a right to left pass
major order (c) Solves it is using divide and conquer in time
&) best if both are in row-major order O (n log n)
(c) best if both are in column-major order (d) Solves it in time O(n2)
(d) independent of the storage scheme [2006: l Mark]
12004:2 Marks] 6.24 A set X can be represented by an array x[n] as
(a) {P, Q, R, S}, {T}, {U}, {V} 6.31 A depth-first search is performed on a directed
(b) {P,Q, R, S, T, V}, {U} ac;zclic graph. Let d[u] denote the time at which
G) {P, Q, S, T,'V}, {R}, {U} vertex u is visited fbr the first time and f[u] the
(d) {P, Q, R, S, T, U,'\r} time at which the dfs call to the vertex u
[2006 : 2 Marks] terminates. Which of the following statements
6.27 ionsider is always true for all edges (u, v) in the graph?
the depth-frrst-search of an undirected
graph with 3 vertices P, Q, and R. Let discovery
(a) dlul < d["] (b) d[u] < f[v]
time d(u) represent the time instanr when the
(c) f[u] < f[v] (d) f[u] > f[v]
vertex u is first visited, and finish time f(u) [2007 :2 Marks]
represent the time instant when the vertex u is If we use Radix Sort to sott n integers in the range
last visited. Gir.en that (rru'2, ,k], for some k > 0 which is independent of n,
d(P) = 5 units, f(P) = 12 units the time taken would be
d(Q) = 6 units, f(Q) = 10 units (a) @(") 0) o(kn)
d(R) = 14 unit, f(R) = 18 units (c) O(n log n) (d) o(n2)
which one of the following statements is TRUE . t2008:2Marksl
about the g,laph
(a) There is only one connected componerrt 6.33 Consider the following sequence of nodes for the
undirected gaph given below.
(b) There are two connectecl components, and p
and R are connected
(c) There are two connected components, and e
and R are connected
(d) There are two connecied components, ancl p
and Q are connected
[2006 : 2 Marks]
Directions for Question 6.28 to G.B0:
An array X of n distinct integers is interpretecl as a 1. abef dgc 2. ab ef cgd
complete binary tree. The index of the first element of 3. a d g e b,c f 4. a d b c g e f
the array is 0. A Depth First Search (DFS) is started at node o.
The nodes are listed in the order they are first
6.28 The index of the parent of element X [i], i * 0, is
visited. Which all of the above is (are) possible
(a) Li I z-l o) [(i - Dt21 output(s)?
b) l,tzl (0 lirzl - t (a) 1 and 3 only @) 2 and 3 only
[2006:2 Marks] (c) 2, 3 and 4 only (d) 1, 2 and B only
6.29 If only the root node does not satisfy the heap [2008 : 2 Marks]
property, the aigorithm to convert the complete
6.34 Two alternative packages A and B are available
binary tree into a heap has the best asymptotic
for processing a database having 10k records.
time complexity of
Package A requires 0.0001 n2 time units and
(a) O(n) O) O(Iog n)
package B requires lOnlogron time units to
G) O(n log n) (d) O(n loglog n) process n records. What is the smallest value of
[2006: 2 Marks] k for which package B will be preferred overA?
6.30 If the root node is at level0, the level of element (a) 72 (b) 10
X[i],i+0,is (c) 6 (d) 5
(a) Llogz i-l @) [log, (i + 1)-l [2010: l Mark]
(c) Llogz (i + 1)-l (0 [log, il
The number of elements that can be stored in
[2006 : 2 Marks]
@(1og n) time using heap sort is
MADE EASY I Algorithms I 387
orderings.
(d)2 1 3 4
[2015 (Set-l):1Mark]
(d) psRe is the onry t"il11?itJ,,_i;1,1**".o,
6.39 Given below are some algorithms, and some
algorithm design paradigms.
6.37 Suppose you want to move from 0 to 100 on the
List-I
number line. In
each step, You either
move right by a unit distance or you take a
A. Dijkstra's Shortest Path
B. Floyd-Warshall algorithm to compute all
shortcut. A shortcut is simply a pre-specified pair
pairs sliortest path
of integers i, j with I < j. Given a shortcut i, j if
C. Qinary search on a sorted arraY
you are at position I on the number line, you may
(k) D. Backtracking search on a graPh
directiy move to j. Suppose denotes the
List-II
smallest number of steps needed to move from k
to 100. Suppose further that there is at most 1
1. Divide and Conquer
&)3 3 1 5
(c)B 2 1 4
(d)3 2 | 5
[2015(Set-2):2Marks]
rITI
388 GATE Previous Years Solved papers : ![
I
| MADE EASY
@*l @tal
A-R, B-P, C-S, D-Q
@sot.
Use either selection or insertion sort. minimum
comparisons is 4.
In worst case, minimum exchanges required =
@rar lnl
t-l
Radix sort take O(n) time and other takes l9t
L- l
O(n iog n). (, if (ALrl < AUI && AJil < 0) {i++"i
(ii) If (ALjl>Alil &&A[]>0) i:--:i
@tol Sorting is not needed, keep all negatives before
Tree representation of tir'e given array is
positives. Worst case occurs vrhen i and j reaches
to middle position.
\Ye require
lnl
I ; I exchanges if arrayhas firstnl2
t'Jt
elements ur" po.itiu* and last rrJ2 elements are
negative exactly.
So two exchanges are required.
@tar
@tal Articulation point is that by removing that vertex,
graph must be in disconnected state. 2, B and E
O(t)+n _ n+1
Average case = are articuiation points and also called as cut
22 vertices.
@or @tal
All pairs shortest paths -+ Dl,namic programming T(n) = T(n-1)+n --1 T0r) = O(n2)
Quick sort -+ Divide and conquer T(n) = T(n/2)+n -+ T(n) = O(n)
Minimum weight spanining tree -+ Greedv T(n) = T(nl2)+n log n -+ T(n) = O(n log n)
technique T(n) = T(n-1)+ log n -+ T(n) = O(n log.n)
Connected components + Depth-First-search
@ro
@or Draw some random graph and try to verify the
Binary O(logn)
<-- options.
[Linear search] Selection <-.O(n)
Merge sort +- O(n log n)
Insertion sort e- O(n2)
MADE EASY I Atgorithms i 38e
@{nl t (n) 1
= qlej=;("c2)
Tit
t 1 \rr
E EE n til
,7\, lh
= 2Pln-2
partent,, = 1n(n-1)ln-2
Lil =, z'E:l
Example:
_ n(n-1)
Parent ra =
lJl=, 4
(i, Letn=odd
c2 c1
@tal
Ifeach set is represented as a linked list with
c1
elements in arbitrary order. Membership
cardinality takes O(1) time for an element in the
set so the operation is very fast.
In the case of intersection, Let A and B are two
sets. An operation such as A n B requires time
Then 3 colors are required to color the cycle with at least proportional to the sum of the sizes of
odd. the two sets. Since the list representing A and
the list representant B must each be scanned at
Minimum number of colors = ,-zll12)l*z least once.
Similarly operation A n B requires time at least
@,o)' proportional to the sum ofthe set sizes, since we
Let ar, a2, d3t .....t a' be a permutation of a set {1, must check for the some element appearing in
2, ......, n). If i <j and ai > aj the pair (a,, a,) is both sets and delete one instance of each such
called an inversion of the permutation. For element.
example the permutation 3742 has three The well known algorithm using 2-3 tree (ordered
inversions : (3, 1), (3, 2) and (4, 2). If all or unordered) takes O(nlogn) if set contains n
permutations are equally likely then according elements for union and intersection operation so
to "O. Terquen" the average number of inversions it is siowest operation.
in a random permutation is
3eo I GATE PreviousYears Solved Papers: (p I MADE EASY
@.(a) @tel
g(x) is min {number of leaf nodes in left subtree In strongly connected component, every two
ofx, number ofleafnodes in right subtree ofx). vetices must be reachable from one to other and
If balanced binary search tree is used and it is maximal component.
contains n nodes then in worst case time
complexity of g(x) is O(n).
@iur @l@
The root of the tree is stored at X[1],
Left of X[i] is stored at X[2i],
Right of Xlil is stored at X[2i + 1].
If tree is complete binary tree minimum it
require n consecutive memory locations of x,
x[1],...,x[n - 1], x[n].
@<al
Since d(Q) = d(P) + 1 and f(Q) < f(P) which
means P and Q a?e connected and R is separate.
@,lq)
In selection sort, minimum number of swaps
taken compared to other sorting techniques.
@r"l
Number of swaps = O(n) Left child of ith element will be at 2*i+1 and
Number of comparisons = O(nz) right child at 2(i+1). The index of the parent of
In finds the minimum of the subarray and element X [i] is Li t il.
exchanges only once in everv pass.
@or
@tut We can just call heapify and it will also take
Scan the array from right and select the leader. log ru time only as other nodes are already in
Now compare each element with the leader and place.
find new leader. So it will take complete one scan
ofan array. @roi
So it is in linear time only. Level
-...*0
@ral
In given algorithm the for loop contains a logical +1
expression
z[il = (xlil
^
- ylil) v (-xlil ylil)
^
The equivalent set representation ofgiven logical -2
expression if we assume z[i] = z, x[i] = x and y[i] = y Index of Every node is shown in the box. Floor
then (log (i + 1)) draw the tree and realise that the
7= (x n y') u (x'- y) last element at each level is the best choice to
z= (x- y) u (y-x) [An B'=A-B] arrive at a conclusion.
@lor @.(al
If each a, and b, is either 0 or 1 and the numbers Since DFS is performed on directed acyciic
are stored in an array then we can find the largest graph so we don't have any back edges.
span (i, j) on average in @(n) times because these is Since we are only having tree edges forward
onlyneedof search. edges and cross edges.
@'or
Time complexity of radix sort = @(kn)
MADE EASY I Algorithms I 3e1
@tul @("1
P
..^\-..
(nY-*
lv 0
s
@sol.
Given that there is shortcut from 9 to 15
DFS orders: OR
1. a-b-e-f-(d is not depth first order) It can move right by a unit distance (9 to 10)
2. a-b-e-f-c-g-d is correct DFS order. T(9) = 1 +Min (T(10). T(15))
3. a-d-g-e-b-c-fis correct DFS order. y = 10,2=15
4. a-d-b-c- (g is not depth first order). =
yz=10x15=150
.'. 2 and 3 are correct DFS orders.
@t"l @t"l
Prims algorithm for finding MST is a greedy
A requires 0.0001 n2 time units. And B require algorithm. Floyd warshalls algorithm for finding
10 n logron time unit to process n records for aII shortest paths is dynamic algorithm.
package B wiII be preferred over A. Merge sort is a Divide and Conquer algorithm.
So 0.0001 n2 <.10 n logron Hamiltonian circuit is an NP-complete problem
t
n- and done by using backtracking.
( 10nloe.^n
urri
-10, @t*l
= 106nlog,rn
n2
compare this constant with 10K Dijktra's shortest path + Greedy design.
So minimum value of K = 6 for which package B Floyd warsirall algorithm to compute all pair
will be preferred over A. shortest path -; Dynamic programming.
Binary search on a sorted -+ Divide and Conquer
@(*) aruay.
Ifwe have an array of x elements then time
complexity to sort x elements using heap sort is Backtracking searching -> Depth first search
O(x log x). on a graph.
We need to find value of x so that time complexity rrtt
to sort x elements gets @(Iog n) we can direct
discard option (a) and (d).
Now check option (c)
=
lT" (log]ogn-loelostogn)'l
o[.logiogn
\ ' /
- logloglog n\)
o[r"r"[ loglognloglogn
= -))
= @(log n)
Option (c) is correct