Download as pdf or txt
Download as pdf or txt
You are on page 1of 51

Algorithrns

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.

Analysis of Previous GATE Papers


;;2lMarlts ',S Mdrk* 5'trIla*k5i'
:'OUeS.,',:
--:
rotat :.Exanr
'r:.Yeiif
I Ma*
,',,Ou3s;.' :.Queg;,,, lHarks Ques.

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

1998 2 2 2014 Set-1 2 2 6

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

(a) O(n) a given element is


&) o(n')
(a) Iog, n b) ,n2
(c) O(mB) (d) o(3n)
(c) logrn-1 (d) n
[1993:2 Marks]
[20022l Mark]
1.4 Consider the following two functions: 1.9 Consider the following functions
[rr'for0<n<10,000 f(n) = SnG
8,(n)=i
- ^
[r'forn>10,000 g(n) = 2J!ilog2'
[nfor0Sn<100 h(n) = n1
gz(n)={ ,-
[n'for n > 100 Which of the following is true?
(a) h(n) is O(f(n)) (b) h(n) is O(g(n))
Which of the following is true?
(c) g(n) is not O(f(n)) (d) f(n) is O(g(n))
(a) gr(n) is O(g, (n)) &) sr(n) is O(n3)
(c) gz(n) is O(g, (n)) (d) gz(n) is O(n) 12002:2 Marksl
[1994:2 Marks] 1.10 Consider the following algorithm for searching
for a given number x in an unsorted array A[1
1.5 Which of the following is false? ..... n] having n distinct values:
1. Choose an i uniformly at random from 1...n;
(a) loon rogn = or"]:?" 2. If A[il = x then StoP else Goto 1;
\100/ I
Assuming that x is present on A, what is the
e) .,[6-sn = o(loglogn) expected number of comparisons made by the
G) If 0 < x < y then n* = O(nY) algorithm before it terminates?
(d) 2n * O(nk) (a) n (b) n-1
(c) 2n (d) n/2
[1996: l Mark]
12002:2 Marksl
1.6 The concatenation of two lists is to be performed
in O(1) time. Which of the following 1.11 The running time of the following algorithm
ProcedureA(n)
implementations of a list should be used?
(a) Singlylinkedlist If n < = 2 return (1) else return (a[.6]);
@) Doubly linked list is best described by
(c) Circular doubly linked list (a) O(n) &) O(logn)
(d) Array implementation of list (c) O(Iog log n) (d) O(1)
[1997: l Mark] 120022 2 Marksl
MADE EASY I Algorithms I 343

1.12 Consider the foilowing three ciaims counter = 0;


1.(n + k)- = @(n*), where k and m are constants for(i=1;i<n;i++)
z.z'+7 = O(2") {
3.22n+ 1 = o(2") if (Atil = = 1) counter **;
Which of these claims are correct? else
(a) 1 and 2 ft) landB {
(c) 2 and 3 (d) 1, 2 and 3 f (counter);
[2003: l Mark] counter = 0;
)
1.13 Consider the following C function.
)
float f(float x, int y)
The complexity of this program fragment is
{
float p, s; int i; (d a(nz) (b) O(n log n) and O(n2)
for (s = 1, p = 1, i = 1; i < y; i ++1 (c) o(n) (d) O(n los n)
{ 120042 2 Marksl
P* = x/i; L,l7 The time complexity of the following C function
s*=pi is(assumen>0)
) int recursive (int n)
return s; It
) if (n==1)
For large values of y, the return value of the
return (1);
function f best approximates
else
(a) xY . (b) e. return(recursive(n-1)+ recursive(n-1)) ;
(c) ln (1 x)
+ (d) x*
)
[2003: l Mark] (a) O(n) (b) O (n log n)
1.14 The tightest lower bound on the number of (c) o(nl (d) o (29
comparisons, in the worst case, for comparison- 12004 z 2 Marksl
based sorling is ofthe order of
(a) n 1.18 Therecurrenceequation
&) .r2
(c) nlogn (d) nlog2n T(r;: 1

l Markl T(n) = 2T(n-1) * n,rt) 2


l2O04z
evaluates to
1.15 What does the following algorithm approximate? (a) 2*r-n-2 &) 2n-n
(Assumem)1,€>0). (c) 2+1-2n-2 (d) 2"+n
x=m; 12004:2 Marksl
1.
y-rr
-- -
l.fg Let f(n), g(n) and h(n) be functions defined for
while(x-y>s) positive integers such that f(n) = g1*1rr), g(n)) *
{ o(f(n)), g(n) = o(h(n)), and h(n) = O(g(n)). Which
x= (x+y)12;
one of the following statements is FALSE?
Y = m/x; (a) f(n) + g(n) = O(h(n)) + h(n))
)
print (x); &) f(n) = o(h(n))
(c) h(n) + O(f(n))
(a) Iog m (b) m2
(d) f(n)h(n) + o(g(n)h(n))
(") *t/' (d)
'','/3
Marksl [Year: 200412 Marks
12004 z 2
L.20 The time complexity of computing the transitive
1.16 Let A [1,..., n] be an array storing a bit
closure of a binary relation on a set of n elements
(1 or 0) at each location, and f(m) is a function
is known to be
whose time complexity is O(m). Consider the
(a) O(n) (b) O(n log n)
foilowing program fragment written in a C like
(c) O(n3/2) (d) O(n3)
language:
[2005: l Mark]
344 I
GATE PreviousYears Solved Papers: !p I MADE EASY

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)

of the following statements is TRUE? [2006: l Mark]


. (a) T(n) = @(los n) @) T(n) = O(Jn) t.26 Consider the following is true?
(c) T(n) = @(n) (d) T(n) = @(n log n) /T /--l\
r (n; = zt(lvn ]) + 1, T (1) = t
[2005:2 Marks]
Which one of the following is true?
1.22 Suppose T(n) = 2T (nl2) + n, T(0) = T(1) = 1 (a) T (n) = @ (Ios log n) &) T (n) = @ (log n)
Which one of the following is FALSE? /-\
(a) T(n) = O (n2) 16) T(n) = @ (n los n)
(c) T (n) = o(Vn) (d) T (n) = @(n)
(c) T(n) = el(n2) (d) T(n) = o (n log n) [2006: 2 Marks]
[2005:2 Marks] 1.27 Consider the following segment of C code
Comrnon Data for Q. 1.23 & q. L.24 int j, n;
Consider the following C function: j=1;
double foo(int n) while(j.=n)
t j=)* 2;
int i; The number of comparisons made in the execution
double sum;
of the loop for any n > 0 is
if (n = = 0) return 1.0;
(d [log,n.]+1 1u)
else "
{' (c) [tog, nl ($ [log, n-] + 1
sum = 0.0;
12007 : l Markl
for(i=0;i<n;i++;
sum * = foo(i); 1.28 What is the time complexity of the following
return sum' recursive function :
) int DoSomething ( int n)
) {

1.23 The space complexity of the above function is


if(n<=2)
(a) o(i)
return 1;
O) o(n)
else
(c) O(n!) (d) o(n9
return DoSomething (floor (sqrt (n)))+n;
[2005:2 Marks]
)
L.24 The space complexity of the above function is foo( ) (a) o(n) &) @(n iog, n)
and store the values of foo(l), 0 < = i ( n, as and (c) @(log, n) (d) @(logr logrn)
when they are computed. With this modification, 12A07 :2 Marksl
the time complexity for function is
foo( )
significantly reduced. The space complexity of the r.29 An array of n numbers is given, where n is an
modified function would be even number. The maximum as well as the
(a) o(1) (kr) O(n) minimum of these n numbers needs to be
(c) O(n2) (d) o(n!) determined. Which of the following is true about
[2005:2 Marks] the number of comparisons needed?
(a) At ieast 2n - c comparisons, for some constant
L.25 Consider the following C-program fragment in c, are needed.
which i, j, and n are integer variables. (b) At most 1.5n - 2 comparisons are needed.
for (i = n, j = 0; i > 0; i I = 2,j+ = i); (c) At least n log, n comparisons are needed.
Let Val 0 = denote the value stored in the variable
(d) None of the above
j after termination of the for 1oop. Which one of
12007 :2 Marksl
the foilowing is true?
MADE EASY I Algorithms I 34s

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

asymptotic order: X[1] = 1; Y[1] = 2; ZtTl = 3;


A. n1/3 B. €F for(i=2;i<=n;i++)
C. r{t4 D. n loge n {
E. 1.0000001" x[i]=Yti-11 +Zli-2);
(a) A,D,C,E,B &) D,A,C,E,B Y[i]=2*X[i];
(c) A, C, D, E, B (d) A, C, D, B, E Zlil=3*X[i];
[2008: l Mark] )
return X[n]
1.32 When n - 22k for some k > 0, the recurrence ;

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

(c) j"togJ[ (d) nlog J; [2008:2 Marks]


[2008 :2 Marks] 1.36 f1(8) and f2(8) return the values
(a) 1661 and 1640 O) 59 and 59
1.33 Consider the following functions: (c) 16a0and1640 (d) 1640and1661
f (n) = 2"
[2008:2 Marksl
g(n)=n!
h (n) = llosn 1.37 What is the number of swaps required to sort n
which of the following statements about the elements using selection sort, in the worst case?
asymptotic behaviour of f (n), g(n), and h (n) is (a) o(n) (b) @(n log n)
true? G) o(n1 (d) @(n21og n)
[2009: l Mark]
346 I
GATE Previous Years Solved Papers : !p I MADE EASY

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)

[2015 (Set-2): l Mark]


t.48 Consider the equality ) r' = X and the following
X
choices for
i=o

I. @ (na) II. @ (n5)


III. O(n5) IV. a (n3)
The equality above remains correctif Xis replace
by
(a) Only I
Only II [2016 (Set-2):2 Marks]
&)
(c) I or III or IV but not II 1.51 Nitems are stored in a sorted doubly linked 1ist.
(d) II or III or IV but not I For a delete operation, apointer is provided to
[2015 (Set-3): l Mark] the record to be deleted. For a decrease-key
operation, a pointer is provided to the record on
Let f(ru) = n and. g(ru) = l-r(1+sin n), where n is a
which the operation is to be performed. An
positive integer. Which of the following
statements is/are correct? aigorithm performs the following operations on
I. f(n)=Ots(n)) n the list in this order: @(Il) delete, O(IoS/9 insert,
f(ru)=o(S(ru))
(a) Onlyl (b) OnlyII O(iogN) find, and@(N) decrease-key. What is
(c) Both I and II (d) Neither I nor II the time complexity of all these operations put
together?
[2015(Set-3):2Marks]
1.50 The given diagram shows the flow chart for a
(a) O(log2 N) o) o(N)
(c) O(N2) (d) @(N2logN)
recursive function A(n,). Assume that all
[2016 (Set-2): l Mark]
statements, except for the recursive calls, have
IIfI
Ei ^tgr,,,i,*r ;rrrory)r! drrq ,rsympforrc raofaftons
1.3 (b) 1.4 (a) 1.5 (b, d) 1.6 (c) L.7 (b) 1.8 (d) l.e (d) 1.10 (a) 1.11 (c)
1.12 (a) 1.13 (b) 1.14 (c) 1.15 (c) 1.16 (c) r.t7 (d) 1.18 (a) 1.1e (d) t.zo (d)
r.21 (e) 1.22 (c) L.23 (b) r.24 (b) 1.25 (c) r.26 (b) r.27 (d) 1.28 (d) L.ze (b)
1.30 (b) 1.31 (a) L.32 (a) 1.33 (d) 1.34 (b) 1.35 (b) 1.36 (c) 1.37 (a) 1.38 (a)
1.3e (c) 1.40 (d) r.4t (b) r.42 (a) 1.44 (d) 1.45 (a) L.46 (a) L.47 (d) 7.48 (c)
1.4e (d) 1.51 (c)
Algqrllhm,,*nalygii,,errd, A*ymptotic fiatati *;fllr , :i.i:it:,::, :,i,::t,

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

81(n) = O(gz(rr)) n!t


Option (a) is correct.
@t"l
@{n,*) Let expected number of comparisons be E. Value
(a) We know that of E is sum of following expression for aII the
f(n) = 61*1,rr, t."., possible cases:
f(n) < k.g(n) Case.I If Alil is found in the first attempt,
for k, some positive integer and n > no Number of comparisons = 1

'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 = -;-*;

< 1 x log log n Case-trIl If A[i] is found in the third attempt,


&) d"g"
Number of comparisons = 3
.. +"g" * O(log log n) (n-1) (n-1) 1
(c) n'(nYas0<x<y Probability = ;_.;- *;
.'. n" = O(nY) There are actually infinite such cases. So, we
(d) 2n<knfork>2 have following infinite series for E.
.'.2n= O(nk) 1 n-1 (n-I)- ("-r) r *3*...
" ---:* r ^ (f, ,:\
.F, = -+ -*2+ " -,- ;
Er,l As list concatenation requires traversing at least After multiplying equation (i) with
('-') *"
,
n
one list to the end. So singly linked list and doubly
get
linked list requires O(n) time complexity whereas
circular doubly linked list required O(1) time. E,, n-1 1 n-l 1 ^
-(n-1) = _-+-+-*-*2+...(tt)
nnnnn
MADE EASY I Algorithms | 34e

Subtracting (ii) from (i), we get @,tul


n-1 1 n-1 n-1
E 1+-*-+-,k-*-+... 1 The given function fis not recursive, so consider
nnnnnnn the following iteration method.
The expression on right side is a G.P with infinite
elcments'
i a )
p=p^.
x
s=s+p
So apply the sum formula l. , _ r.l I
L Initilize 1
E flliln-(n-I/l \\
1

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

Let n = 2m. x' x3 xn


s=1+x+-+-+-
2624
= Ttn; = 112*;
+ T(2-1= 51*; x'
5 'D- _ ;x
I

:+ T(n) = g1*1 2.7 o

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

Et"t Let recursive(n) = 11r;


According to line 2 if (n = - 1) return(l) then the
Let x = m = 9. The loop will be terminated when
x - y = 0 or x - y < 0" Consider the following recursive equation is
iteration for x = m = 9, y = 1 T(n)=1, n=1
x-y>0 + ;1 =(x*y)/2, y-m/x According to line 4 the recursion equation is
9-1=8 x=5.0. y=9i5.0=1.8 T(n) = T (n- 1) + T (n-1). n > 1
5.0_1.8=3.2 x=3..1, y=913.4=2.6
So the complete recursion equation is
3.4_2.6=.80 x=3.0, y=9t3.0=3.0
T(n)=1, n=1
x-y = 3.0 - 3.0 = 0, Ioop terminated
T(n) = T(n- 1) + T(n- 1), n > 1
So, m=9thenx=3 or T(n) = 2T(n- 1), n > 1
x=(m)1/2=(g)trz
= x=B T(1) = l=2'
So the algorithm computes x - m1/2.
T(2) = 2T(t;=2.7=21

@t.l T(3) = 2T(2)=2.2=22


T(4) = 2T(3) = 2.22=23
The given code is
1. Counter=0;
2. lbr(i=1;i<=n;i++)
3. i if (Atil = = 1) counter **; T(n) = 2n-r
4. else {f(counter); counter = 0;}
5") Or, T(n) = 2".
I
'fhe time complexity of the program fragment
depends on the frequency (Number of steps) of So, T(n) = O(2")
line 3 and 4. In line 4 the frequency depends on
the variable counter and there is no increment @tal
in the counter variable which is initialize to 0. so T(i) = 1

f(0) then counter = 0 it means there is no cell in T(n) = 2T(n-1)+n n>2


an array which having a bit 0, so all cells in the T1z1 = 2T(1)+2=2.7+2=4
array contains 1. Consider the line 3 if (A[i] = = T(3) 2T(2)+3=2.4+3=11
1) counter ++; the vaiue of i will be increases =
T(+1 = 2T(3)+ 4=2.11+1=26
upto n so the value r,rf counter will be n. Since n
is the frequency of the line 3 and the frequency
of line 4 is 0. So the time complexity of line 3 is T(n- 1) = 2T(n-2)+n =2"-(n-l)-z
O(n) on average n and f(O; = g1r, is the time So T(n) = 2n*7 -n-2
complexity of line 4. So the time complexity of
the program fragment is maximum of line 3 and @tar
4 u,hich is O(n) on average.
We can verify as:
f <gBUT C{f. Thereforef <g
Eto Also g = h as C = O(h) and h = O(g).
The given C function is recursive. 'Ihe best way Thereforefcgandg=[
to find the time complexity of recursive function (a) f(n) + g(n) = O(h(n)) + h(n)) is true.
= f+g=f +h<h+h
is that convert the code (algorithm) into recursion
equation and solution ofthe recursion equation (b) f(n) = O(h(n)) is true.
is the time complexity of given algorithm.
==rf<h
1. int recursive (int n) { (c) h(n) * O(f(n)) is true.
2. if (n = = 1) return (1);
3. else =hlfiscorrect.
(d) f(n)h(n) + O(g(n)h(n)) is false.
4. return (recursive(n-1)+recursive (n- 1));
5.) = f .h < g.h implies fh = O(gh)
MADE EASY I Algorithms | 3sl

@tal The longest calling sequence:


foo(n) -+ foo(n-1) -+ ... foo(0)
The time complexitSz of computing the transitive
closwe of a binary relaiion on a set of n elements Therefore space complexity = Q1r;
is O(n3; apply the Warshall's algorithm to fNote: Time complexity = O(n")]
. compute the transitive closure. The algorithm
contains three nested for loops each having @(u)
foo(n)
frequency n so time complexity is O(n3).

@t"l
T(n) = 2T(nl2) +"',6' foo(0) foo(1) foo(2) foo(S) foo(n-1)

By substitution method T(n) = 61111. Space required: foo(0), foo(1),...,foo(n-1) = O(n)

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

foo(n-2) comparisons = i + 1 = [16grn] + t


I i\lfoo(1)
@.td,
1

foo(0) foo(0) foo(0) foo(n-3)

foo(0) foo(01 The given function is recursive so the equivalent


--x--
Longest
recursion equation is
depth T(n) = 1' n32
3s2 | GATE Previous Years Solved Papers : [S I MADE EASY

T(n) = LJn]. n;n >2 @t"l


T(n) = Jz.r@tD+Ji ...(1)

GJ; =
"'rlJr.T@
t g + J,rt z)* Ji
nlt1 .............. n ti1 n1r4.............. n 1,4
= (Jr)' .r(ntz,)+zJi .."(2)

All the level sums are equal to n. The problem


ofthe recursion tree is n2-k and we
srze atlevel k = (Jr)' .r (n t z,) + B.,,li ...(3)
stop recursing when this value is a constant.
Setting n2-k= 2 and solving for k gives us
2-klogrn = I = (Jr)'r .r (n t z'k) + 2hJi
= 2k = Iogrn
= k= logrlogrn
=
/
.1 + log n ../n
-\log,
(J2) .
['.' Put 2k =iog n]
So T(n) ='@(og,log,n)

@rar - Vnr--+ )ogn.ln


When we apply the divide and conquer method = JnGogru+1)
such that dived n into two parts of n/2 then
recurrence equation is
T(n)=1forn-=2
@ral
f(n) = 2n =+ f(n) = O(2")
T(n) = 2T(nl2) + 2 for n> 2 g(n) = n!= g(n) = O(nl)
The solution of T(n) is
h(n) = ,rloen -- h(n) = O(nlos";
o
:-n-2
,a [rr. n' means n grows more slowly than n2]
T(n) = The asymptotic order of function is as follows:
2
1 < loglogn < iogn ( nt ( rrc 4 rrlogn ( cn ( nn (
= 1.5n-2comparison
ct"<n! '

@,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

binary search then in expected case comparrson


@r"l
is not greater than [og(n + r]1. But if integer A(n) -+ Average case complexity
appears n/2 times in an array and array is W(n) -+ Worst case complexity
already sorted then it take @(1) times for We know
consecutive locations. So total no. of comparisons Best case < Average case complexitv < Worst case
is not greater than @(Iog n) time. complexity
and always A(n) < k.W(n) =+ A(n) = O(W(n))
@tnr
The fr(n) is a recursive function. @tar
The recurrence equation for fr(n) is TOH (n, L, M, R)
T(o; = s
T(r1 = 1
T(n) = 2T(n-1)+3T(n-2)
The solution of this linear equation contains a
polynornial of 2" so on average the running time
TOH MOV TOH
(n- 1, L, R, M). (L-R) (n- 1, M, L, R)
of fr(n) is O(2").

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

Flnd Inse{ Delete


Decrease
kev
Overall
and when ever the value of 'sin n' is +1, then
Unsoaed
Eacb fnrd g(n) = n2
operation ia O(10 o(rl"-o)
o(x.f5) o(\D o(r1ffi) orN,"l"g\r

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

@t*l lhetrrrnF iLr/!r f--<


I

-1.-/\ V

Max heap N{ax heap


In worst case scenerio.
Heapify operation always takes O(logn) (for a we have 5 A(n/2) function calls and other
complete binary tree). statements takes O(1) time.
Since left subtree and right subtree are max So, the recurrrance relation will be,
heaps it takes a(Iog n) to heapify. A(n) = 5 A(nl2) + O(1)
By using Master theorem, we get n'o*,t which
@r*r is equivalent to n2 32. So the value of o is 2.32.
Take first 3 elements. The middle of the 3
elements will be the element that is neither @t"l
minimum nor maximum in the array. Data
Find Insert Delete
Decrease Overall
structure used key asymptotic time
Hence O(1) time to compare 3 elements. Sorted doubll'
O(N IogN) O(N IogN) o(N) o(N) O(N logN)
linked list
Example: Assume 4, 6,2 arefirst three elements.
Then 4 is the middle element of 4, 6 and 2. Sorted doubly ]inked list take maximum of of
Which is neither minimum nor maximum. O(N logN) time, but since not present in option.
So, gn for nearest value O(N2).

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

(a) C1< C2 2.17 The usual @(n2) implementation of Insertion Sort


o) cl>c2 to sort an array uses linear search to identify
(c) C1= C2 the position where an element is to be inserted
(d) we cannot say anything for arbitrary n into the already soited part ofthe array. Ifinstead,
[1996:2 Marks] we use binary search to identify the position. the
lvorst case running time will
2.72 Let T(n) be the function defined by T(f ; = 1, T(n)
(a) remain @(n2) ft) become @(n 0og n)2)
(c) become@(nlogn) (d) become0(n)
= ,t[L;i; + Jn ror n > 2. which orthe rollowing
[2003: l Mark]

statements is true? 2.78 Consider a list of recursive algorithms and a list


of recurrence relations as shown below, Each
(a) T(n) = 0(\,6) @) T(n) = O(n) recurrence relation corresponds to exactly one
(c) T(n) = O (log n) (d) None of these algorithm and is used to derive the time
[1997:2 Marks] complexity of the algorithm.
List-I (Recursive Algorithm)
2.13 A sorting technique is called stable if
(a) it takes O(nlog n) time
P. Binary search
Q. Merge sort
@) it maintains the relative order of occurrence
R. Quick sort
of non-distinct elements
(c) it uses divide and conquer paradigm
S. Tower of Hanoi
List-II (Recurrence Relation)
(d) it takes O(n) space
I. T(n) = T(n - k) + T(k) + cn
.. [1999: l Mark] II. T(n) = 2T(n - 1) + 1
2.74 If one uses straight two-way merge sort III. T(n) = 2T(nl2) + cn
algorithm to sort the following eiements in IV. T(n) = T(n/2) + t
ascendinp rrder: Which of the foliorving is the ccrrect rnatch
20, 4't, 15, 8, 9, 4, 40,30.72,77 between the algorithms and their recurrence
then the order ofthese elements after second pass relations?
ofthe algorithm is Codes:
(a) 8, 9, 15,20, 47, 4, 12, 17, 30, 40 PARS
(b) g, 15, 20,47,4, g. 30, 40,12,17 (a)tr III IV I
(c) 15, 20, 47,4, 8, 9. 12, 30, 40,17 (o)IV m I tr
(d) 4, g, g, 75,20, 47, 72, 77, 30, 40 (c)Itr tr IV I
[1999: l Mark] (d)rv tr r m
2.15 Let s be a sorted array of n integers. Let t(n) 12004:2 Marksl
denote the time taken for the most efficient 2.19 Suppose there are log n sorted lists of n/Iog n
algorithm to determine if there are two elements elements each. The time complexity of producing
with sum less than 1000 in s. Which of the a sorted list of all these elements is:
. following statements is true? (Hint: Use a heap data structure)
(a) t (n) is O(1) (a) O(n log log n) @) @(n log n)
(b) n<t(n)Snlogrn (c) Q(n log n) ($ a(n3/2)
(c) m [2000:lMark] [2005:2 Marks]
2.16 Randomized quicksort is an extension of quicksort 2.20 The median of n elements can be found in O(n)
where the pivot is chosen randomly. What is the time. Which one of the foilowing is correct about
worst case complexity of sorting n numbers using the complexity of quick sort, in which remains
randomized quicksort? is seleci,ed as pivot?
(a) O(n) (b) (n log n) (a) o(n) @) @(nlogn)
(c) O(n2) (d) O(n!) (c) o(n2) (d) o(n)
[2001: I Mark] [2006:2 Marks]
MADE EASY I Algorithms I ssz

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

2.82 Which one of the following is the recurrence else


equation for the worst case time complerity of I{
the Quicksort aigorithm fbr sorting n(> 2) return kth_smallest (__);
numbers? In the recurrence equations given in )
the options below. c is a constant. )
(a) T(n) = 2T (ni2) + cn
The rnissing argument iists are respectively
h) T(n) = T(n. - 7) + T(7) + cn (a) (a, Ieft_end, k) and (a+left_end+1, n-1sft_.rd-
(c) I'Qt) - 2T (n - l) + cn
1, k-left_end*1)
(d) T(ru') = T(nl2) + cru (b) (a, left_end, k) and (a, n-ieft_end-1. k-
[2015 (Set-l): l Mark] left_end-1)
(c) (a+left_end+ 1, n-left_end-1. k-Ieft_end-1)
2.33 What are the worst-case complexities of insertion
and(a, left_end, k)
and deietion of a key in a binary search tree?
(d) (a, n-Ieft_end-1. k-ieft_end-1) and (a,
(a) @(logn) for both insertion and Celetion
left-end, k)
&) O(ru) for both insertion and deletion '
(c) O(ru) for insertion and O(logn) for deietion [2015 (Set-2) : 2 Marks]
(d) @(logn.) for insertiori and @(ru) for deletion 2.35 Assume that a mergesort algorithm in the worst
[2015 (Set-l):1Mark] case takes 30 seconds for an input of size 64.
Which of the following most closely approximates
2.34 Suppose vou are provided with the following
the maximum input size of a probJ.em that can
f'unction declaration in the C programming
be solved in 6 minutes?
language.
(a) 256 (b) 512
int partition (int a[]. int n); (c) to24 (d) 2048
The function treats the first element of a[ ] as a
[2015 (Set-3):2 Marks]
pivot, and rearranges the array so that all
eiements less than or equal to the pivot is in the 2.36 The worst case running times of lrusertion sort,
left part of the array, and all elements greater Merge sorl and Quicle sorf, respectively, are:
than the pivot is in the right part. In addition, it (a) @(n log n). O(n log,t). and O(n2)
moves the pivot sc that the pivot is the last (b) O(n.2), O(n2), and @(ru log n)
element of the left part. The return value is the (c) @(ru2), O(n log rz), and @(ru log n)
number of eiements in the left part. (d) @(n2), O(n log rl, and@(r*)
The fbllorving partially given function in the C [2016 (Set-l): l Mark]
programming language is used to find the kth 2.37 Assume that the algorithms considered here sort
smallest element in an array a[] of size n using the input sequences in ascending order. If the
the partition function. We assume k < n. input is aiready in ascending order, which of the
int kth-smallest (int a[]. int n. int k) following are TRUE?
(
1
I. Quicksort runs in O1n2; time
int left_end = partition (a, n);
IL Bubblesort runs in @(ru2) time
if (ieft_end+1==k) III. Mergesort runs in @(n) time
l fV. Insertion sort runs in O(ru) time
return a fieft_end];
(a) I and II only &) I and III only
)
(c) II and IV only (d) I and IV only
if (left_end+1 > k)
f
t [2016 (Set-2): l Mark]
return kth_smallest (_ ); IIIE
l
I
MADE EASY I Algorithms | 3se

@iD#ji i and conqutr


2.1 (c) 2.4 (d) 2.5 (a) 2.6 (b) 2.7 (a) 2.8 (c) 2.s (d) 2.t0 (a) z.rt (c)
z.Lz (b) z.t8 (b) 2.r4 (b) 2.75 (a) 2.L6 (c) 2.17 (a) 2.18 (b) z.Ls (a) 2.20 (b)
2.21 (a) 2.22 (a) 2.23 (b) 2.24 (b) 2.25 (c) 2.26 (c) 2.27 (b) 2.28 (c) 2.2e (c)
2.31 (a) 2.32 (b) 2.33 (b) 2.34 (a) 2.35 (b) 2.36 (d) 2.37 (d)

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.

= O(n) IV. Binary search can be used with linked list,


however, it is inefficient.
[[sor, So option (d) is correct.

Quicksort gives worst case when all elements are


already sorted. So give any sorted order input @tul
either in ascending or descending order. Using Master Theorem
We get ,'o*t' a ,,
Eta)
Radix sort is a non-comparative integer sorting @tut
algorithm that sorts data with integer keys by Both of given cases are
grouping keys which share same position and Quicksort Worst cases problem, so comparisons
value. So it take O(n) time. are equal.

@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

For example in the following input the two 4's


are indistinguishable. 1, 4,, 3, 40, 2 and so the
EErnr
Binary search : T(n) = T(n/2) + 1
output of a stable sorting algorithm must be:
Merge sort : T(n) = 2T(nl2) + cn
7,2, 3, 4u, 4b
Quick sort : T(n) = T(n - k) + T(k) + cn
Bubble sort, merge sort, counting sort, insertion
Tower of Hanoi :T(n) = 2T(n - 1) + 1
sbrt are stable sorting algorithms.

@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

adding n elements to a binary search tree could


..r_- 1 t \ /
require O (n log n) time. nofrr,t(t<.n)
MADE EASY I Algorithms i 361

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 )

We get minimum number of multiplications


= 148 comparisons
using ((NtI1 x (Nf2 x M3)) x M4).
Total number of multipiication
* 5 x 80
@t"l
= 100 x 20 x 5 + 10,t 100 * 5 + 1C Choosing the centrai element (middie) as the pivot
= 19000 alu,ays can not make the partition into equal
parts.
@t*l .'. The worsi case time complexity = 91rrz)
We know that in balanced BST there are 1og, n
leveis in both worst as well as best case where'n' @tur
is no. of elements In worst case the pivot element position may tre
logr2
.'. logz (n 2") = logrn + either first or 1ast. In that case the elements
1og, n + n log, 2 =logrn + n = O(n) are always divided in 1 : (n - 1) proportion.
.'. Option'C' is correct. The recurrence relation for such a proportional
division would be
T(") - Tttl + T(n-l) + O(n) = O(n2)
352 I GATE Previous Years Solved Papers : (f,1 I MADE EASY

@1 f1n1 = 27' (nl2)* crl = O(n log n) @(rr


&) 7(ru) = T(n - l) + (1) + cn = O(n2) For n=64
(c) T(n) = 2T (n * l) + at = O(2") cr.nlog n = 30 sec
(d) (n) = T(nl2) + cn = O(n) cr.64. 1og 64 = 30 sec
5
@.tu; -1 64
...(1)
In worst case the BST may be Skewed BST.
This case occurs when we insert the elements
Now,cr.rulogn=6x60sec
in increasing order or decreasing order. 6 x 60sec
nlogn=
Example: Consider we insert elements, in the c1 sec

order 1, 12, 39, 43, 50, ....


6x60
The BST would be nlogn= _x64
5
nlogn= 4608
nlogn= 512x9= n=572

To find'n' is the worst case we may have to


@tal
The worst case time complexity of algo given
traverse to bottom of tree which takes O(n)
are:
time.
Insertion sort = @(n2)
Hence for both insertion and deletion worst case
Merge sort = @(n log n)
goes to @(n).
Quick sort = @(ra2)
@.ul @,to'
Right
Quick sort takes O(n2) time to sort the input
(ascending order) into ascending order. by using
divide and conquer.
n-elements Insertion sort take O(n) time to sort input
left_end (is pivot position) = partition (a, n); (ascending order) into ascending order since
need one comparision everytime andno swaping.
Note: kth smallest is same as an element at
index (k-1) in the sorted array. Merge sort take O(n log n) and bubble sort can
take O(n) time.
if (left_end+l = - k) f ltt smallest found.
So, option (d) is most appropriate.
return a[Ieft_end]; ll return pivot element.
IIII
if (Ieft_end+ 7 > k) ll kth smallest is before pivot.
return kth-smallest (a, left_end, k); // search
before pivot
else l/ kth smallest is after pivot (right part)
return kth_smalest (a+left_end+1, n-(left_end-1). k-(efi_end+1)):
\-_Jr-v+
address of first Number of elements
element after in right part
pivot (dght part)
j

Greedy Method
t
i
i
:

i
I
-,-***^t

3.1- The weighted external path length of the binary


tree in figure is
6/
1

(a) 29 &) 31
[1991 :2 Marks] (c) 38 (d) 41

Kruskal's algorithm for finding a minitnum [2003:2 ivlarks]


3.2
spanning tree of a weighted graph G with n 3.6 The following are the starting and er.lding trmes
vertices and m edges has the time complexity of of activities A, B, C, D, E, F, G, and H respectively
(a) O(n2) ' (b) O(mn)
in chronoiogical order: "a. b, c, &" d. cu e. f" b" d"
(c) O(m + n) (d) O(mloen) starting
S, €" f" h, g" h"" Here, x. denotes the
(e) O(m2) time and x" denotes the ending time of activity
[1991:2 Marks] X. W need to schcduie the activities in a set of
o.o Complexity of Kruskal's algorithm for finding the rooms available to us. An activity can be
scheduied in a room only ifthe room is reserved
minimum spanning tree of an undirected graph
containing n vertices ancl m edges if the edges for the activity for irs entire duration. What is
are sorted is the minimum number of rooms required?
(a) 3 (b) +
Izao* 2 Marksl
(c) 5 (d) 6
8.4 Let G be an undirected connected graph with [2003 : 2 Nlarksl
-
distinct edge weights. Let e-u, be the edge with
maximum weight and e-;,. the edge with 3.7 Suppose we run Dijkstra's single source shortesl-

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

3.5 What is the weight of a minimum spanning tree


of the foliow'ing graph? T .,, t;
364 GATE Previous years Solved papers
|
: [ft I MADE EASY

In what order do the nodes get includecl into the


1. diagonal elements are 0's, and
set of vertices for which the shortest path
2. non-diagonal elements are 1's.
distances are fi nalized?
Which one of the following is TRUE?
(a) P, Q, R, S, T, U (b) p, q, R, U, S. T
(a) Graph G has no minimum spanning tree
(c) P, Q, R. U, T, S (d) p,
e, T. R, LI, S
o{sT)
[2A04:2 Marks] (d) Graph G has a unique MST of cost n_1
3.8 Consider the undirected graph below: (c) Graph G has multiple distinct NIST's. each
B of cost n- 1

(d) Graph G has multiple spanning trees of


different costs
[2008: 1Mark]
3.11 Let G be a weighted undirected graph and e be
an edge with maximum rneight in G. Suppose
there is a minimtim weight spanning tree in G
Using Prim's algorithm..to construct a minimum containing the edge e. Which of the following
spanning tree starting with node A, which one of statements is ahvays TRUE?
the following sequences of edges represents a (a) There exists a cutset in G having al1 edges
possible or.der in which the edges would be adcle,J of maximum weight.
to construct the minimum spanning tree? (b) There exists a cycle in G having all eclges
(a) (E,G), (C,F), (F,G), (A,D), (A,B), (A,C) of maximum weight.
&) (A,D), (A,B), (A,C), (C,F), (G,E), (F,G) (c) Edge e cannot be contained in a cycle.
(c) (A,B), (A,D), (D,F), (F.G), (G,E), (F,C) (d) All edges in G have the same weight.
(d) (A,D), (A,B), (D,F), (F,C), (F,G), (G.E)
[2008 : 2 Marks]
[2004 t 2 Marks]
3,L2 Let G (V, E) an undirected graph with positive
3.9 In the following table, the left column ccntains edge weights. Dijkstra's single source_shortest
the names of standard gi"aph algorithms and the path algorithm can be implernented using the
right column contains the time complexiiies of binary heap data strr.rcture with time complexity?
the algorithms. Match each algorithm u,ith its (a) o(lvl2) tr) o(lBi+lvlroclvl)
time complexity, (c) otlvlrog Ivj) (0 ottlel+ lvljios.lvi)
List-I [2005:2 Marks]
1. Beilman-Fordalgorithm Common Data for Q. B.1B & e. 3.14
2. Kruskal's algorithm We are given 9 tasks T, T, ... Tr. The execution of
3. Floyd-Warshallalgorithm each task requires one unit of time. We can execute
4. Topological sorting one^task at a time. T, has a profit p, and a deadline d,
List-Itr profit P, is earned if the task is completed before the
A. O(rnlog n) end of the d,th unit of time.
B. O(n3)
' C. O(nm) Task T1 T2 T3 T^ T5 T6 T7 Ts T,
Profit i5 2A 30 18 18 i0 23
D. O(n + m)
Deadline
16 25
7 2 5 5 2 7
(a) 1-C, 2-A, g-B, 4-D 3

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

[2006: l Mark] (b) If e is not in a minimum spanning tree T.


then in the cycle formed by adding e to T, ail
3.18 Consider the foilou,ing graph:
edges have the same weight.
(c) Ever5, minimum spanning tree has an edge
of weight ro
(d) e is present in every minimum spanning tree
12007 :2 Marksl
Common Data for q.3.22 & Q.3.23
1
Suppose the letters a, b, c, d, e have probabilities
,'
1111
resPectivelY.
Which one of the following cannot be the sequence i, g, G, n
of edges added, in that order, to a minimum
spanning tree using Kruskal's algorithm? 3.22 Which of the following is the Huffman code for
(a) (a -b),(d-0, (b -0, (d-c), (d-e) the letters a, b. c, d, e?
(a) 0, 10, 110,1110, 1111
(b) (a-b),(d-0, (d-c), (b-0, (d-e)
(c) (d-0, (a-b), (d-c), &-f), (d-e) &) 11, 10.011,010,001
(d) (d-0, (a-b), (b-0, (d-e), (d-c)
(c) 11, 10,01,001,0001
(d) 110, 100, 010, 000, 001
[2006:2 Marks]
[2007:2 Marks]
365 I GATE Previous Years Solved Papers : [fl I MADE EASY

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]

." [2AA7:2Marks] 3.28 W'hich of the following statemen'u(s) is/are correct


regarding Bellman-Ford shortest path
For the undirected, weighted Sraph given below,
algoritirm?
which of the following sequences of edges P. Alwarvs firrds a negative weightedcycie, if one
represents a correct execution of Prim's aigorithm exists.
to construct a Minimum Spanning Tree? Q. Finds vzhether any negative weighted cycle
is reachable from the source
(a) P onl3, (h) Q onlv
(c) both P and Q (d) neither P nor Q
[2009: l Mark]
3.29 Consider the foliowing graph:
7\J72
(a) (a, b), (d, 0, (f, c), (9, i), (d, a), (9, h), (c, e),
-b \ -/el _r D
_\\>a
(f, h) 6'\.-^,,.-6
4 idld o
!/

&) (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

by deleting some elements from the sequence,


keeping the order of the remaining elements the 1a; fi{rln'-sn; ft) n2-n+ 1

same. Let X denote the maximum possibie weight


of a subseqr-rence of ao, a1,. , &n-1 and Y the (c) 6n - 11 (d 2n+1
maximum possible weight of a subsequence of [2011 :2 Marks]
dL, a2,... , 8n-1. Then X is equal to
3.34 The length of the path from v, to vu in the MST
(a) maxff, ao + D (b) maxfY", ao + Yl2)
of previous question with n = 10 is
(c) maxff, ao 2Y) (d) a,, + Y/2
+ (a) 11 &) 25
[2010:2 Marks] (c) 31 (d) 4i
Comrnon Data for Questions 3.31 and 3.32 [2011:2 Marks]
Consider a complete undirected graph with vertex set
tet G be a weighted graph with edge weights
greater than one and G'be the graph constructed
{0,7,2,3, 4}. Entry W,, in the matrix W below is the
bv squaring the weights of edge in G. Let T and
weight of the edge {i, j}.
T'be the minimum spanning trees of G and G'
(0 181 4\ respectively, with total u,eights t and t'. Which
r o rz 4 ,l
'1
of the fciilowing statements is TRUE?
*=lr t2 o 7 3l (a) T' = T with total weight L' = t2
11 4 7 0 2l (b) T' = T with total weight t' < t2
[a e B 2 o) (c) T' * T but total weight t'= t2
(d) None of the above
3.31 What is the minimum possible weight of a l20l2z 2 Marksl
spanning tree T in this graph such that vertex 0
3.36 Consider the directed graph shown in the figure
is a leaf node in the tree T?
below. There are multiple shortest paths between
(a) 7 @)8 vertices S and T. Whieh one 'arili he reported by
(c) 9 (d) 10
Dijkstra's shortest path algorithm? Asstime that,
[2010:2 Marks] in any iteration, the shortest path to a vertex v
3.32 What is the minimum possible weight of a path is updatedonly rvhen a strictly shorter path to v
P from vertex 1 to vertex 2 in this graph such is discovered.
that P contains at most 3 edges?
(a) 7 &)8
(c) e (d) 10
[2010:2 Marks]
Linked Data Question 3.33 and 3.34
An undirected graph G(V, E) contains n(n > 2) nodes
named yr, y2,..., v.. Two nodes vi, vj are connected if RF
andonlyifO. I i-j I sz. Eachedge (v1,ri)is assigned
a weight i + j. A sample graph with n = 4 is shown
(a) SDT &) SVDT

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]

trEf@ Qreedy Methsd


3.2' (d) 6.+ (c) 3.5 (b) 3.6 (b) 3.7 (b) 3.8 (d) 3.e (a) 3.10 (c) 3.11 (a)
3.12 (b) 3.13 (d) 3.14 (a) 3.15 (a) 3.16 (b) 3.1? (c) 3.18 (d) 3.19 (c) 3.20 (d)
3.2L (d) 3.22 (a) 3.23 (d) 3.24 (d) 3.25 (c) 3.26 (d) 3.27 (d) 3.28 (h) 3.2e (d)
3.30 (d) 3.31 (d) 3.32 (b) 3.33 (b) 3.34 (c) 3.35 (d) 3.36 (d) 3.37 (b) 3.38 (b)
3.41 (a) 3.43 (b)
MADE EASY I Algorithms I 36e

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

The gap betlveen star"ting and ending time of B


is greater than all other activities. Consider the
order b.c.a"d.c"e-f"b" be the gap between b. to bu
is 6 in n-hich two activity a" and c" ended so
minirnum nr:mber of required rooms is 4.
Sc the path length is 52.
ffirur
@rar In Dijkstra's singie source shortest path the nodes
Kruskal's algorithm time cornplexity are inclpded in following seqlrence.
=O(elogv) (oH],
t^

=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

=7* 2+2+ 2+ 3+4 + 4+ 5+8= 31


370 | GATE PreviousYears Solved Papers: !S I MADE EASY

@(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

we add e to rninimum spanning tree it form a


@tar simple circuit. So we can't include e in every
In l&'uskal's algorithm we wilI add the edges of
minimum spanning tree.
minimum weight whether they 2vs zdjacent or not.
Consider each choice separatelv
@t"l
(a) (a - b), (C - 1), (b - 0, (ci - c), (d, e)
11111
1 + 1 + 2 + 2 + 3 =9
(b) (a - b), (d - 0. (d - c), (b - t). (d, e)
The probabilities are
,'Z' a' ro' s2
1 + 1 + 2 + 2 + 3 =9 So, the Huffman code according to tree is unique.
(c) (d - 0, (a - b), (d - c), (b - 0, (d, e)
0, 10. i10. 1110, 11110, 1111 1 represents a, b, c.
1 + 1 + 2 + 2 + 3 =9
(d) (d-f), (a-b), &-0, (d-e), (d*c) d, e, frespectivelv.
1 + 1 + 2 + 3 + 2 =9
In choice (d), we added (d - e) before (d - c) which
r.-iolates algorithm, hence option (d) is not correct.

@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

(a) if fine .but second edge (d, f) is nowhere


(a, b)
connected to previous edge. Therefore (a) is
@rul
BeIIman-Ford shortest path algorithm alvrays
eliminated. finds any negative weighted cycle which is
&) I will straight away go to the point. In reachable from the source. If the negative
choosing edge (g, h) we scan previous edges eighted cycle is not reachable then, Beliman
' and DON'T find'g'or'h'in any of the order
rn

Ford algorithm not able to find that cycie.


pairs. So (g, h) is not adjacent to any of
them. So &) aiso eliminated. You can do @tar
this by marking the graph. as well. In Kruskal's algorithm, edges are added irr non
(c) This satisfies all the required properties. decreasing order, starting from lowest edge
(d) At every stage you will find the graph weight, as Iong as they don't form a cycle with
connected BUT let's check for other property: a1read5, added edges.
GREEDYNESS. When we choose (f, c) and In choice (d): (b, e) edge weight is 2 is added
(f, d) this order violate the greedy approach. first. This step is ok, since 2 is smallest in edge
Because (f, d) has.cost 2 and shouid be weight. Edge (e, f) is then added, whose edge
included before (f, c). Therefore false. weight of 3, is next highest, and hence this is
also ok.
@ral Then edge (b, c) is added. whose edge weight is
Given graph G contains n vertices and 4, and this is not ok is Kruskal's algorithm,
2n - 2 = 2 (n - 1) edges. So spanning tree must since there is an edge (a, c) of edge weight 3,
contains 2n - 4 edges. If G can be partitioned which is less than the edge weight of (b. c). So
into two edge disjoint spdnning tree. Then for (a, c) has to be added before (b, c). Notice also

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.

- 4= 2tn- 2). So there is no two-vertex-disjoint @ral


paths between every pair ofvertices.
;CDE A
@ral Ato 1 8 74
Dijkstra's single source shortest path is not B l' 41249
guaranteed to work for graphs with negative
w= c la 72 0 7 3
weight edges, but it works for the given graph. D lr 4 7 02
Run the 1st pass: b1
ELn 9 3 2A
b is minimum, so shortest distance to b is 1
We draw a graph
After 1st pass, distances are: c3, e - 2
e is minimum, sh<.rrtest distance to e is -2
After 2nd pass, distances are: c3, f0
f is minimum, so shortest distance to f is 0
After 3rd pass, distances are: c3, gB
Both are same, let us take g so shortest distance
togisS
After 4th pass, distances are: c3. h5
c is minimum, so shortest distance to c is 3
After 5th pass, distance is: h - 2 D-
U2 "
h is minimum, so shortest distance to h is -2. We have to make Minimum possible spanning
-1
tree having vertex A is a leafnode.
MADE EASY I Algorithms N 373

'/

So Minimum possible weight


-4+l+2+3=10 18 -

@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

The shortest path from S -+ T is 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

@t"l If we consider edge weights in such order, that


form the cycle, then we have to choose two
Statement P: Since every edge weight is minimum we choose minimum value i.e., 4.
positive and we increase the value ofevery edge
So MST will be
weight by same constant values. So minimum
o=----=1-*a
spanning tree of G does not change. \
\
Statement Q: Taking an example: \
,r7h o'.---7-"
\/ So max weight wiII be 1+ 2 + 4 = 7.
\/
e\
\ \/ /z @or
\/V

First path from 'o' tl '"' ,ri" 'b'have path value


3. But here path can be change 'o' to'e' direct
since paths value is same but path can be Here'BD' is lightest edge in cycle 'BCD'. But

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.1 Abinarysearchtreeis generatedbyinsertingin Linked Answers Questions 4.5 and.4.6


order the foliowing integers: 50, 15, 62, 5, 20. 58. The subset-sum problem is defined as foliows. Given a
91, 3. 8, 37, 60, 24. The numberr of nodes in the set of n positive integers, S = {ar, a.2, &tt ......., ari and a
left subtree and right subtree of the root positive integer W is there a subset S whose elements
respectively is sum of W? A dynamic program for solving this problem
(a) (a,7) (b) (7, 4) uses a 2-dimensional Boolean array, X with n rolvs and
(c) (8, 3) (d) (3.8) W-1 colurnns X [i, j]. 1 <i<n, 0<j <W. is TRUtr ifand
[1996:2 Marks] oniy if there is a subset of {a,. ar....., ai} whose elements
sum to j.
4.2 Which one of the following aigorithrn design
techniques is used in finding all pairs of shortest 4.5 Which of the fbllowing is valid for 2 a i S n and a,
distances in a graph? < j<w?
(a) Dynamic programming (a) X [i, i] = X li -1, il X [i, j-a']
',
ft) Backtracking ft) X [i. ji = X [i -1' j] " X [i-1. j-aJ
(c) X [i. j] = X [i -1, j] .^ X [i, j-aiJ
(c) Greedy
(d) X [i, j] = X [i -1, j] X [i -1, j-aJ
(d) Divide and Conquer .. "
l Mark] [2008:2 Marks]
[1998:
4.6 Which entry of the array X. if TRUE, impiies
4.3 A B-tree of order 4 is built from scratch by 10
that there is a subset. whose elements sum to W?
successive insertions. What is the maximum
(a) X i1, W'l (b) X [n,0]
number of node splitting operations that may take (c) X [n. W.] (d) X [n -1. n]
place?
, 12008:2 Marksl
(a) 3 &)+
(c) 5 (d) 6 Comrnon Data for Question 4.7 and 4.8
A subsequence of a given sequence is just ihe given
[2008:2 Marks]
sequence with some elements (possibiy none or all) left
The subset-sum problem is defined as follows: out. We are given two sequences X[m] and Y[n] of
Given a set S of n positive integers and a positive lengths m and n, respectively, with indexes of X and Y
integer W; determine whether there is a subset starting from 0.
of S whose elements sum to W.
4.7 We wish to find the length of the longest common
An algorithm Q solves this problem in O(nMf
subsequence (LCS) of X[m] andY[n] as /(m, n),
time. Which of the following statements is false?
where an incomplete recursive definition for the
(a) Q solves the subset-sum problem in
function l(i, j) to compute the length of the LCS
polynomial time when the input is encoded of X[m] and Y[n] is given below:
in unar\. l(i, j) = 0, ifeither i = 0 orj = 0
(b) Q solves the subset-Sum problem is = expr1, if i, j > 0 and x[i -1] = Y [ -1]
polynominal time when the input is encoded = expr2, if i, j>0 and x[i-1] +Y[j -11
in binary W-hich one of the following options is correct?
(c) The subset sum problem belongs to the class (a) exprl = l(i-l. j) + 1
NP &) exprl = l(i, j
-1)
(d) The subset sum problem in NP-hard (c) expr2 = max (l(i-1. j), l(i, j-1))
[2008:2 Marks] (d) exPr2 = max (l(i-1, j-1), l(i, j))
[2009:2 Marksj
MADE EASY I Algorithms | 377

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)

Which one of the following statements would be [2013: l Mark]


TRUE i:egarding the dynamic programming 4.11 Consider two strings A = "qpqrr" and B =
solution for the recursive definition ofl(i, j) ? "pqprqrp".Let r be the length of the longest
(a) An elements of L should be initialized to 0 common subsequence (not necessarily contiguous)
for the values of l(i,j) to be properly computed betweenA and B and lety be the number of such
G) The values of l(i, j) may be computed in a longest common subsequences betweenA andB.
row major order or column major order of L Then r +10v -
[M, N] Marksl
(c) The values of l(i, j) cannot be cornputed in
either row major order or column major order 4.12 Consider the weighted undirected graph given
-1zot+(set-2):2
of L [M, N] by with 4 vertices, where the weight of edge {1, j}
(d) L [p, q] needs to be computed before L [r, s] if is the entry W,intlne matrix lV.
eitherp<rorq<s
[2009:2 Marks]
I-o 28 5l
l" 05 8l
An algorithm to find the length of the longest W=l
4.9 50 xl
monotonically increasing sequence of numbers in t: 8r ol
L5
an array A[0: n - 1] is given belorn'.
Let L, denotes the length of the longest The largest possible integer value of r, for which
monotonically increasing sequence starting at at least one shortest path between some pair of
index i in the array vertices will contain the edge with weight r
InitializeL,_r=1 is_-_=___.
For a1I i such that 0< i<n- 2 [2016 (Set-l):2 Marks]
, _ l, +Li*l. If A[i]< e[t + r] 4.13 The Floyd-Warshall algorithm for all-pair
t 1 Otherwise shortest paths computation is based on
Finally the length of the longest monotonically (a) Greedyparadigm
increasing sequence is Max(Lo, L,,......, Lr+ r). (b) Divide-and-conquer paradigm
Which of the following statements is TRUE? (c) Dynamic Programming paradigm
(a) The algorithm uses dynamic programming (d) Neither Greedy nor Divide-and-Conquer nor
paradigm Dynamic Programming paradigm.
(b) The algorithm has a linear complexity and l Mark]
[2016 (Set-2):
uses branch and bound paradigm
(c) The algorithm has a uon-linear polynomial 4.14 Let A, A2, As and A, be four matrices of
complexity and uses branch and bound dimensions 10 x 5, 5 x 20,20 x 10, and 10 x 5,
paradigm respectively. The minimum number of scalar
(d) The algorithm uses divide and conquer multiplications required to find the product A,
paradigm A2AsA4using the basic matrix multiplication
[2011: l Mark] method is
[2016 (set-2) : 2 Marhs]
-' rITI
378 I GATE Previous Years Solved Papers : !$ | MADE EASY

|',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\,
\/ )

[2008 : 1 Mark] \___-/


5.3 Let nobe a problem that belongs to the class NP. P=NP=NPC
Then which one of the following is TRUE?
(d)
(a) There is no polynomial time algorithm forno
(b) If n" can be solved deterministically in
polynomial time, then P = NP (Set-l):2 Marks]
[2014
(c) If n^ is NP-hard, then it is NP-complete
(d) na maybe undecidable 5.6 Consider the decision problem 2CNFSATdefined
as follows:
[2009: l Mark]
{O I O is a satisfiable propositional formula in CNF
5.4 Which of the following statements are TRUE?
with at most two literals per clause)
1. The problem of determining whether there
exists a cycle in an undirected graph is in P. For exampl€, (D = (x, v.lr) ,r (xrv:q )n(xrv,tr) is a
2. The problem of determining whether there Boolean formula and it is in 2CI{FSAT. The
exists a cycle in an undirected graph is in decision problem 2C NFSAT ts
NP. (a) NP-Complete.
3. If a problem A is NP-Complete, there exists ft) solvable in polynomial time by reduction to
a non-deterministic polynomial time directed graph reachability.
algorithm to solve A. (c) solvable in constant time since any input
(a) 1, 2 and 3 &) land3only instance is satisfiable.
(c) 2 only (d) 3 only (d) NP-hard, but not NP-complete.
[2013: l Mark] [20la (Set-8):2 Marks]
MADE EASY I Algorithms I 381

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)

Explanations P & NP Contepts

@'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.

@tur 2. As P c NP so this problem will also be


X is reducible to NPC. Hence X is also NPC. considered as NP problem.
This is the definition of NP-complete so it is
@t*t trivially true.
It is given that no e NP So option (a) is correct
.'. If nois NP- hard, and since it is given that no
e NP, this means that n^ is NP-complete @tal
.'. choice (c) is correct. Clique is NP-complete 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.

Choice (d) is incorrect since,


AII problems belonging to P or NP have to be
decidable.
382 I
GATE PreviousYears Solved Papers: (f! | MADE EASY

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.1 Match the pairs in the following: List-II


List-I 1. Greedy
A. Straseen's matrix multiplication algorithm 2. Depth-First search
B. Kruskal's rninimum spanningtree algorithm 3. D}rnamicProgramming
C. Biconnectedcornponents algorithm 4. Divide and Conquer
D. Floyd's shortest path aigorithm Codes:
List-II (a) A-28-4 C-1D-3
P. Greedymethod o) A-38-4C-1D-2
Q. Dynamic programming (c) A-3F-4C-2D-1
R. Divide and Conquer (d) A-48-1C-2D*3
S. Depth first search [1990 : 2 l\Iarks] [1997: l Mark]
6.2 The minimum number of comparisons required 6.7 Give the correct matching for the following pairs:
to sort 5 eiements is List-I LisLII
[1991:2 Marks] A. O(logn) P. Selection
Following algorithm(s) can be used to sort n B. O(n) Q. Insertion sort
integers in the range [1 ...n3] in O(n) time C. O(nlogn) R. Binary search
(a) Heap sort (b) Quick sort D. O(n2) S. Merge sort
(c) Merge sort (d) Radix sort Codes:
[1992:2 Marks] (a) A-R B-P C-Q D-S
The minimum number of interchanges needed
(b) A-R B-P C-S D-Q
(c) A ,P B-R C-S D-Q
to convert the array
(d) A-P B-S C-R D_Q
89, 19, 40, 17, 72, r0,2, 5,7,11, 6, g, 70 into aheap
with maximum element at the root is [1998:1Mark]
(a) o o)1 6.8 Suppose we want to arrange the n numbers
(c) 2 (d) 3 stored in an array such that all negative values
[1996:2 Marks] occur before all positive ones. Minimum number
b.D The average number of key comparisons done on ofexchanges required in the worst case is
a successful sequential search in list oflength n (a) n-1 (b) n
is (c) n+1 (d) None of these
[1999: l Mark]
(a) log n o)+ 6.9 The number of articulation points of the following
_ n+1 graph is
(c) rl2 ta) ,
[1996:2 Marks]
6.6 The correct matching for the following pairs is
List-I
A. AlI pairs shortest paths
B. Quick Sort
C. Minimum weight spanning tree o)1
(d) 3
D. Connected Components
[1999: l Markl
384 {
GATE Previous Years Solved Papers : [$ | MADE EASY

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

(a) m-w,h-v,o-u,p-X lnl


&) m-w, D-u, o-X, p-v
(c) 4 (d n-21;.1+2
(c) ffi-v,D-w,o-x,p-u 120A2: l Markl
(d) m-w,h-u,o-v,p-X
[1999:2 Marks] Common Data for Q.6.15 & Q. 6.16
In a permutation B1 ... a. of n distinct integers, an
6.11 Lt G be an undirected'graph. Consider a depth- inversion is a pair (a,,'a1) such that i < j and ai > aj.
first traversal of G, and let T be the resulting
depth-first search tree. Let u be a vertex in G 6.15 If all permutations are equally likely, what is
and let v he the first new (unvisited) vertex visited the expected number of inversions in a randomly
after visiting u in the traversal. Which of the chosen permutation of 1...n?

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

@)2 O((log log n)-) for any constant m > 0


l, I
(d) O((Iog log n)k) for some constant k > 0.5, but
[2001:1Mark] not O(Qog 1og n)o 5)

6.13 Consider an undirected unweighted graph G. Let [2003:2 Marks]


a breadth-first traversal of G be done starting 6.18 T\vo matrices M, and M, are to be stored in arrays
from a node r. Let d(r, u) and d(r, v) be the lengths A and B respectively. Each array can be stored
ofthe shortest paths from r to u and v respectively either in row-major or column-major order in
in G. If u is visited before v during the breadth- contiguous memory locations. The time
first traversal, which of the foliowing statement complexity of an algorithm to compute M, t M,
is correct? willbe
MADE EASY I Algorithms i 38s

(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

6.19 Suppose each set is represented as a linked list follows


with elements in arbitrary order. Which of the [rr if ieX
operations among union, intersection, =
"[iJ io: otherwise
membership, cardinality wiII be the slowest?
Consider the following algorithm in which x, y,
(a) uniononly
and, z are booiean arrays of size n:
@) intersection. membershiP
algorithm zzz(xll, y[ ], z[ ])
(c) membership, cardinality
(d) union' intersection {
Marksl int i;
12004:2
for(i=0;i<n:++i)
6.20 A program takes as input a balanced binary z [i] = (x [i] ,^. - vtil) v (-x [i] nylil);
search tree with n leaf nodes and computes the 1
f
value of a function g(x) for each node x' If the The set Z computed by the algorithm is
cost of computing g(x) is min(nurnber of leaf- (a) (X uY) (b) (xnD
nodes in left-subtree of x, number of leaf-nodes (c) (x-Dn(Y-x) (d) (x-Y)u(Y-x)
in right-suhtree'of x) then the worst case time [2006:2 Marks]
complexity of the program is
(a) @(n) (b) O (n log n) 6.25 Given two arrays of numbers 81,..., a. and br,...,
(c) O(n)2 (d) o (2) b. where each number is 0 or 1, the fastest
algorithm to find the largest span (i, j) such that
[2004:2 Marks]
oi * ai*t +..:+ aj = b, + b,*, +...+ b1, or report that
6.21 A scheme for storing binary trees in an array X
there is no such span,
is as fo1lows. Indexing of X starts at 1 instead of
(a) Takes O(3") and Q(2") time if hashing is
0. The root is stored at X[1]. For a node stored at
permitted
X[i], the ]eft child, if any, is stored in X[2i] and
@) Takes O(n3) and Q(nz's; time in the key
the right child, if any, in X[2i + 1]. To be able to
comparison model
store any binary tree on n vertices, the minimum
(c) Takes @(n) time and space
size ofX should be
(a) log, n &) n (d) Takes O(J;) time onlv if the sum of the 2n
(c) 2n + 1 (d) 2n elements is an even number
. t2006: l Markl [2006:2 Marks]
6.22 Which one the following inplace sorting
Which of the following is the correct
aigorithms needs the minimum number of swaps?
decomposition of the directed $aph given below
(a) Quicksort (b) Insertion sort
into its strongly connected components?
(c) Selection sort (d) Heap sort
[2006: l Mark]
An element in an array X is called a leader if it
is greater than all elements to the right of it in
X. The best algorithm to find all leaders in an
array.
(a) Solves it in linear time using a left to right
pass ofthe array
386 ! GATE Previous Years Solved papers : [ft I MADE EASY

(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

(a) @(1) 6.38 Match the following


(b) o(.["g") LisGI
A. Prim's algorithm for minimum spanning
(c)r(ffi) tree
B. Floyd-Warshall algorithm for a1I pairs
(d) @(logn) shortest paths
[2018:2 Marks] C. Mergesort
D. Hamiltoniancircuit
6.36 Consider the directed graph given below.
List-II
1. Backtracking
2. Greedy method
3. Dynamic programming
4, Divide andconquer
Which one of the foliowing is TRUE?
Codes:
(a) The graph does not have any topological
ordering.
A ,B C D
(a)3 2 4 1
o) Both PQRS and SRQP are toPological
orderings. &)1 2 4 3

(c) Both PSRQ and SPRQ are toPological


(c)2 3 4 1.

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

shortcut involving any number, and in particular


2. Dynamic Programming

from 9 there is a shortcut to 15.


3. Greedydesign
4. Depth-first search
Let y and e be such that (9) - 1 + min ((y)'
5. Breadth-frrstsearch
?l(e)). Then the value of the productyzis
Match the above algorithms (List-I) to the
[2014 (Set-3):2 Marks] corresponding design paradigm (List-II) they
-. foilow.
Codes:
A BC D
(a)1 3 1 5

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

f@![ nnistarun roi*cs,


6.3 (d) 6.4 (c) 6.5 (d) 6.6 (b) 6.7 (b) 6.8 (d) 6.e (d) 6.10 (d) 6.11 (c)
6.12 (b) 6.13 (c) 6.14 (d) 6.15 (b) 6.16 (d) 6.L7 (c) 6.18 (d) 6.1e (d) 6.20 (a)
6.21 (b) 6.22 (c) 6.23 (b) 6.24 (d) 6.25 (e) 6.26 (c) 6.27 (d) 6.28 (a) 6.2e (b)
6.30 (i) 6.31 (a) 6.32 (b) 6.33 (b) 6.34 (c) 6.35 (c) 6.36 (c) 6.38 (c) 6.39 (c)
Explanations Miscellaneous Topics

@*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

parent rul = @,tal


[f.]=, Insertion sort runs in O(n + f(n)) time where f(n)
denotes number of inversions.
@tcl Therefore time complexity is @(n).
If u is visited before v, d(r, u) < d(r, v) i.e., r to u
is having shortest or equal length compared from @tut
rtov. The cube root of a natural number n is defined
as the largest natural number m such that m3 <
@rur n. Compiexity of computing the cube root of n is
Cycle may contain even or odd number of vertices O((logn)k) for some constant k > 0.
(i) Let n = even. Then exactly 2 colors are
requiredminimum @t*t
c1 c2 Access time equai for all elements if it is stored
ail------ril
YY l- in array. Accessing any element takes constant
-t
GHU
time.

(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

Topological orderings: PSRQ and SPRQ

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

loe' tonl ]os" ll


olloglogn
= "\ loglogn /]
I

=
lT" (log]ogn-loelostogn)'l
o[.logiogn
\ ' /

- logloglog n\)
o[r"r"[ loglognloglogn
= -))
= @(log n)
Option (c) is correct

You might also like