Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
920 views

CS8451 Design and Analysis of Algorithms MCQ

The document discusses recursion and provides examples of recursive functions and code snippets. It asks multiple choice questions about recursion concepts like base cases, stack memory usage, and evaluating example recursive functions. Recursion is introduced as a problem-solving technique where the solution depends on smaller instances of the same problem until a base case is reached. Recursion uses more memory than iteration due to function calls being stored on the stack.

Uploaded by

sanjana jadhav
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
920 views

CS8451 Design and Analysis of Algorithms MCQ

The document discusses recursion and provides examples of recursive functions and code snippets. It asks multiple choice questions about recursion concepts like base cases, stack memory usage, and evaluating example recursive functions. Recursion is introduced as a problem-solving technique where the solution depends on smaller instances of the same problem until a base case is reached. Recursion uses more memory than iteration due to function calls being stored on the stack.

Uploaded by

sanjana jadhav
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 206

CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Length of a string can be solved using


recursion.
CS8451 DESIGN
3. Recursion is similar to which of the
AND ANALYSIS OF following?
a) Switch Case
ALGORITHMS b) Loop
c) If-else
d) if elif else
CSE - SEMESTER 4 Answer: b
Explanation: Recursion is similar to a loop.

REG. 2017 4. In recursion, the condition for which the


function will stop calling itself is
____________
a) Best case
b) Worst case
c) Base case
UNIT I INTRODUCTION d) There is no such condition
1. Recursion is a method in which the Answer: c
solution of a problem depends on Explanation: For recursion to end at some
____________ point, there always has to be a condition for
a) Larger instances of different problems which the function will not call itself. This
b) Larger instances of the same problem condition is known as base case.
c) Smaller instances of the same problem
d) Smaller instances of different problems 5. Consider the following code snippet:

Answer: c void my_recursive_function()


Explanation: In recursion, the solution of a {
problem depends on the solution of smaller my_recursive_function();
}
instances of the same problem. int main()
{
2. Which of the following problems can’t be my_recursive_function();
solved using recursion? return 0;
a) Factorial of a number }
b) Nth fibonacci number
c) Length of a string What will happen when the above snippet is
d) Problems without base case executed?
a) The code will be executed successfully and
Answer: d no output will be generated
Explanation: Problems without base case b) The code will be executed successfully and
leads to infinite recursion call. In general, we random output will be generated
will assume a base case to avoid infinite c) The code will show a compile time error
recursion call. Problems like finding Factorial d) The code will run for some time and stop
of a number, Nth Fibonacci number and when the stack overflows

Downloaded From: https://cse-r17.blogspot.com 1


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: d c) if(n == 0)
Explanation: Every function call is stored in d) my_recursive_function(n-1)
the stack memory. In this case, there is no
terminating condition(base case). So, Answer: c
my_recursive_function() will be called Explanation: For the base case, the recursive
continuously till the stack overflows and there function is not called. So, “if(n == 0)” is the
is no more space to store the function calls. base case.
At this point of time, the program will stop
abruptly. 8. How many times is the recursive function
called, when the following code is executed?
6. What is the output of the following code?
void my_recursive_function(int n)
void my_recursive_function(int n) {
{ if(n == 0)
if(n == 0) return;
return; printf("%d ",n);
printf("%d ",n); my_recursive_function(n-1);
my_recursive_function(n-1); }
} int main()
int main() {
{ my_recursive_function(10);
my_recursive_function(10); return 0;
return 0; }
}
a) 9
a) 10 b) 10
b) 1 c) 11
c) 10 9 8 … 1 0 d) 12
d) 10 9 8 … 1
Answer: c
Answer: d Explanation: The recursive function is called
Explanation: The program prints the 11 times.
numbers from 10 to 1.
9. What does the following recursive code
7. What is the base case for the following do?
code?
void my_recursive_function(int n)
void my_recursive_function(int n) {
{ if(n == 0)
if(n == 0) return;
return; my_recursive_function(n-1);
printf("%d ",n); printf("%d ",n);
my_recursive_function(n-1); }
} int main()
int main() {
{ my_recursive_function(10);
my_recursive_function(10); return 0;
return 0; }
}
a) Prints the numbers from 10 to 1
a) return b) Prints the numbers from 10 to 0
b) printf(“%d “, n)

Downloaded From: https://cse-r17.blogspot.com 2


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

c) Prints the numbers from 1 to 10 12. What will be the output of the following
d) Prints the numbers from 0 to 10 code?

Answer: c void my_recursive_function(int n)


Explanation: The above code prints the {
if(n == 0)
numbers from 1 to 10. {
printf("False");
10. Which of the following statements is true? return;
a) Recursion is always better than iteration }
b) Recursion uses more memory compared to if(n == 1)
iteration {
printf("True");
c) Recursion uses less memory compared to return;
iteration }
d) Iteration is always better and simpler than if(n%2==0)
recursion my_recursive_function(n/2);
else
{
Answer: b
printf("False");
Explanation: Recursion uses more memory return;
compared to iteration because every time the }
recursive function is called, the function call
is stored in stack. }
int main()
{
11. What will be the output of the following my_recursive_function(100);
code? return 0;
}
int cnt=0;
void my_recursive_function(int n) a) True
{
if(n == 0)
b) False
return;
cnt++; Answer: b
my_recursive_function(n/10); Explanation: The function checks if a
} number is a power of 2. Since 100 is not a
int main() power of 2, it prints false.
{
my_recursive_function(123456789);
printf("%d",cnt); 13. What is the output of the following code?
return 0;
} int cnt = 0;
void my_recursive_function(char *s, int i
a) 123456789 )
{
b) 10 if(s[i] == '\0')
c) 0 return;
d) 9 if(s[i] == 'a' || s[i] == 'e' || s[i
] == 'i' || s[i] == 'o' || s[i] == 'u')
Answer: d cnt++;
my_recursive_function(s,i+1);
Explanation: The program prints the number
}
of digits in the number 123456789, which is int main()
9. {
my_recursive_function("thisisrecursi
on",0);

Downloaded From: https://cse-r17.blogspot.com 3


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

printf("%d",cnt); index of 2 is 4(0 based indexing), the


return 0; program prints 4.
}

a) 6
1. In general, which of the following methods
b) 9
isn’t used to find the factorial of a number?
c) 5
a) Recursion
d) 10
b) Iteration
Answer: a c) Dynamic programming
Explanation: The function counts the number d) Non iterative / recursive
of vowels in a string. In this case the number
Answer: d
is vowels is 6.
Explanation: In general we use recursion,
14. What is the output of the following code? iteration and dynamic programming to find
the factorial of a number. We can also
void my_recursive_function(int *arr, int implement without using iterative / recursive
val, int idx, int len) method by using tgammal() method. Most of
{ us never use it generally.
if(idx == len)
{
2. Which of the following recursive formula
printf("-1");
return ; can be used to find the factorial of a number?
} a) fact(n) = n * fact(n)
if(arr[idx] == val) b) fact(n) = n * fact(n+1)
{ c) fact(n) = n * fact(n-1)
printf("%d",idx);
d) fact(n) = n * fact(1)
return;
}
my_recursive_function(arr,val,idx+1,l Answer: c
en); Explanation: fact(n) = n * fact(n – 1) can be
} used to find the factorial of a number.
int main()
{ 3. Consider the following iterative
int array[10] = {7, 6, 4, 3, 2, 1, 9
, 5, 0, 8}; implementation to find the factorial of a
int value = 2; number:
int len = 10;
my_recursive_function(array, value, int main()
0, len); {
return 0; int n = 6, i;
} int fact = 1;
for(i=1;i<=n;i++)
a) 3 _________;
printf("%d",fact);
b) 4
return 0;
c) 5 }
d) 6
Which of the following lines should be
Answer: b inserted to complete the above code?
Explanation: The program searches for a a) fact = fact + i
value in the given array and prints the index b) fact = fact * i
at which the value is found. In this case, the c) i = i * fact
program searches for value = 2. Since, the d) i = i + fact

Downloaded From: https://cse-r17.blogspot.com 4


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: b return 0;
Explanation: The line “fact = fact * i” should }
be inserted to complete the above code.
a) O(1)
4. Consider the following recursive b) O(n)
implementation to find the factorial of a c) O(n2)
number: d) O(n3)
int fact(int n) Answer: b
{
Explanation: The time complexity of the
if(_________)
return 1; above recursive implementation to find the
return n * fact(n - 1); factorial of a number is O(n).
}
int main() 6. What is the space complexity of the
{ following recursive implementation to find
int n = 5;
int ans = fact(n);
the factorial of a number?
printf("%d",ans);
return 0; int fact(int n)
} {
if(_________)
return 1;
Which of the following lines should be return n * fact(n - 1);
inserted to complete the above code? }
a) n = 0 int main()
b) n != 0 {
c) n == 0 int n = 5;
int ans = fact(n);
d) n == 1 printf("%d",ans);
return 0;
Answer: c }
Explanation: The line “n == 0” should be
inserted to complete the above code. a) O(1)
Note: “n == 1” cannot be used because it does b) O(n)
not take care of the case when n = 0, i.e when c) O(n2)
we want to find the factorial of 0.
d) O(n3)
5. The time complexity of the following Answer: a
recursive implementation to find the factorial Explanation: The space complexity of the
of a number is ________ above recursive implementation to find the
int fact(int n) factorial of a number is O(1).
{
if(_________) 7. Consider the following recursive
return 1; implementation to find the factorial of a
return n * fact(n - 1); number:
}
int main() int fact(int n)
{ {
int n = 5; if(n == 0)
int ans = fact(n); return 1;
printf("%d",ans); return n * fact(n - 1);
}

Downloaded From: https://cse-r17.blogspot.com 5


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

int main() int n = 1;


{ int ans = fact(n);
int n = 5; printf("%d",ans);
int ans = fact(n); return 0;
printf("%d",ans); }
return 0;
} a) 0
b) 1
Which of the following lines is the base case? c) 2
a) return 1 d) 3
b) return n * fact(n-1)
c) if(n == 0) Answer: b
d) if(n == 1) Explanation: The program prints 1!, which is
1.
Answer: c
Explanation: The line “if(n == 0)” is the base 10. How many times will the function fact()
case. be called when the following code is
executed?
8. What is the output of the following code?
int fact(int n)
int fact(int n) {
{ if(n == 0)
if(n == 0) return 1;
return 1; return n * fact(n - 1);
return n * fact(n - 1); }
} int main()
int main() {
{ int n = 5;
int n = 0; int ans = fact(n);
int ans = fact(n); printf("%d",ans);
printf("%d",ans); return 0;
return 0; }
}
a) 4
a) 0 b) 5
b) 1 c) 6
c) 2 d) 7
d) 3
Answer: c
Answer: b Explanation: The fact() function will be
Explanation: The program prints 0!, which is called 6 times with the following arguments:
1. fact(5), fact(4), fact(3), fact(2), fact(1),
fact(0).
9. What is the output of the following code?
11. What is the output of the following code?
int fact(int n)
{
if(n == 0) int fact(int n)
return 1; {
return n * fact(n - 1); if(n == 0)
} return 1;
int main() return n * fact(n - 1);
{ }

Downloaded From: https://cse-r17.blogspot.com 6


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

int main() Answer: d


{ Explanation: Fibonacci number can be
int n = 5;
int ans = fact(n);
calculated by using Dynamic Programming,
printf("%d",ans); Recursion method, Iteration Method.
return 0;
} 4. Consider the following iterative
implementation to find the nth fibonacci
a) 24 number?
b) 120
c) 720 int main()
d) 1 {
int n = 10,i;
if(n == 1)
Answer: b printf("0");
Explanation: The function prints 5!, which is else if(n == 2)
120. printf("1");
else
{
1. Suppose the first fibonnaci number is 0 and int a = 0, b = 1, c;
for(i = 3; i <= n; i++)
the second is 1. What is the sixth fibonnaci {
number? c = a + b;
a) 5 ________;
b) 6 ________;
c) 7 }
printf("%d",c);
d) 8 }
return 0;
Answer: a }
Explanation: The sixth fibonnaci number is
5. Which of the following lines should be added
to complete the above code?
2. Which of the following is not a fibonnaci a)
number?
a) 8 c = b
b) 21
b = a
c) 55
d) 14 b)
Answer: d a = b
Explanation: 14 is not a fibonnaci number.
b = c
3. Which of the following option is wrong?
a) Fibonacci number can be calculated by c)
using Dynamic programming
b = c
b) Fibonacci number can be calculated by
using Recursion method a = b
c) Fibonacci number can be calculated by
using Iteration method d)
d) No method is defined to calculate
Fibonacci number a = b

Downloaded From: https://cse-r17.blogspot.com 7


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

b = a 2) should be inserted to complete the above


code.
Answer: b
Explanation: The lines “a = b” and “b = c” 7. Consider the following recursive
should be added to complete the above code. implementation to find the nth fibonnaci
number:

int fibo(int n)
5. Which of the following recurrence {
relations can be used to find the nth fibonacci if(n == 1)
number? return 0;
else if(n == 2)
a) F(n) = F(n) + F(n – 1) return 1;
b) F(n) = F(n) + F(n + 1) return fibo(n - 1) + fibo(n - 2);
c) F(n) = F(n – 1) }
d) F(n) = F(n – 1) + F(n – 2) int main()
{
Answer: d int n = 5;
int ans = fibo(n);
Explanation: The relation F(n) = F(n – 1) + printf("%d",ans);
F(n – 2) can be used to find the nth fibonacci return 0;
number. }

6. Consider the following recursive Which of the following is the base case?
implementation to find the nth fibonacci a) if(n == 1)
number: b) else if(n == 2)
c) return fibo(n – 1) + fibo(n – 2)
int fibo(int n) d) both if(n == 1) and else if(n == 2)
{
if(n == 1)
Answer: d
return 0;
else if(n == 2) Explanation: Both if(n == 1) and else if(n ==
return 1; 2) are the base cases.
return ________;
} 8. What is the time complexity of the
int main() following recursive implementation to find
{
int n = 5;
the nth fibonacci number?
int ans = fibo(n);
printf("%d",ans); int fibo(int n)
return 0; {
} if(n == 1)
return 0;
else if(n == 2)
Which of the following lines should be return 1;
inserted to complete the above code? return fibo(n - 1) + fibo(n - 2);
a) fibo(n – 1) }
b) fibo(n – 1) + fibo(n – 2) int main()
c) fibo(n) + fibo(n – 1) {
int n = 5;
d) fibo(n – 2) + fibo(n – 1) int ans = fibo(n);
printf("%d",ans);
Answer: b return 0;
Explanation: The line fibo(n – 1) + fibo(n – }

Downloaded From: https://cse-r17.blogspot.com 8


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

a) O(1) {
b) O(2*n) int n = -1;
int ans = fibo(n);
c) O(n2) printf("%d",ans);
d) O(2n) return 0;
}
Answer: d
a) 0
Explanation: The time complexity of the
b) 1
above recursive implementation to find the
c) Compile time error
nth fibonacci number is O(2n). d) Runtime error
9. What is the space complexity of the Answer: d
following recursive implementation to find Explanation: Since negative numbers are not
the nth fibonacci number? handled by the program, the function fibo()
int fibo(int n)
will be called infinite times and the program
{ will produce a runtime error when the stack
if(n == 1) overflows.
return 0;
else if(n == 2) 11. What is the output of the following code?
return 1;
return fibo(n - 1) + fibo(n - 2); int fibo(int n)
} {
int main() if(n == 1)
{ return 0;
int n = 5; else if(n == 2)
int ans = fibo(n); return 1;
printf("%d",ans); return fibo(n - 1) + fibo(n - 2);
return 0; }
} int main()
{
a) O(1) int n = 5;
b) O(2*n) int ans = fibo(n);
printf("%d",ans);
c) O(n2) return 0;
d) O(2n) }

Answer: a a) 1
Explanation: The space complexity of the b) 2
above recursive implementation to find the c) 3
nth fibonacci number is O(1). d) 5

10. What is the output of the following code? Answer: c


Explanation: The program prints the 5th
int fibo(int n) fibonacci number, which is 3.
{
if(n == 1) 12. How many times will the function fibo()
return 0;
else if(n == 2) be called when the following code is
return 1; executed?
return fibo(n - 1) + fibo(n - 2);
} int fibo(int n)
int main() {

Downloaded From: https://cse-r17.blogspot.com 9


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

if(n == 1) 1. Which of the following option is wrong


return 0; about natural numbers?
else if(n == 2)
return 1;
a) Sum of first n natural numbers can be
return fibo(n - 1) + fibo(n - 2); calculated by using Iteration method
} b) Sum of first n natural numbers can be
int main() calculated by using Recursion method
{ c) Sum of first n natural numbers can be
int n = 5;
int ans = fibo(n);
calculated by using Binomial coefficient
printf("%d",ans); method
return 0; d) No method is prescribed to calculate sum
} of first n natural number
a) 5 Answer: d
b) 6 Explanation: All of the above mentioned
c) 8 methods can be used to find the sum of first n
d) 9 natural numbers.
Answer: d 2. Which of the following gives the sum of
Explanation: The function fibo() will be the first n natural numbers?
called 9 times, when the above code is a) nC2
executed. b) (n-1)C2
c) (n+1)C2
13. What is the output of the following code? d) (n+2)C2
int fibo(int n)
Answer: c
{
if(n == 1) Explanation: The sum of first n natural
return 0; numbers is given by n*(n+1)/2, which is
else if(n == 2) equal to (n+1)C2.
return 1;
return fibo(n - 1) + fibo(n - 2); 3. Consider the following iterative solution to
}
int main()
find the sum of first n natural numbers:
{
int n = 10; #include<stdio.h>
int ans = fibo(n); int get_sum(int n)
printf("%d",ans); {
return 0; int sm = 0, i;
} for(i = 1; i <= n; i++)
________;
return sm;
a) 21 }
b) 34 int main()
c) 55 {
d) 13 int n = 10;
int ans = get_sum(n);
Answer: b printf("%d",ans);
return 0;
Explanation: The program prints the 10th }
fibonacci number, which is 34.
Which of the following lines completes the
above code?
a) sm = i

Downloaded From: https://cse-r17.blogspot.com 10


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

b) sm += i {
c) i = sm int n = 10;
int ans = get_sum(n);
d) i += sm printf("%d",ans);
return 0;
Answer: b }
Explanation: The line “sm += i” completes
the above code. a) O(1)
b) O(n)
4. What is the output of the following code? c) O(n2)
#include<stdio.h> d) O(n3)
int get_sum(int n)
{ Answer: b
int sm, i; Explanation: The time complexity of the
for(i = 1; i <= n; i++) above iterative method used to find the sum
sm += i;
return sm; of first n natural numbers is O(n).
}
int main() 6. Consider the following code:
{
int n = 10; #include<stdio.h>
int ans = get_sum(n); int recursive_sum(int n)
printf("%d",ans); {
return 0; if(n == 0)
} return 0;
return ________;
a) 55 }
b) 45 int main()
{
c) 35 int n = 5;
d) Depends on compiler int ans = recursive_sum(n);
printf("%d",ans);
Answer: d return 0;
Explanation: Since the variable “sm” is not }
initialized to 0, it will produce a garbage
value. Some compiler will automatically Which of the following lines is the recurrence
initialises variables to 0 if not initialised. In relation for the above code?
that case the value is 55. Hence the value a) (n – 1) +recursive_sum(n)
depends on the compiler. b) n + recursive_sum(n)
c) n + recursive_sum(n – 1)
5. What is the time complexity of the d) (n – 1) + recursive_sum(n – 1)
following iterative method used to find the
sum of the first n natural numbers? Answer: c
Explanation: The recurrence relation for the
#include<stdio.h> above code is: n + recursive_sum(n – 1).
int get_sum(int n)
{ 7. Consider the following code:
int sm, i;
for(i = 1; i <= n; i++) #include<stdio.h>
sm += i; int recursive_sum(int n)
return sm; {
} if(n == 0)
int main() return 0;

Downloaded From: https://cse-r17.blogspot.com 11


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

return n + recursive_sum(n - 1); least time complexity?


} a) Recursion
int main()
{
b) Iteration
int n = 5; c) Binomial coefficient
int ans = recursive_sum(n); d) All have equal time complexity
printf("%d",ans);
return 0; Answer: c
} Explanation: Recursion and iteration take
O(n) time to find the sum of first n natural
Which of the following is the base case for
numbers while binomial coefficient takes
the above recursive code?
O(1) time.
a) if(n == 0)
b) return 0 10. What is the output of the following code?
c) return n + recursive_sum(n – 1)
d) if(n == 1) #include<stdio.h>
int recursive_sum(int n)
Answer: a {
Explanation: “if(n == 0)” is the base case for if(n == 0)
return 0;
the above recursive code.
return n + recursive_sum(n - 1);
}
8. What is the time complexity of the int main()
following recursive implementation used to {
find the sum of the first n natural numbers? int n = 5;
int ans = recursive_sum(n);
#include<stdio.h> printf("%d",ans);
int recursive_sum(int n) return 0;
{ }
if(n == 0)
return 0; a) 10
return n + recursive_sum(n - 1); b) 15
} c) 21
int main()
{
d) 14
int n = 5;
int ans = recursive_sum(n); Answer: b
printf("%d",ans); Explanation: The above code prints the sum
return 0; of first 5 natural numbers, which is 15.
}
11. How many times is the function
a) O(1) recursive_sum() called when the following
b) O(n) code is executed?
c) O(n2)
d) O(n3) #include<stdio.h>
int recursive_sum(int n)
{
Answer: b if(n == 0)
Explanation: The time complexity of the return 0;
above recursive implementation used to find return n + recursive_sum(n - 1);
the sum of first n natural numbers is O(n). }
int main()
{
9. Which of the following methods used to int n = 5;
find the sum of first n natural numbers has the

Downloaded From: https://cse-r17.blogspot.com 12


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

int ans = recursive_sum(n); int ans = recursive_sum(n);


printf("%d",ans); printf("%d",ans);
return 0; return 0;
} }

a) 4 a) 0
b) 5 b) -10
c) 6 c) 1
d) 7 d) runtime error

Answer: c Answer: d
Explanation: The function recursive_sum is Explanation: The above code doesn’t handle
called 6 times when the following code is the case of negative numbers and so the
executed. function recursive_sum() will be called again
and again till the stack overflows and the
12. What is the output of the following code? program produces a runtime error.
#include<stdio.h>
int recursive_sum(int n)
1. Which of the following is not another name
{
if(n == 0) for GCD(Greatest Common Divisor)?
return 0; a) LCM
return n + recursive_sum(n - 1); b) GCM
} c) GCF
int main()
d) HCF
{
int n = 0;
int ans = recursive_sum(n); Answer: a
printf("%d",ans); Explanation: : LCM (Least Common
return 0; Multiple) and GCD are not same. GCM
} (Greatest Common Measure), GCF (Greatest
Common Factor), HCF (Highest Common
a) -1
Factor) are other names for GCD.
b) 0
c) 1 2. What is the GCD of 8 and 12?
d) runtime error a) 8
b) 12
Answer: b c) 2
Explanation: The program prints the sum of d) 4
first 0 natural numbers, which is 0.
Answer: d
13. What is the output of the following code?
Explanation: GCD is largest positive integer
#include<stdio.h> that divides each of the integer. So the GCD
int recursive_sum(int n) of 8 and 12 is 4.
{
if(n == 0) 3. If GCD of two number is 8 and LCM is
return 0; 144, then what is the second number if first
return n + recursive_sum(n - 1);
}
number is 72?
int main() a) 24
{ b) 2
int n = -4;

Downloaded From: https://cse-r17.blogspot.com 13


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

c) 3 7. What is the GCD according to the given


d) 16 Venn Diagram?

Answer: d
Explanation: As A * B = GCD (A, B) *
LCM (A, B). So B = (144 * 8)/72 = 16.

4. Which of the following is also known as


GCD?
a) Highest Common Divisor
b) Highest Common Multiple
c) Highest Common Measure
d) Lowest Common Multiple a) 2
b) 3
Answer: a c) 5
Explanation: GCM (Greatest Common d) 6
Measure), GCF (Greatest Common Factor),
HCF (Highest Common Factor) and HCF Answer: c
(Highest Common Divisor) are also known as Explanation: In terms of Venn Diagram, the
GCD. GCD is given by the intersection of two sets.
So A ꓵ B gives the GCD. While A U B gives
5. Which of the following is coprime the LCM. So here A ꓵ B is 5.
number?
a) 54 and 24 8. What is the GCD of a and b?
b) 4 and 8 a) a + b
c) 6 and 12 b) gcd (a-b, b) if a>b
d) 9 and 28 c) gcd (a+b, a-b)
d) a – b
Answer: d
Explanation: Coprime numbers have GCD 1. Answer: b
So 9 and 28 are coprime numbers. While 54 Explanation: As per Euclid’s Algorithm, gcd
and 24 have GCD 6, 4 and 8 have GCD 4, 6 (a, b) = gcd (a-b, b) if a > b or gcd (a, b) =
and 12 have GCD 6. gcd (a, b-a) if b > a.
6. In terms of Venn Diagram, which of the 9. What is the GCD of 48, 18, 0?
following expression gives GCD (Given A ꓵ a) 24
B ≠ Ø)? b) 2
a) Multiplication of A U B terms c) 3
b) Multiplication of A ꓵ B terms d) 6
c) Multiplication of A*B terms
d) Multiplication of A-B terms Answer: d
Explanation: GCD is largest positive integer
Answer: b that divides each of the integer. So the GCD
Explanation: In terms of Venn Diagram, the of 48, 18, 0 is 6.
GCD is given by the intersection of two sets.
So A ꓵ B gives the GCD. While A U B gives 10. Is 9 and 28 coprime number?
the LCM. a) True
b) False

Downloaded From: https://cse-r17.blogspot.com 14


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: a Answer: a
Explanation: Coprime numbers have GCD 1. Explanation: In the year 1972, James E.
So 9 and 28 are coprime numbers. Nymann showed some result to show the
probability and expected value of gcd.
11. If gcd (a, b) is defined by the expression,
d=a*p + b*q where d, p, q are positive 15. What is the computational complexity of
integers and a, b is both not zero, then what is Binary GCD algorithm where a and b are
the expression called? integers?
a) Bezout’s Identity a) O (log a + log b)2)
b) Multiplicative Identity b) O (log (a + b))
c) Sum of Product c) O (log ab)
d) Product of Sum d) O (log a-b)
Answer: a Answer: a
Explanation: If gcd (a, b) is defined by the Explanation: From the Binary GCD
expression, d=a*p + b*q where d, p, q are algorithm, it is found that the computational
positive integers and a, b is both not zero,
complexity is O (log a + log b)2) as the total
then the expression is called Bezout’s Identity
number of steps in the execution is at most
and p, q can be calculated by extended form
the total sum of number of bits of a and b.
of Euclidean algorithm.

12. Is gcd an associative function. 1. LCM is also called as ________


a) True
a) GCD
b) False
b) SCM
c) GCF
Answer: a
d) HCF
Explanation: The gcd function is an
associative function as gcd (a, gcd (b, c)) =
Answer: b
gcd (gcd (a, b), c).
Explanation: GCD (Greatest Common
Divisor), GCF (Greatest Common Factor),
13. Which is the correct term of the given
relation, gcd (a, b) * lcm (a, b) =? HCF (Highest Common Factor) is not an alias
for LCM. LCM is also called as Smallest
a) |a*b|
b) a + b Common Multiple(SCM).
c) a – b
2. What is the LCM of 8 and 13?
d) a / b
a) 8
b) 12
Answer: a
c) 20
Explanation: The gcd is closely related to
d) 104
lcm as gcd (a, b) * lcm (a, b) = |a*b|.

14. Who gave the expression for the Answer: d


probability and expected value of gcd? Explanation: 104 is the smallest positive
integer that is divisible by both 8 and 12.
a) James E. Nymann
b) Riemann 3. Which is the smallest number of 3 digits
c) Thomae that is divisible by 2, 4, 8?
d) Euler a) 100
b) 102

Downloaded From: https://cse-r17.blogspot.com 15


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

c) 116
d) 104

Answer: d
Explanation: LCM of 2, 4, 8 is 8. So check
for the number that is divisible by 8. So 104
is the smallest number that is divisible by 2,
4, 8.

M
4. Which of the following is also known as
a) 2
LCM?
b) 3

O
a) Lowest Common Divisor
c) 180
b) Least Common Multiple
d) 6

C
c) Lowest Common Measure
d) Highest Common Multiple Answer: c

T.
Explanation: In terms of Venn Diagram, the
Answer: a
LCM is given by the Union of two sets. So A
Explanation: Least Common Multiple is also

O
U B gives the LCM. So product of all the
known as LCM or Lowest Common Multiple.
terms is 180.
5. What is the LCM of two coprime numbers?
a) 1
b) 0
SP
8. What is the lcm (a, b)?
a) a + b
G
b) gcd (a-b, b) if a>b
c) Addition of two coprime numbers
c) lcm (b, a)
d) Multiplication of two coprime numbers
LO

d) a – b
Answer: d
Answer: c
Explanation: Coprime numbers have GCD 1.
Explanation: Since the LCM function is
While LCM of coprime numbers is the
.B

commutative, so lcm (a, b) = lcm (b, a).


product of those two coprime numbers.
9. What is the LCM of 48, 18, 6?
17

6. In terms of Venn Diagram, which of the


following expression gives LCM (Given A ꓵ a) 122
B ≠ Ø)? b) 12*2
c) 3
-R

a) Multiplication of A U B terms
d) 6
b) Multiplication of A ꓵ B terms
c) Multiplication of A*B terms Answer: a
SE

d) Multiplication of A-B terms Explanation: The LCM of 48, 18, 6 is 144


Answer: a and 122 is 144.
Explanation: In terms of Venn Diagram, the
C

10. Is 9 and 28 coprime number.


LCM is given by the Union of two sets. So A
a) True
U B gives the LCM. While A ꓵ B gives the b) False
GCD.
Answer: a
7. What is the LCM according to the given Explanation: Coprime numbers have GCD 1
Venn Diagram?

Downloaded From: https://cse-r17.blogspot.com 16


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

and LCM is the product of the two given 15. Which algorithm is the most efficient
terms. So 9 and 28 are coprime numbers. numerical algorithm to obtain lcm?
a) Euler’s Algorithm
11. What is the following expression, lcm (a, b) Euclid’s Algorithm
lcm (b, c) equal to? c) Chebyshev Function
a) lcm (a, b, c) d) Partial Division Algorithm
b) a*b*c
c) a + b + c Answer: b
d) lcm (lcm (a, b), c) Explanation: The most efficient way of
calculating the lcm of a given number is using
Answer: d Euclid’s algorithm which computes the lcm in
Explanation: Since LCM function follows much lesser time compared to other
associativity, hence lcm (a, lcm (b, c) is equal algorithms.
to lcm (lcm (a, b), c).

12. Is lcm an associative function. 1. Which of the following methods can be


a) True used to find the sum of digits of a number?
b) False a) Recursion
b) Iteration
Answer: a c) Greedy algorithm
Explanation: The lcm function is an d) Both recursion and iteration
associative function as lcm (a, lcm (b, c) is
equal to lcm (lcm (a, b), c). Answer: d
Explanation: Both recursion and iteration
13. Which is the correct term of the given can be used to find the sum of digits of a
relation, lcm (a, b) * gcd (a, b) =? number.
a) |a*b|
b) a + b 2. What can be the maximum sum of digits
c) a – b for a 4 digit number?
d) a / b a) 1
b) 16
Answer: a c) 36
Explanation: The lcm is closely related to d) 26
gcd as lcm (a, b) * gcd (a, b) = |a*b|.
Answer: c
14. What is the following expression, lcm (a, Explanation: The sum of digits will be
gcd (a, b)) equal to? maximum when all the digits are 9. Thus, the
a) a sum will be maximum for the number 9999,
b) b which is 36.
c) a*b
d) a + b 3. What can be the minimum sum of digits for
a 4 digit number?
Answer: a a) 0
Explanation: Since the lcm function follows b) 1
absorption laws so lcm (a, gcd (a, b)) equal to c) 16
a. d) 36

Downloaded From: https://cse-r17.blogspot.com 17


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: b }
Explanation: The sum of digits will be int main()
{
minimum for the number 1000 and the sum is int n = 1234;
1. int ans = sum_of_digits(n);
printf("%d",ans);
4. Consider the following iterative return 0;
implementation to find the sum of digits of a }
number:
a) 1
#include<stdio.h> b) 3
int sum_of_digits(int n) c) 7
{ d) 10
int sm = 0;
while(n != 0)
{
Answer: d
_________; Explanation: The above code prints the sum
n /= 10; of digits of the number 1234, which is 10.
}
return sm; 6. Consider the following recursive
} implementation to find the sum of digits of
int main()
{ number:
int n = 1234;
int ans = sum_of_digits(n); #include<stdio.h>
printf("%d",ans); int recursive_sum_of_digits(int n)
return 0; {
} if(n == 0)
return 0;
return _________;
Which of the following lines should be
}
inserted to complete the above code? int main()
a) sm += n {
b) sm += n%10 int n = 1201;
c) sm += n-10 int ans = recursive_sum_of_digits(n
);
d) sm += n/10
printf("%d",ans);
return 0;
Answer: b }
Explanation: The line “sm += n % 10” adds
the last digit(LSB) of the number to the Which of the following lines should be
current sum. Thus, the line “sm += n%10” inserted to complete the above code?
should be added to complete the above code. a) (n / 10) + recursive_sum_of_digits(n % 10)
b) (n) + recursive_sum_of_digits(n % 10)
5. What is the output of the following code? c) (n % 10) + recursive_sum_of_digits(n / 10)
d) (n % 10) + recursive_sum_of_digits(n %
#include<stdio.h>
10)
int sum_of_digits(int n)
{
int sm = 0; Answer: c
while(n != 0) Explanation: The line “(n % 10) +
{ recursive_sum_of_digits(n / 10)” should be
sm += n%10; inserted to complete the above code.
n /= 10;
}
return sm;

Downloaded From: https://cse-r17.blogspot.com 18


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

7. What is the time complexity of the c) 15


following recursive implementation to find d) 14
the sum of digits of a number n?
Answer: b
#include<stdio.h> Explanation: The above code prints the sum
int recursive_sum_of_digits(int n) of digits of the number 1234321, which is 16.
{
if(n == 0)
return 0; 9. How many times is the function
return _________; recursive_sum_of_digits() called when the
} following code is executed?
int main()
{ #include<stdio.h>
int n = 1201; int recursive_sum_of_digits(int n)
int ans = recursive_sum_of_digits(n {
); if(n == 0)
printf("%d",ans); return 0;
return 0; return n % 10 + recursive_sum_of_di
} gits(n/10);
}
a) O(n) int main()
b) O(1) {
int n = 1201;
c) O(len(n)), where len(n) is the number of
int ans = recursive_sum_of_digits(n
digits in n );
d) O(1/2) printf("%d",ans);
return 0;
Answer: c }
Explanation: The time complexity of the
above recursive implementation to find the a) 6
sum of digits of a number is O(len(n)). b) 7
c) 5
8. What is the output of the following code? d) 9

#include<stdio.h> Answer: c
int recursive_sum_of_digits(int n) Explanation: The function
{ recursive_sum_of_digits() is called 8 times,
if(n == 0)
return 0;
when the following code is executed.
return n % 10 + recursive_sum_of_di
gits(n/10); 10. You have to find the sum of digits of a
} number given that the number is always
int main() greater than 0. Which of the following base
{ cases can replace the base case for the below
int n = 1234321;
int ans = recursive_sum_of_digits(n code?
);
printf("%d",ans); #include<stdio.h>
return 0; int recursive_sum_of_digits(int n)
} {
if(n == 0)
return 0;
a) 10
return n % 10 + recursive_sum_of_di
b) 16 gits(n/10);
}

Downloaded From: https://cse-r17.blogspot.com 19


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

int main() int i, tmp_sm;


{ for(i=1;i<=n;i++)
int n = 1201; {
int ans = recursive_sum_of_digits(n tmp_sm = recursive_sum_of_digit
); s(i);
printf("%d",ans); if(tmp_sm == sm)
return 0; cnt++;
} }
return cnt;
a) if(n == 0) return 1 }
b) if(n == 1) return 0 int recursive_sum_of_digits(int n)
{
c) if(n == 1) return 1 if(n == 0)
d) no need to modify the base case return 0;
return n % 10 + recursive_sum_of_di
Answer: d gits(n/10);
Explanation: None of the above mentioned }
int main()
base cases can replace the base case if(n == {
0) return 0. int n = 20, sum = 3;
int ans = my_function(n,sum);
11. What is the output of the following code? printf("%d",ans);
return 0;
#include<stdio.h> }
int recursive_sum_of_digits(int n)
{ a) 0
if(n == 0) b) 1
return 0;
return n % 10 + recursive_sum_of_di
c) 2
gits(n/10); d) 3
}
int main() Answer: c
{ Explanation: The code prints the count of
int n = 10000; numbers between 1 and 20 such that the sum
int ans = recursive_sum_of_digits(n
); of their digits is 3. There are only two such
printf("%d",ans); numbers: 3 and 12.
return 0;
}
1. Consider the following iterative
a) 0 implementation used to reverse a string:
b) 1
c) runtime error #include<stdio.h>
d) -1 #include<string.h>
void reverse_string(char *s)
{
Answer: b int len = strlen(s);
Explanation: The program prints the sum of int i,j;
digits of the number 10000, which is 1. i=0;
j=len-1;
12. What is the output of the following code? while(______)
{
#include<stdio.h> char tmp = s[i];
int cnt =0; s[i] = s[j];
int my_function(int n, int sm) s[j] = tmp;
{ i++;

Downloaded From: https://cse-r17.blogspot.com 20


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

j--; a) O(1)
} b) O(n)
}
c) O(n2)
Which of the following lines should be d) O(n3)
inserted to complete the above code?
a) i > j Answer: b
b) i < len Explanation: The time complexity of the
c) j > 0 above code used to reverse a string is O(n).
d) i < j
4. What does the following code do?
Answer: d
Explanation: The line “i < j” should be #include<stdio.h>
#include<string.h>
inserted to complete the above code. void reverse_string(char *s)
{
2. What is the output of the following code? int len = strlen(s);
int i,j;
#include<stdio.h> i=0;
#include<string.h> j=len-1;
void reverse_string(char *s) while(i < j)
{ {
int len = strlen(s); char tmp = s[i];
int i,j; s[i] = s[j];
i=0; s[j] = tmp;
j=len-1; i++;
while(i < j) j--;
{ }
char tmp = s[i]; }
s[i] = s[j]; int main()
s[j] = tmp; {
i++; char s[100] = "abcdefg";
j--; char t[100];
} strcpy(t,s);
} reverse_string(s);
int main() if(strcmp(t,s) == 0)
{ printf("Yes");
char s[100] = "reverse"; else
reverse_string(s); printf("No");
printf("%s",s); return 0;
return 0; }
}
a) Copies a string to another string
a) ersevre b) Compares two strings
b) esrever c) Reverses a string
c) eserver d) Checks if a string is a palindrome
d) eresevr
Answer: d
Answer: b Explanation: The main purpose of the above
Explanation: The program reverses the string code is to check if a string is a palindrome.
“reverse” and prints “esrever”.
5. What is the output of the following code?
3. What is the time complexity of the above
code used to reverse a string?

Downloaded From: https://cse-r17.blogspot.com 21


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

#include<stdio.h> Which of the following lines should be


#include<string.h> inserted to complete the above code?
void reverse_string(char *s)
{
a) recursive_reverse_string(s, left+1, right+1)
int len = strlen(s); b) recursive_reverse_string(s, left-1, right-1)
int i,j; c) recursive_reverse_string(s, left+1, right-1)
i=0; d) recursive_reverse_string(s, left-1, right+1)
j=len-1;
while(i < j) Answer: c
{
char tmp = s[i]; Explanation: The line
s[i] = s[j]; “recursive_reverse_string(s, left+1, right-1)”
s[j] = tmp; should be inserted to complete the above
i++; code.
j--;
}
}
7. What is the output of the following code?
int main()
{ #include<stdio.h>
char s[100] = "rotator"; #include<string.h>
char t[100]; void recursive_reverse_string(char *s, in
strcpy(t,s); t left, int right)
reverse_string(s); {
if(strcmp(t,s) == 0) if(left < right)
printf("Yes"); {
else char tmp = s[left];
printf("No"); s[left] = s[right];
return 0; s[right] = tmp;
} recursive_reverse_string(s, left
+1, right-1);
}
a) Yes }
b) No int main()
c) Runtime error {
d) Compile time error char s[100] = "recursion";
int len = strlen(s);
recursive_reverse_string(s,0,len-1);
Answer: a printf("%s",s);
Explanation: The program checks if a string return 0;
is a palindrome. Since the string rotator is a }
palindrome, it prints “yes”.
a) recursion
6. Consider the following recursive b) nsoirucer
implementation used to reverse a string: c) noisrcuer
d) noisrucer
void recursive_reverse_string(char *s, in
t left, int right) Answer: d
{
if(left < right) Explanation: The program prints the
{ reversed string of “recursion”, which is
char tmp = s[left]; “noisrucer”.
s[left] = s[right];
s[right] = tmp; 8. How many times is the function
_________;
recursive_reverse_string() called when the
}
} following code is executed?

Downloaded From: https://cse-r17.blogspot.com 22


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

#include<stdio.h> c) Empty String


#include<string.h> d) Strings of length 2
void recursive_reverse_string(char *s, in
t left, int right)
{ Answer: d
if(left < right) Explanation: String “ab” is a string of length
{ 2 whose reversal is not the same as the given
char tmp = s[left]; one. Palindromic Strings, String of length 1
s[left] = s[right]; and Empty Strings case – the reversal is the
s[right] = tmp;
recursive_reverse_string(s, left same as the one given.
+1, right-1);
}
} 1. Which of the following is the binary
int main() representation of 100?
{
char s[100] = "madam";
a) 1010010
int len = strlen(s); b) 1110000
recursive_reverse_string(s,0,len-1); c) 1100100
printf("%s",s); d) 1010101
return 0;
} Answer: c
a) 3 Explanation: 100 = 64 + 32 + 4 = 26 + 25 +
b) 4 22 = 1100100.
c) 5
d) 6 2. Consider the following iterative code used
to convert a decimal number to its equivalent
Answer: a binary:
Explanation: The function
recursive_reverse_string() is called 3 times #include<stdio.h>
void dec_to_bin(int n)
when the above code is executed. {
int arr[31],len = 0,i;
9. What is the time complexity of the above if(n == 0)
recursive implementation used to reverse a {
string? arr[0] = 0;
len = 1;
a) O(1)
}
b) O(n) while(n != 0)
c) O(n2) {
arr[len++] = n % 2;
d) O(n3) _______;
}
Answer: b for(i=len-1; i>=0; i--)
Explanation: The time complexity of the printf("%d",arr[i]);
above recursive implementation used to }
int main()
reverse a string is O(n). {
int n = 10;
10. In which of the following cases is the dec_to_bin(n);
reversal of a string not equal to the original return 0;
string? }
a) Palindromic strings
b) Strings of length 1

Downloaded From: https://cse-r17.blogspot.com 23


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Which of the following lines should be {


inserted to complete the above code? arr[0] = 0;
len = 1;
a) n– }
b) n /= 2 while(n != 0)
c) n /= 10 {
d) n++ arr[len++] = n % 2;
n /= 2;
Answer: b }
for(i=len-1; i>=0; i--)
Explanation: The line “n /= 2” should be printf("%d",arr[i]);
inserted to complete the above code. }
int main()
3. What is the output of the following code? {
int n = 0;
#include<stdio.h> dec_to_bin(n);
void dec_to_bin(int n) return 0;
{ }
int arr[31],len = 0,i;
if(n == 0) a) 0
{ b) 1
arr[0] = 0; c) Runtime error
len = 1;
} d) Garbage value
while(n != 0)
{ Answer: a
arr[len++] = n % 2; Explanation: The program prints the binary
n /= 2; equivalent of 0, which is 0.
}
for(i=len-1; i>=0; i--)
printf("%d",arr[i]);
5. What is the time complexity of the
} following code used to convert a decimal
int main() number to its binary equivalent?
{
int n = 63; #include<stdio.h>
dec_to_bin(n); void dec_to_bin(int n)
return 0; {
} int arr[31],len = 0,i;
if(n == 0)
a) 111111 {
b) 111011 arr[0] = 0;
len = 1;
c) 101101 }
d) 101010 while(n != 0)
{
Answer: a arr[len++] = n % 2;
Explanation: The program prints the binary n /= 2;
equivalent of 63, which is 111111. }
for(i=len-1; i>=0; i--)
printf("%d",arr[i]);
4. What is the output of the following code? }
int main()
#include<stdio.h> {
void dec_to_bin(int n) int n = 0;
{ dec_to_bin(n);
int arr[31],len = 0,i; return 0;
if(n == 0) }

Downloaded From: https://cse-r17.blogspot.com 24


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

a) O(1) #include<stdio.h>
b) O(n) int arr[31], len = 0;
void recursive_dec_to_bin(int n)
c) O(n2) {
d) O(logn) if(n == 0 && len == 0)
{
Answer: d arr[len++] = 0;
return;
Explanation: The time complexity of the }
above code used to convert a decimal number if(n == 0)
to its binary equivalent is O(logn). return;
arr[len++] = n % 2;
6. Consider the following recursive recursive_dec_to_bin(n/2);
implementation used to convert a decimal }
number to its binary equivalent:
Which of the following lines is the base case
#include<stdio.h> for the above code?
int arr[31], len = 0; a) if(n ==0 && len == 0)
void recursive_dec_to_bin(int n) b) if(n == 0)
{ c) if(n ==0 && len == 0) and if(n == 0)
if(n == 0 && len == 0)
{
d) if(n == 1)
arr[len++] = 0;
return; Answer: c
} Explanation: Both of the above mentioned
if(n == 0) lines are the base cases for the above code.
return;
__________;
8. What is the output of the following code?
recursive_dec_to_bin(n/2);
}
int main() #include<stdio.h>
{ int arr[31], len = 0;
int n = 100,i; void recursive_dec_to_bin(int n)
recursive_dec_to_bin(n); {
for(i=len-1; i>=0; i--) if(n == 0 && len == 0)
printf("%d",arr[i]); {
return 0; arr[len++] = 0;
} return;
}
if(n == 0)
Which of the following lines should be return;
inserted to complete the above code? arr[len++] = n % 2;
a) arr[len] = n recursive_dec_to_bin(n/2);
b) arr[len] = n % 2 }
c) arr[len++] = n % 2 int main()
{
d) arr[len++] = n int n = -100,i;
recursive_dec_to_bin(n);
Answer: c for(i=len-1; i>=0; i--)
Explanation: The line “arr[len++] = n % 2” printf("%d",arr[i]);
should be inserted to complete the above return 0;
}
code.
a) -1100100
7. Consider the following code:
b) 1100100

Downloaded From: https://cse-r17.blogspot.com 25


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

c) 2’s complement of 1100100 return;


d) Garbage value arr[len++] = n % 2;
recursive_dec_to_bin(n/2);
}
Answer: d
Explanation: The program doesn’t handle a) O(1)
negative inputs and so produces a garbage b) O(n)
value.
c) O(n2)
9. What is the time complexity of the d) O(logn)
recursive implementation used to convert a
Answer: d
decimal number to its binary equivalent?
Explanation: The space complexity of the
#include<stdio.h> recursive implementation used to convert a
int arr[31], len = 0; decimal number to its binary equivalent is
void recursive_dec_to_bin(int n) O(logn).
{
if(n == 0 && len == 0) 11. What is the output of the following code?
{
arr[len++] = 0;
#include<stdio.h>
return;
int arr[31], len = 0;
}
void recursive_dec_to_bin(int n)
if(n == 0)
{
return;
if(n == 0 && len == 0)
arr[len++] = n % 2;
{
recursive_dec_to_bin(n/2);
arr[len++] = 0;
}
return;
}
a) O(1) if(n == 0)
b) O(n) return;
c) O(n2) arr[len++] = n % 2;
recursive_dec_to_bin(n/2);
d) O(logn) }
int main()
Answer: d {
Explanation: The time complexity of the int n = 111,i;
recursive implementation used to convert a recursive_dec_to_bin(n);
decimal number to its binary equivalent is for(i=len-1; i>=0; i--)
printf("%d",arr[i]);
O(logn). return 0;
}
10. What is the space complexity of the
recursive implementation used to convert a a) 1110111
decimal number to its binary equivalent? b) 1001111
c) 1101111
#include<stdio.h> d) 1010111
int arr[31], len = 0;
void recursive_dec_to_bin(int n)
{ Answer: c
if(n == 0 && len == 0) Explanation: The program prints the binary
{ equivalent of 111, which is 1101111.
arr[len++] = 0;
return; 12. How many times is the function
}
if(n == 0)
recursive_dec_to_bin() called when the

Downloaded From: https://cse-r17.blogspot.com 26


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

following code is executed? return len;


}
#include<stdio.h>
int arr[31], len = 0; Which of the following conditions should be
void recursive_dec_to_bin(int n) checked to complete the above code?
{ a) temp->next != 0
if(n == 0 && len == 0)
{
b) temp == 0
arr[len++] = 0; c) temp != 0
return; d) temp->next == 0
}
if(n == 0) Answer: c
return; Explanation: The condition “temp != 0”
arr[len++] = n % 2;
recursive_dec_to_bin(n/2); should be checked to complete the above
} code.
int main()
{ 2. What is the output of the following code?
int n = 111,i;
recursive_dec_to_bin(n); #include<stdio.h>
for(i=len-1; i>=0; i--) #include<stdlib.h>
printf("%d",arr[i]); struct Node
return 0; {
} int val;
struct Node *next;
a) 7 }*head;
b) 8 int get_len()
c) 9 {
struct Node *temp = head->next;
d) 10 int len = 0;
while(temp != 0)
Answer: b {
Explanation: The function len++;
recursive_dec_to_bin() is called 8 times when temp = temp->next;
}
the above code is executed.
return len;
}
int main()
1. Consider the following iterative {
implementation used to find the length of a int arr[10] = {1,2,3,4,5}, n = 5, i
linked list: ;
struct Node *temp, *newNode;
head = (struct Node*)malloc(sizeof(
struct Node
struct Node));
{
head->next = 0;
int val;
temp = head;
struct Node *next;
for(i=0; i<n; i++)
}*head;
{
int get_len()
newNode = (struct Node*)malloc(
{
sizeof(struct Node));
struct Node *temp = head->next;
newNode->val = arr[i];
int len = 0;
newNode->next = 0;
while(_____)
temp->next = newNode;
{
temp = temp->next;
len++;
}
temp = temp->next;
int len = get_len();
}
printf("%d",len);

Downloaded From: https://cse-r17.blogspot.com 27


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

return 0; return 0;
} }

a) 4 a) O(1)
b) 5 b) O(n)
c) 6 c) O(n2)
d) 7 d) O(logn)
Answer: b Answer: b
Explanation: The program prints the length Explanation: The time complexity of the
of the linked list, which is 5. above iterative implementation used to find
the length of a linked list is O(n).
3. What is the time complexity of the
following iterative implementation used to 4. What is the output of the following code?
find the length of a linked list?
#include<stdio.h>
#include<stdio.h> #include<stdlib.h>
#include<stdlib.h> struct Node
struct Node {
{ int val;
int val; struct Node *next;
struct Node *next; }*head;
}*head; int get_len()
int get_len() {
{ struct Node *temp = head->next;
struct Node *temp = head->next; int len = 0;
int len = 0; while(temp != 0)
while(temp != 0) {
{ len++;
len++; temp = temp->next;
temp = temp->next; }
} return len;
return len; }
} int main()
int main() {
{ int arr[10] = {1,2,3,4,5}, n = 5, i
int arr[10] = {1,2,3,4,5}, n = 5, i ;
; struct Node *temp, *newNode;
struct Node *temp, *newNode; head = (struct Node*)malloc(sizeof(
head = (struct Node*)malloc(sizeof( struct Node));
struct Node)); head->next = 0;
head->next = 0; int len = get_len();
temp = head; printf("%d",len);
for(i=0; i<n; i++) return 0;
{ }
newNode = (struct Node*)malloc(
sizeof(struct Node)); a) 0
newNode->val = arr[i];
newNode->next = 0;
b) Garbage value
temp->next = newNode; c) Compile time error
temp = temp->next; d) Runtime error
}
int len = get_len(); Answer: a
printf("%d",len); Explanation: The program prints the length

Downloaded From: https://cse-r17.blogspot.com 28


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

of the linked list, which is 0. implementation used to find the length of a


linked list?
5. Which of the following can be the base
case for the recursive implementation used to #include<stdio.h>
find the length of linked list? #include<stdlib.h>
struct Node
{
#include<stdio.h>
int val;
#include<stdlib.h>
struct Node *next;
struct Node
}*head;
{
int recursive_get_len(struct Node *curren
int val;
t_node)
struct Node *next;
{
}*head;
if(current_node == 0)
int get_len()
return 0;
{
return _____;
struct Node *temp = head->next;
}
int len = 0;
int main()
while(temp != 0)
{
{
int arr[10] = {1,2,3,4,5}, n = 5, i
len++;
;
temp = temp->next;
struct Node *temp, *newNode;
}
head = (struct Node*)malloc(sizeof(
return len;
struct Node));
}
head->next = 0;
int main()
temp = head;
{
for(i=0; i<n; i++)
int arr[10] = {1,2,3,4,5}, n = 5, i
{
;
newNode = (struct Node*)malloc(
struct Node *temp, *newNode;
sizeof(struct Node));
head = (struct Node*)malloc(sizeof(
newNode->val = arr[i];
struct Node));
newNode->next = 0;
head->next = 0;
temp->next = newNode;
int len = get_len();
temp = temp->next;
printf("%d",len);
}
return 0;
int len = recursive_get_len(head->n
}
ext);
printf("%d",len);
a) if(current_node == 0) return 1 return 0;
b) if(current_node->next == 0) return 1 }
c) if(current_node->next == 0) return 0
d) if(current_node == 0) return 0 a) recursive_get_len(current_node)
b) 1 + recursive_get_len(current_node)
Answer: d c) recursive_get_len(current_node->next)
Explanation: The line “if(current_node == 0) d) 1 + recursive_get_len(current_node->next)
return 0” can be used as a base case in the
recursive implementation used to find the Answer: d
length of a linked list. Note: The line Explanation: The line “1 +
“if(current_node->next == 0) return 1” cannot recursive_get_len(current_node->next)”
be used because it won’t work when the should be inserted to complete the above
length of the linked list is zero. code.

6. Which of the following lines should be 7. What is the output of the following code?
inserted to complete the following recursive

Downloaded From: https://cse-r17.blogspot.com 29


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

#include<stdio.h> {
#include<stdlib.h> int val;
struct Node struct Node *next;
{ }*head;
int val; int recursive_get_len(struct Node *curren
struct Node *next; t_node)
}*head; {
int recursive_get_len(struct Node *curren if(current_node == 0)
t_node) return 0;
{ return 1 + recursive_get_len(curren
if(current_node == 0) t_node->next);
return 0; }
return 1 + recursive_get_len(curren int main()
t_node->next); {
} int arr[10] = {-1,2,3,-3,4,5,0}, n
int main() = 7, i;
{ struct Node *temp, *newNode;
int arr[10] = {-1,2,3,-3,4,5,0}, n head = (struct Node*)malloc(sizeof(
= 7, i; struct Node));
struct Node *temp, *newNode; head->next = 0;
head = (struct Node*)malloc(sizeof( temp = head;
struct Node)); for(i=0; i<n; i++)
head->next = 0; {
temp = head; newNode = (struct Node*)malloc(
for(i=0; i<n; i++) sizeof(struct Node));
{ newNode->val = arr[i];
newNode = (struct Node*)malloc( newNode->next = 0;
sizeof(struct Node)); temp->next = newNode;
newNode->val = arr[i]; temp = temp->next;
newNode->next = 0; }
temp->next = newNode; int len = recursive_get_len(head->n
temp = temp->next; ext);
} printf("%d",len);
int len = recursive_get_len(head->n return 0;
ext); }
printf("%d",len);
return 0; a) O(1)
} b) O(n)
a) 6 c) O(n2)
b) 7 d) O(n3)
c) 8
d) 9 Answer: b
Explanation: To find the length of the linked
Answer: b list, the program iterates over the linked list
Explanation: The program prints the length once. So, the time complexity of the above
of the linked list, which is 7. code is O(n).

8. What is the time complexity of the 9. What is the output of the following code?
following code used to find the length of a
linked list? #include<stdio.h>
#include<stdlib.h>
struct Node
#include<stdio.h>
{
#include<stdlib.h>
int val;
struct Node

Downloaded From: https://cse-r17.blogspot.com 30


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

struct Node *next; t_node)


}*head; {
int recursive_get_len(struct Node *curren if(current_node == 0)
t_node) return 0;
{ return 1 + recursive_get_len(curren
if(current_node == 0) t_node->next);
return 0; }
return 1 + recursive_get_len(curren int main()
t_node->next); {
} int arr[10] = {-1,2,3,-3,4,5}, n =
int main() 6, i;
{ struct Node *temp, *newNode;
int arr[10] = {-1,2,3,-3,4,5}, n = head = (struct Node*)malloc(sizeof(
6, i; struct Node));
struct Node *temp, *newNode; head->next = 0;
head = (struct Node*)malloc(sizeof( temp = head;
struct Node)); for(i=0; i<n; i++)
head->next = 0; {
temp = head; newNode = (struct Node*)malloc(
for(i=0; i<n; i++) sizeof(struct Node));
{ newNode->val = arr[i];
newNode = (struct Node*)malloc( newNode->next = 0;
sizeof(struct Node)); temp->next = newNode;
newNode->val = arr[i]; temp = temp->next;
newNode->next = 0; }
temp->next = newNode; int len = recursive_get_len(head->n
temp = temp->next; ext);
} printf("%d",len);
int len = recursive_get_len(head->n return 0;
ext); }
printf("%d",len);
return 0; a) 5
} b) 6
c) 7
a) 5
d) 8
b) 6
c) 7 Answer: c
d) 8 Explanation: The function is called “len + 1”
times. Since the length of the linked list in the
Answer: b
above code is 6, the function is called 6 + 1 =
Explanation: The program prints the length
7 times.
of the linked list, which is 6.

10. How many times is the function


1. Consider the following iterative
recursive_get_len() called when the following
implementation to find the length of the
code is executed?
string:
#include<stdio.h>
#include<stdlib.h> #include<stdio.h>
struct Node int get_len(char *s)
{ {
int val; int len = 0;
struct Node *next; while(________)
}*head; len++;
int recursive_get_len(struct Node *curren return len;

Downloaded From: https://cse-r17.blogspot.com 31


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

} #include<stdio.h>
int main() int get_len(char *s)
{ {
char *s = "harsh"; int len = 0;
int len = get_len(s); while(s[len] != '\0')
printf("%d",len); len++;
return 0; return len;
} }
int main()
Which of the following lines should be {
inserted to complete the above code? char *s = "lengthofstring";
int len = get_len(s);
a) s[len-1] != 0 printf("%d",len);
b) s[len+1] != 0 return 0;
c) s[len] != ‘\0’ }
d) s[len] == ‘\0’
a) O(1)
Answer: c b) O(n)
Explanation: The line “s[len] != ‘\0′” should c) O(n2)
be inserted to complete the above code. d) O(logn)
2. What is the output of the following code? Answer: b
Explanation: The time complexity of the
#include<stdio.h>
code used to find the length of the string is
int get_len(char *s)
{ O(n).
int len = 0;
while(s[len] != '\0') 4. What is the output of the following code?
len++;
return len; #include<stdio.h>
} int get_len(char *s)
int main() {
{ int len = 0;
char *s = "lengthofstring"; while(s[len] != '\0')
int len = get_len(s); len++;
printf("%d",len); return len;
return 0; }
} int main()
{
a) 14 char *s = "";
b) 0 int len = get_len(s);
printf("%d",len);
c) Compile time error return 0;
d) Runtime error }

Answer: a a) 0
Explanation: The program prints the length b) 1
of the string “lengthofstring”, which is 14. c) Runtime error
d) Garbage value
3. What is the time complexity of the
following code used to find the length of the Answer: a
string? Explanation: The program prints the length
of an empty string, which is 0.

Downloaded From: https://cse-r17.blogspot.com 32


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

5. Which of the following can be the base b) len


case for the recursive implementation used to c) recursive_get_len(s, len+1)
find the length of a string? d) 1 + recursive_get_len(s, len+1)
#include<stdio.h> Answer: d
int get_len(char *s) Explanation: The line “1 +
{
int len = 0;
recursive_get_len(s, len+1)” should be
while(s[len] != '\0') inserted to complete the code.
len++;
return len; 7. What is the output of the following code?
}
int main() #include<stdio.h>
{ int recursive_get_len(char *s, int len)
char *s = ""; {
int len = get_len(s); if(s[len] == 0)
printf("%d",len); return 0;
return 0; return 1 + recursive_get_len(s, len
} +1);
}
a) if(string[len] == 1) return 1 int main()
b) if(string[len+1] == 1) return 1 {
char *s = "abcdef";
c) if(string[len] == ‘\0’) return 0
int len = recursive_get_len(s,0);
d) if(string[len] == ‘\0’) return 1 printf("%d",len);
return 0;
Answer: c }
Explanation: “if(string[len] == ‘\0’) return 0”
can be used as base case in the recursive a) 5
implementation used to find the length of the b) 6
string. c) 7
d) 8
6. Consider the following recursive
implementation used to find the length of a Answer: b
string: Explanation: The above code prints the
length of the string “abcdef”, which is 6.
#include<stdio.h>
int recursive_get_len(char *s, int len) 8. What is the time complexity of the
{ following recursive implementation used to
if(s[len] == 0)
return 0; find the length of the string?
return ________;
} #include<stdio.h>
int main() int recursive_get_len(char *s, int len)
{ {
char *s = "abcdef"; if(s[len] == 0)
int len = recursive_get_len(s,0); return 0;
printf("%d",len); return 1 + recursive_get_len(s, len
return 0; +1);
} }
int main()
{
Which of the following lines should be
char *s = "abcdef";
inserted to complete the above code? int len = recursive_get_len(s,0);
a) 1 printf("%d",len);

Downloaded From: https://cse-r17.blogspot.com 33


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

return 0; }
} int main()
{
a) O(1) char *s = "123-1-2-3";
b) O(n) int len = recursive_get_len(s,0);
printf("%d",len);
c) O(n2) return 0;
d) O(n3) }

Answer: b a) 3
Explanation: The time complexity of the b) 6
above recursive implementation used to find c) 9
the length of the string is O(n). d) 10

9. How many times is the function Answer: c


recursive_get_len() called when the following Explanation: The above program prints the
code is executed? length of the string “123-1-2-3”, which is 9.

#include<stdio.h>
int recursive_get_len(char *s, int len) 1. If Matrix A is of order X*Y and Matrix B
{ is of order M*N, then what is the order of the
if(s[len] == 0) Matrix A*B given that Y=M?
return 0;
return 1 + recursive_get_len(s, len
a) Y*N
+1); b) X*M
} c) X*N
int main() d) Y*M
{
char *s = "adghjkl"; Answer: c
int len = recursive_get_len(s,0);
printf("%d",len); Explanation: The Matrix A*B is of order
return 0; X*N as it is given that Y=M i.e. number of
} columns in Matrix A is equal to total number
of rows in matrix B. So the Matrix A*B must
a) 6 have X number of rows and N number of
b) 7 columns.
c) 8
d) 9 2. How many recursive calls are there in
Recursive matrix multiplication through
Answer: c Simple Divide and Conquer Method?
Explanation: The function a) 2
recursive_get_len() is called 8 times when the b) 6
above code is executed. c) 9
d) 8
10. What is the output of the following code?
Answer: d
#include<stdio.h>
int recursive_get_len(char *s, int len)
Explanation: For the multiplication two
{ square matrix recursively using Simple
if(s[len] == 0) Divide and Conquer Method, there are 8
return 0; recursive calls performed for high time
return 1 + recursive_get_len(s, len complexity.
+1);

Downloaded From: https://cse-r17.blogspot.com 34


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

3. What is the time complexity of matrix c) 16


multiplied recursively by Divide and Conquer d) 20
Method?
a) O(n) Answer: b
b) O(n2) Explanation: The resultant matrix will be of
order 3*5 when multiplied recursively and
c) O(n3)
therefore the matrix will have 3*5=15
d) O(n!)
elements.
Answer: c
7. If Matrix X is of order A*B and Matrix Y
Explanation: The time complexity of
is of order C*D, and B=C then the order of
recursive multiplication of two square the Matrix X*Y is A*D?
matrices by the Divide and Conquer method a) True
is found to be O(n3) since there are total of 8 b) False
recursive calls.
Answer: a
4. What is the time complexity of matrix Explanation: Given that B=C, so the two
multiplied recursively by Strassen’s Method? matrix can be recursively multiplied.
a) O(nlog7) Therefore, the order of the Matrix X*Y is
b) O(n2) A*D.
c) O(n3)
8. What is the time complexity of the fastest
d) O(n!)
known matrix multiplication algorithm?
Answer: a a) O(nlog7)
Explanation The time complexity of recursive b) O(n2.37)
multiplication of two square matrices by c) O(n3)
Strassen’s Method is found to be O(nlog7) d) O(n!)
since there are total 7 recursive calls.
Answer: b
5. How many recursive calls are there in Explanation: The Coppersmith-Winograd
Recursive matrix multiplication by Strassen’s algorithm multiplies the matrices in O(n2.37)
Method? time. Several improvements have been made
a) 5 in the algorithm since 2010.
b) 7
c) 8 9. Is Coppersmith-Winograd algorithm better
d) 4 than Strassen’s algorithm in terms of time
complexity?
Answer: b a) True
Explanation: For the multiplication two b) False
square matrix recursively using Strassen’s
Method, there are 7 recursive calls performed Answer: a
for high time complexity. Explanation: Since The Coppersmith-
Winograd algorithm multiplies the matrices in
6. Matrix A is of order 3*4 and Matrix B is of O(n2.37) time. The time complexity of
order 4*5. How many elements will be there recursive multiplication of two square
in a matrix A*B multiplied recursively. matrices by Strassen’s Method is found to be
a) 12
b) 15 O(n2.80). Therefore, Coppersmith-Winograd

Downloaded From: https://cse-r17.blogspot.com 35


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

algorithm better than Strassen’s algorithm in a) Last node


terms of time complexity. b) First node
c) Random node
d) Middle node
1. Which of the following statement is true
about stack? Answer: b
a) Pop operation removes the top most Explanation: First node is considered as the
element top element when stack is implemented using
b) Pop operation removes the bottom most linked list.
element
c) Push operation adds new element at the 5. What is the time complexity of the
bottom program to reverse stack when linked list is
d) Push operation removes the top most used for its implementation?
element a) O(n)
b) O(n log n)
Answer: a C) O(n2)
Explanation: As stack is based on LIFO(Last D) O(log n)
In First Out) principle so the deletion takes
place from the topmost element. Thus pop Answer: a
operator removes topmost element. Explanation: As a linked list takes O(n) time
for getting reversed thus linked list version of
2. What is the space complexity of program stack will also take the same time.
to reverse stack recursively?
a) O(1) 6. Which of the following takes O(n) time in
b) O(log n) worst case in array implementation of stack?
c) O(n) a) pop
d) O(n log n) b) push
c) isEmpty
Answer: c d) pop, push and isEmpty takes constant time
Explanation: The recursive program to
reverse stack uses memory of the order n to Answer: d
store function call stack. Explanation: Functions pop, push and
isEmpty all are implemented in constant time
3. Stack can be reversed without using extra in worst case.
space by _____________
a) using recursion 7. What will be the time complexity of the
b) using linked list to implement stack code to reverse stack recursively?
c) using an extra stack a) O(n)
d) it is not possible b) O(n log n)
c) O(log n)
Answer: b d) O(n2)
Explanation: If linked list is used for
implementing stack then it can be reversed Answer: d
without using any extra space. Explanation: The recurrence relation for the
recursive code to reverse stack will be given
4. Which of the following is considered as the by-T(n)=T(n-1)+n.This is calculated to be
top of the stack in the linked list
implementation of the stack? equal to O(n2).

Downloaded From: https://cse-r17.blogspot.com 36


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

8. Which of the following functions correctly Answer: c


represents the recursive approach to reverse a Explanation: We keep on holding the
stack? elements in call stack until we reach the
a) bottom of the stack.Then we insert elements
at the bottom.This reverses our stack.
int reverse()
{
if(s.size()<0)
{
9. Which of the following correctly represents

M
int x = s.top();
s.pop(); the function to insert elements at the bottom
reverse(); of stack?

O
BottomInsert(x); a)
}

C
}
int BottomInsert(int x)
{
b)

T.
if(s.size()!=0) s.push(x);
else
int reverse() {

O
{ int a = s.top();
if(s.size()>=0) s.pop();
{ BottomInsert(x);
int x = s.top();
s.pop();
reverse();
BottomInsert(x);
SP
}
}
s.push(a);
G
} b)
}
LO

int BottomInsert(int x)
c) {
if(s.size()==0) s.push(x);
int reverse() else
.B

{ {
if(s.size()>0) int a = s.top();
{ s.pop();
17

int x = s.top(); s.push(a);


s.pop(); BottomInsert(x);
reverse(); }
BottomInsert(x); }
-R

}
} c)
SE

d) int BottomInsert(int x)
{
int reverse() if(s.size()==0) s.push(x);
{ else
C

if(s.size()>0) {
{ int a = s.top();
int x = s.top(); s.pop();
BottomInsert(x); BottomInsert(x);
s.pop(); s.push(a);
reverse(); }
} }
}
d)

Downloaded From: https://cse-r17.blogspot.com 37


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

int BottomInsert(int x) #include <stack>


{ void reverseStack(stack<int> &input, stac
if(s.size()==0) s.push(x); k<int> &extra)
else {
{ while(input.size()!=0)
s.pop(); {
int a = s.top(); input.pop();
BottomInsert(x); extra.push(input.top());
s.push(a); }
} extra.swap(input);
} }

Answer: c d)
Explanation: We hold all the elements in the
call stack until we reach the bottom of stack #include <stack>
and then the first if statement is executed as void reverseStack(stack<int> &input, stac
k<int> &extra)
the stack is empty at this stage.Finally we
{
push back all the elements held in the call while(input.size()==0)
stack. {
input.pop();
extra.push(input.top());
}
extra.swap(input);
10. Which of the following code correctly }
represents the function to reverse stack
without using recursion? Answer: b
a) Explanation: We are using one extra stack to
reverse the given stack. First the elements of
#include <stack> the original stack are pushed into the other
void reverseStack(stack<int> &input, stac
k<int> &extra)
stack which creates a reversed version of the
{ original stack. Then we swap this stack with
while(input.size()!=0) the original stack.
{
extra.push(input.top());
input.pop();
}
input.swap(extra);
} 1. Which of the following sorting algorithm
has best case time complexity of O(n2)?
b) a) bubble sort
b) selection sort
#include <stack>
void reverseStack(stack<int> &input, stac
c) insertion sort
k<int> &extra) d) stupid sort
{
while(input.size()!=0) Answer: b
{ Explanation: Selection sort is not an adaptive
extra.push(input.top()); sorting algorithm. It finds the index of
input.pop();
} minimum element in each iteration even if the
extra.swap(input); given array is already sorted. Thus its best
} case time complexity becomes O(n2).
c)

Downloaded From: https://cse-r17.blogspot.com 38


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

2. Which of the following is the biggest c) O(log n)


advantage of selection sort? d) O(n log n)
a) its has low time complexity
b) it has low space complexity Answer: b
c) it is easy to implement Explanation: Selection sort’s algorithm is
d) it requires only n swaps under any such that it finds the index of minimum
condition element in each iteration even if the given
array is already sorted. Thus its best case time
Answer: d complexity becomes O(n2).
Explanation: Selection sort works by
obtaining least value element in each iteration 6. Recursive selection sort is a comparison
and then swapping it with the current index. based sort.
So it will take n swaps under any condition a) true
which will be useful when memory write b) false
operation is expensive.
Answer: a
3. What will be the recurrence relation of the Explanation: In selection sort we need to
code of recursive selection sort? compare elements in order to find the
a) T(n) = 2T(n/2) + n minimum element in each iteration. So we
b) T(n) = 2T(n/2) + c can say that it uses comparisons in order to
c) T(n) = T(n-1) + n sort the array. Thus it qualifies as a
d) T(n) = T(n-1) + c comparison based sort.

Answer: c 7. What is the average case time complexity


Explanation: Function to find the minimum of recursive selection sort?
element index takes n time.The recursive call a) O(n)
is made to one less element than in the b) O(n log n)
previous call so the overall recurrence c) O(n2)
relation becomes T(n) = T(n-1) + n. d) O(log n)
4. Which of the following sorting algorithm is Answer: c
NOT stable? Explanation: The overall recurrence relation
a) Selection sort of recursive selection sort is given by T(n) =
b) Brick sort
c) Bubble sort T(n-1) + n. It is found to be equal to O(n2). It
d) Merge sort is unvaried throughout the three cases.

8. What is the bidirectional variant of


Answer: a
Explanation: Out of the given options selection sort?
a) cocktail sort
selection sort is the only algorithm which is
b) bogo sort
not stable. It is because the order of identical
c) gnome sort
elements in sorted output may be different
from input array. d) bubble sort

Answer: a
5. What will be the best case time complexity
Explanation: A bidirectional variant of
of recursive selection sort?
a) O(n) selection sort is called cocktail sort. It’s an
algorithm which finds both the minimum and
b) O(n2) maximum values in the array in every pass.

Downloaded From: https://cse-r17.blogspot.com 39


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

This reduces the number of scans of the array int x = minIndex(a, index, n-1);
by a factor of 2. if (x != index)
{
swap(a[x], a[index]);
9. Choose correct C++ code for recursive }
selection sort from the following. recursiveSelectionSort(a, n, inde
a) x + 1);
}
#include <iostream> int main()
using namespace std; {
int minIndex(int a[], int i, int j) int arr[] = {5,3,2,4,1};
{ int n = sizeof(arr)/sizeof(arr[0]
if (i == 0) );
return i; recursiveSelectionSort(arr, n);
int k = minIndex(a, i + 1, j); return 0;
return (a[i] < a[k])? i : k; }
}
void recursiveSelectionSort(int a[], int c)
n, int index = 0)
{ #include <iostream>
using namespace std;
if (index == n) int minIndex(int a[], int i, int j)
return; {
int x = minIndex(a, index, n-1); if (i == j)
if (x == index) return i;
{ int k = minIndex(a, i + 1, j);
swap(a[x], a[index]); return (a[i] > a[k])? i : k;
} }
recursiveSelectionSort(a, n, inde void recursiveSelectionSort(int a[], int
x + 1); n, int index = 0)
} {
int main() if (index == n)
{ return;
int arr[] = {5,3,2,4,1}; int x = minIndex(a, index, n-1);
int n = sizeof(arr)/sizeof(arr[0] if (x != index)
); {
recursiveSelectionSort(arr, n); swap(a[x], a[index]);
return 0; }
} recursiveSelectionSort(a, n, inde
x + 1);
b) }
int main()
#include <iostream> {
using namespace std; int arr[] = {5,3,2,4,1};
int minIndex(int a[], int i, int j) int n = sizeof(arr)/sizeof(arr[0]
{ );
if (i == j) recursiveSelectionSort(arr, n);
return i; return 0;
int k = minIndex(a, i + 1, j); }
return (a[i] < a[k])? i : k;
} d)
void recursiveSelectionSort(int a[], int
n, int index = 0) #include <iostream>
{ using namespace std;
int minIndex(int a[], int i, int j)
if (index == n) {
return;

Downloaded From: https://cse-r17.blogspot.com 40


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

if (i == j) 1. Which of the following methods can be


return i; used to find the largest and smallest element
int k = minIndex(a, i + 1, j);
return (a[i] > a[k])? i : k;
in an array?
} a) Recursion
void recursiveSelectionSort(int a[], int b) Iteration
n, int index = 0) c) Both recursion and iteration
{ d) No method is suitable
if (index == 0)
return;
int x = minIndex(a, index, n-1); Answer: c
if (x == index) Explanation: Both recursion and iteration
{ can be used to find the largest and smallest
swap(a[x], a[index]); element in an array.
}
recursiveSelectionSort(a, n, inde
2. Consider the following iterative code
x + 1);
} snippet to find the largest element:
int main()
{ int get_max_element(int *arr,int n)
int arr[] = {5,3,2,4,1}; {
int n = sizeof(arr)/sizeof(arr[0] int i, max_element = arr[0];
); for(i = 1; i < n; i++)
recursiveSelectionSort(arr, n); if(________)
return 0; max_element = arr[i];
} return max_element;
}
Answer: b
Explanation: Using the function Which of the following lines should be
recursiveSelectionSort() we find the element inserted to complete the above code?
that needs to be placed at the current index. a) arr[i] > max_element
For finding the minimum element index we b) arr[i] < max_element
use another function minIndex(). After c) arr[i] == max_element
finding the minimum element index the d) arr[i] != max_element
current element is swapped with this element
in the function recursiveSelectionSort(). Answer: a
Explanation: The line “arr[i] >
max_element” should be inserted to complete
the above code snippet.
10. What is the number of swaps required to
sort the array arr={5,3,2,4,1} using recursive 3. Consider the following code snippet to find
selection sort? the smallest element in an array:
a) 0
int get_min_element(int *arr, int n)
b) 1 {
c) 2 int i, min_element = arr[0];
d) 3 for(i = 1; i < n; i++)
if(_______)
Answer: c min_element = arr[i];
return min_element;
Explanation: The first swap takes place }
between 1 and 5. The second swap takes
place between 3 and 2 which sorts our array. Which of the following lines should be
inserted to complete the above code?

Downloaded From: https://cse-r17.blogspot.com 41


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

a) arr[i] > min_element #include<stdio.h>


b) arr[i] < min_element int get_max_element(int *arr,int n)
{
c) arr[i] == min_element int i, max_element = arr[0];
d) arr[i] != min_element for(i = 1; i < n; i++)
if(arr[i] > max_element)
Answer: b max_element = arr[i];
Explanation: The line “arr[i] < min_element” return max_element;
should be inserted to complete the above }
int get_min_element(int *arr, int n)
code. {
int i, min_element;
4. What is the output of the following code? for(i = 1; i < n; i++)
if(arr[i] < min_element)
#include<stdio.h> min_element = arr[i];
int get_max_element(int *arr,int n) return min_element;
{ }
int i, max_element = arr[0]; int main()
for(i = 1; i < n; i++) {
if(arr[i] > max_element) int n = 7, arr[7] = {1,1,1,0,-1,-1,-
max_element = arr[i]; 1};
return max_element; int max_element = get_max_element(ar
} r,n);
int get_min_element(int *arr, int n) int min_element = get_min_element(ar
{ r,n);
int i, min_element = arr[0]; printf("%d %d",max_element,min_eleme
for(i = 1; i < n; i++) nt);
if(arr[i] < min_element) return 0;
min_element = arr[i]; }
return min_element;
} a) 1 -1
int main() b) -1 1
{
int n = 7, arr[7] = {5,2,4,7,8,1,3}; c) 1 Garbage value
int max_element = get_max_element(ar d) Depends on the compiler
r,n);
int min_element = get_min_element(ar Answer: c
r,n); Explanation: Since the min_element variable
printf("%d %d",max_element,min_eleme
is not initialised, some compilers will auto
nt);
return 0; initialise as 0 which produces -1 as output
} whereas some compilers won’t initialise
automatically. In that case, the result will be a
a) 5 3 garbage value hence the output depends on
b) 3 5 the compiler.
c) 8 1
d) 1 8 6. What is the time complexity of the
following iterative implementation used to
Answer: c find the largest and smallest element in an
Explanation: The program prints the values array?
of the largest and the smallest elements in the
array, which are 8 and 1 respectively. #include<stdio.h>
int get_max_element(int *arr,int n)
{
5. What is the output of the following code? int i, max_element = arr[0];
for(i = 1; i < n; i++)

Downloaded From: https://cse-r17.blogspot.com 42


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

if(arr[i] > max_element) Which of the following lines should be


max_element = arr[i]; inserted to complete the above code?
return max_element;
}
a) max_of_two(arr[idx],
int get_min_element(int *arr, int n) recursive_max_element(arr, len, idx))
{ b) recursive_max_element(arr, len, idx)
int i, min_element; c) max_of_two(arr[idx],
for(i = 1; i < n; i++) recursive_max_element(arr, len, idx + 1))
if(arr[i] < min_element)
min_element = arr[i];
d) recursive_max_element(arr, len, idx + 1)
return min_element;
} Answer: c
int main() Explanation: The line “max_of_two(arr[idx],
{ recursive_max_element(arr, len, idx + 1))”
int n = 7, arr[7] = {1,1,1,0,-1,-1,- should be inserted to complete the above
1};
int max_element = get_max_element(ar code.
r,n);
int min_element = get_min_element(ar 8. What is the output of the following code?
r,n);
printf("%d %d",max_element,min_eleme #include<stdio.h>
nt); int max_of_two(int a, int b)
return 0; {
} if(a > b)
return a;
a) O(1) return b;
b) O(n) }
int min_of_two(int a, int b)
c) O(n2) {
d) O(n/2) if(a < b)
return a;
Answer: b return b;
}
Explanation: The time complexity of the int recursive_max_element(int *arr, int l
above iterative implementation used to find en, int idx)
the largest and the smallest element in an {
array is O(n). if(idx == len - 1)
return arr[idx];
7. Consider the following recursive return max_of_two(arr[idx], recursi
ve_max_element(arr, len, idx + 1));
implementation to find the largest element in }
an array. int recursive_min_element(int *arr, int l
en, int idx)
int max_of_two(int a, int b) {
{ if(idx == len - 1)
if(a > b) return arr[idx];
return a; return min_of_two(arr[idx], recursi
return b; ve_min_element(arr, len, idx + 1));
} }
int recursive_max_element(int *arr, int l int main()
en, int idx) {
{ int n = 10, idx = 0, arr[] = {5,2,6,7
if(idx == len - 1) ,8,9,3,-1,1,10};
return arr[idx]; int max_element = recursive_max_eleme
return _______; nt(arr,n,idx);
} int min_element = recursive_min_eleme
nt(arr,n,idx);

Downloaded From: https://cse-r17.blogspot.com 43


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

printf("%d %d",max_element,min_elemen nt(arr,n,idx);


t); int min_element = recursive_min_eleme
return 0; nt(arr,n,idx);
} printf("%d %d",max_element,min_elemen
t);
a) -1 10 return 0;
b) 10 -1 }
c) 1 10
a) O(1)
d) 10 1
b) O(n)
Answer: b c) O(n2)
Explanation: The program prints the values d) O(n3)
of the largest and the smallest element in the
array, which are 10 and -1 respectively. Answer: b
Explanation: The time complexity of the
9. What is the time complexity of the above recursive implementation used to find
following recursive implementation used to the largest and smallest element in an array is
find the largest and the smallest element in an O(n).
array?
10. How many times is the function
#include<stdio.h> recursive_min_element() called when the
int max_of_two(int a, int b) following code is executed?
{
if(a > b)
int min_of_two(int a, int b)
return a;
{
return b;
if(a < b)
}
return a;
int min_of_two(int a, int b)
return b;
{
}
if(a < b)
int recursive_min_element(int *arr, int l
return a;
en, int idx)
return b;
{
}
if(idx == len - 1)
int recursive_max_element(int *arr, int l
return arr[idx];
en, int idx)
return min_of_two(arr[idx], recursi
{
ve_min_element(arr, len, idx + 1));
if(idx == len - 1)
}
return arr[idx];
int main()
return max_of_two(arr[idx], recursi
{
ve_max_element(arr, len, idx + 1));
int n = 10, idx = 0, arr[] = {5,2,6,
}
7,8,9,3,-1,1,10};
int recursive_min_element(int *arr, int l
int min_element = recursive_min_elem
en, int idx)
ent(arr,n,idx);
{
printf("%d",min_element);
if(idx == len - 1)
return 0;
return arr[idx];
}
return min_of_two(arr[idx], recursi
ve_min_element(arr, len, idx + 1));
} a) 9
int main() b) 10
{ c) 11
int n = 10, idx = 0, arr[] = {5,2,6,7 d) 12
,8,9,3,-1,1,10};
int max_element = recursive_max_eleme

Downloaded From: https://cse-r17.blogspot.com 44


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: b Answer: a
Explanation: The function Explanation: The program prints the values
recursive_min_element() is called 10 times of the largest and the smallest element in the
when the above code is executed. array, which are 1 and 1.

11. What is the output of the following code?


1. Which of the following methods can be
#include<stdio.h> used to find the largest and smallest number
int max_of_two(int a, int b)
in a linked list?
{
if(a > b) a) Recursion
return a; b) Iteration
return b; c) Both Recursion and iteration
} d) Impossible to find the largest and smallest
int min_of_two(int a, int b)
numbers
{
if(a < b)
return a; Answer: c
return b; Explanation: Both recursion and iteration
} can be used to find the largest and smallest
int recursive_max_element(int *arr, int l number in a linked list.
en, int idx)
{
if(idx == len - 1) 2. Consider the following code snippet to find
return arr[idx]; the largest element in a linked list:
return max_of_two(arr[idx], recursi
ve_max_element(arr, len, idx + 1)); struct Node{
} int val;
int recursive_min_element(int *arr, int l struct Node *next;
en, int idx) }*head;
{ int get_max()
if(idx == len - 1) {
return arr[idx]; struct Node* temp = head->next;
return min_of_two(arr[idx], recursi int max_num = temp->val;
ve_min_element(arr, len, idx + 1)); while(______)
} {
int main() if(temp->val > max_num)
{ max_num = temp->val;
int n = 5, idx = 0, arr[] = {1,1,1,1 temp = temp->next;
,1}; }
int max_element = recursive_max_elem return max_num;
ent(arr,n,idx); }
int min_element = recursive_min_elem
ent(arr,n,idx); Which of the following lines should be
printf("%d %d",max_element,min_eleme inserted to complete the above code?
nt);
return 0;
a) temp->next != 0
} b) temp != 0
c) head->next != 0
a) 1 1 d) head != 0
b) 0 0
c) compile time error Answer: b
d) runtime error Explanation: The line “temp != 0” should be
inserted to complete the above code.

Downloaded From: https://cse-r17.blogspot.com 45


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

3. Consider the following code snippet to find int main()


the smallest element in a linked list: {
int n = 9, arr[9] ={5,1,3,4,5,2,3,3
,1},i;
struct Node
struct Node *temp, *newNode;
{
head = (struct Node*)malloc(sizeof(
int val;
struct Node));
struct Node* next;
head -> next =0;
}*head;
temp = head;
int get_min()
for(i=0;i<n;i++)
{
{
struct Node* temp = head->next;
newNode =(struct Node*)malloc(s
int min_num = temp->val;
izeof(struct Node));
while(temp != 0)
newNode->next = 0;
{
newNode->val = arr[i];
if(_________)
temp->next =newNode;
min_num = temp->val;
temp = temp->next;
temp = temp->next;
}
}
int max_num = get_max();
return min_num;
printf("%d %d",max_num);
}
return 0;
}
Which of the following lines should be
inserted to complete the above code? a) 5
a) temp > min_num b) 1
b) val > min_min c) runtime error
c) temp->val < min_num d) garbage value
d) temp->val > min_num
Answer: c
Answer: c Explanation: The variable temp will always
Explanation: The line “temp->val = point to the first element in the linked list due
min_num” should be inserted to complete the to the line “temp = head->next” in the while
above code. loop. So, it will be an infinite while loop and
the program will produce a runtime error.
4. What is the output of the following code:
5. What is the output of the following code?
#include<stdio.h>
#include<stdlib.h>
#include<stdio.h>
struct Node
#include<stdlib.h>
{
struct Node
int val;
{
struct Node* next;
int val;
}*head;
struct Node* next;
int get_max()
}*head;
{
int get_max()
struct Node* temp = head->next;
{
int max_num = temp->val;
struct Node* temp = head->next;
while(temp != 0)
int max_num = temp->val;
{
while(temp != 0)
if(temp->val > max_num)
{
max_num = temp->val;
if(temp->val > max_num)
temp = head->next;
max_num = temp->val;
}
temp = temp->next;
return max_num;
}
}
return max_num;

Downloaded From: https://cse-r17.blogspot.com 46


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

} int val;
int get_min() struct Node* next;
{ }*head;
struct Node* temp = head->next; int get_max()
int min_num = temp->val; {
while(temp != 0) struct Node* temp = head->next;
{ int max_num = temp->val;
if(temp->val < min_num) while(temp != 0)
min_num = temp->val; {
temp = temp->next; if(temp->val > max_num)
} max_num = temp->val;
return min_num; temp = temp->next;
} }
int main() return max_num;
{ }
int i, n = 9, arr[9] ={8,3,3,4,5,2, int get_min()
5,6,7}; {
struct Node *temp, *newNode; struct Node* temp = head->next;
head = (struct Node*)malloc(sizeof( int min_num = temp->val;
struct Node)); while(temp != 0)
head -> next =0; {
temp = head; if(temp->val < min_num)
for(i=0;i<n;i++) min_num = temp->val;
{ temp = temp->next;
newNode =(struct Node*)malloc(s }
izeof(struct Node)); return min_num;
newNode->next = 0; }
newNode->val = arr[i]; int main()
temp->next =newNode; {
temp = temp->next; int i, n = 9, arr[9] ={8,3,3,4,5,2,
} 5,6,7};
int max_num = get_max(); struct Node *temp, *newNode;
int min_num = get_min(); head = (struct Node*)malloc(sizeof(
printf("%d %d",max_num,min_num); struct Node));
return 0; head -> next =0;
} temp = head;
for(i=0;i<n;i++)
a) 2 2 {
b) 8 8 newNode =(struct Node*)malloc(s
izeof(struct Node));
c) 2 8 newNode->next = 0;
d) 8 2 newNode->val = arr[i];
temp->next =newNode;
Answer: d temp = temp->next;
Explanation: The program prints the largest }
int max_num = get_max();
and smallest elements in the linked list, which
int min_num = get_min();
are 8 and 2 respectively. printf("%d %d",max_num,min_num);
return 0;
6. What is the time complexity of the }
following iterative code used to find the
smallest and largest element in a linked list? a) O(1)
b) O(n)
#include<stdio.h> c) O(n2)
#include<stdlib.h>
struct Node d) O(n3)
{

Downloaded From: https://cse-r17.blogspot.com 47


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: b return a;
Explanation: The time complexity of the return b;
}
above iterative code used to find the largest int recursive_get_max(struct Node* temp)
and smallest element in a linked list is O(n). {
if(temp->next == 0)
7. Consider the following recursive return temp->val;
implementation to find the largest element in return max_of_two(temp->val,recursi
a linked list: ve_get_max(temp->next));
}
int min_of_two(int a, int b)
struct Node
{
{
if(a < b)
int val;
return a;
struct Node* next;
return b;
}*head;
}
int max_of_two(int a, int b)
int recursive_get_min(struct Node* temp)
{
{
if(a > b)
if(temp->next == 0)
return a;
return temp->val;
return b;
return min_of_two(temp->val,recursi
}
ve_get_min(temp->next));
int recursive_get_max(struct Node* temp)
}
{
int main()
if(temp->next == 0)
{
return temp->val;
int n = 9, arr[9] ={1,3,2,4,5,0,5,6,
return max_of_two(______, _______);
7},i;
}
struct Node *temp, *newNode;
head = (struct Node*)malloc(sizeof(s
Which of the following arguments should be truct Node));
passed to the function max_of two() to head -> next =0;
complete the above code? temp = head;
a) temp->val,recursive_get_max(temp->next) for(i=0;i<n;i++)
{
b) temp, temp->next newNode =(struct Node*)malloc(
c) temp->val, temp->next->val sizeof(struct Node));
d) temp->next->val, temp newNode->next = 0;
newNode->val = arr[i];
Answer: a temp->next =newNode;
Explanation: The arguments {temp- temp = temp->next;
}
>val,recursive_get_max(temp->next)} should int max_num = recursive_get_max(head
be passed to the function max_of_two() to ->next);
complete the above code. int min_num = recursive_get_min(head
->next);
8. What is the output of the following code? printf("%d %d",max_num,min_num);
return 0;
#include<stdio.h> }
#include<stdlib.h>
struct Node a) 7 1
{ b) 0 7
int val; c) 7 0
struct Node* next; d) 1 1
}*head;
int max_of_two(int a, int b)
{ Answer: c
if(a > b) Explanation: The program prints the largest

Downloaded From: https://cse-r17.blogspot.com 48


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

and the smallest elements in the linked list, temp = temp->next;


which are 7 and 0 respectively. }
int max_num = recursive_get_max(head
->next);
9. What is the time complexity of the int min_num = recursive_get_min(head
recursive implementation used to find the ->next);
largest and smallest element in a linked list? printf("%d %d",max_num,min_num);
return 0;
#include<stdio.h> }
#include<stdlib.h>
struct Node a) O(1)
{ b) O(n)
int val;
struct Node* next; c) O(n2)
}*head; d) O(n3)
int max_of_two(int a, int b)
{
if(a > b)
Answer: b
return a; Explanation: The time complexity of the
return b; above recursive implementation used to find
} the largest and smallest element in linked list
int recursive_get_max(struct Node* temp) is O(n).
{
if(temp->next == 0)
return temp->val;
10. What is the output of the following code?
return max_of_two(temp->val,recursi
ve_get_max(temp->next)); #include<stdio.h>
} #include<stdlib.h>
int min_of_two(int a, int b) struct Node
{ {
if(a < b) int val;
return a; struct Node* next;
return b; }*head;
} int min_of_two(int a, int b)
int recursive_get_min(struct Node* temp) {
{ if(a < b)
if(temp->next == 0) return a;
return temp->val; return b;
return min_of_two(temp->val,recursi }
ve_get_min(temp->next)); int recursive_get_min(struct Node* temp)
} {
int main() if(temp->next == 0)
{ return temp->val;
int n = 9, arr[9] ={1,3,2,4,5,0,5,6, return min_of_two(temp->val,recursi
7},i; ve_get_min(temp->next));
struct Node *temp, *newNode; }
head = (struct Node*)malloc(sizeof(s int main()
truct Node)); {
head -> next =0; int n = 5, arr[5] ={1,1,1,1,1},i;
temp = head; struct Node *temp, *newNode;
for(i=0;i<n;i++) head = (struct Node*)malloc(sizeof(s
{ truct Node));
newNode =(struct Node*)malloc( head -> next =0;
sizeof(struct Node)); temp = head;
newNode->next = 0; for(i=0;i<n;i++)
newNode->val = arr[i]; {
temp->next =newNode; newNode =(struct Node*)malloc(

Downloaded From: https://cse-r17.blogspot.com 49


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

sizeof(struct Node)); newNode =(struct Node*)malloc(


newNode->next = 0; sizeof(struct Node));
newNode->val = arr[i]; newNode->next = 0;
temp->next =newNode; newNode->val = arr[i];
temp = temp->next; temp->next =newNode;
} temp = temp->next;
int min_num = recursive_get_min(head }
->next); int min_num = recursive_get_min(head
printf("%d",min_num); ->next);
return 0; printf("%d",min_num);
} return 0;
}
a) 1
b) 0 a) 4
c) compile time error b) 5
d) runtime error c) 6
d) 7
Answer: a
Explanation: The program prints the smallest Answer: b
element in the linked list, which is 1. Explanation: The function
recursive_get_min() will be called 5 times
11. How many times will the function when the above code is executed.
recursive_get_min() be called when the
following code is executed?
1. Which of the following techniques can be
#include<stdio.h> used to search an element in an unsorted
#include<stdlib.h> array?
struct Node
a) Iterative linear search
{
int val; b) Recursive binary search
struct Node* next; c) Iterative binary search
}*head; d) Normal binary search
int min_of_two(int a, int b)
{ Answer: a
if(a < b)
return a;
Explanation: Iterative linear search can be
return b; used to search an element in an unsorted
} array.
int recursive_get_min(struct Node* temp) Note: Binary search can be used only when
{ the array is sorted.
if(temp->next == 0)
return temp->val;
return min_of_two(temp->val,recursi 2. Consider the array {1,1,1,1,1}. Select the
ve_get_min(temp->next)); wrong option?
} a) Iterative linear search can be used to search
int main() for the elements in the given array
{ b) Recursive linear search can be used to
int n = 5, arr[5] ={1,1,1,1,1},i;
struct Node *temp, *newNode; search for the elements in the given array
head = (struct Node*)malloc(sizeof(s c) Recursive binary search can be used to
truct Node)); search for the elements in the given array
head -> next =0; d) No method is defined to search for an
temp = head; element in the given array
for(i=0;i<n;i++)
{

Downloaded From: https://cse-r17.blogspot.com 50


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: d }
Explanation: Iterative linear search, int main()
{
Recursive linear search and Recursive binary int arr[5] ={1,3,3,3,5},num=3,len =
search can be applied to search for an element 5;
in the above given array. int indx = search_num(arr,num,len);
printf("Index of %d is %d",num,indx
3. What does the following code do? );
return 0;
#include<stdio.h> }
int search_num(int *arr, int num, int len
) a) Index of 3 is 0
{ b) Index of 3 is 1
int i; c) Index of 3 is 2
for(i = 0; i < len; i++)
if(arr[i] == num)
d) Index of 3 is 3
return i;
return -1; Answer: b
} Explanation: The program prints the index of
int main() the first occurrence of 3, which is 1.
{
int arr[5] ={1,2,3,4,5},num=3,len = 5. What is the time complexity of the
5;
int indx = search_num(arr,num,len); following code used to search an element in
printf("Index of %d is %d",num,indx an array?
);
return 0; #include<stdio.h>
} int search_num(int *arr, int num, int len
)
a) Search and returns the index of all the {
int i;
occurrences of the number that is searched
for(i = 0; i < len; i++)
b) Search and returns the index of the first if(arr[i] == num)
occurrence of the number that is searched return i;
c) Search and returns of the last occurrence of return -1;
the number that is searched }
int main()
d) Returns the searched element from the
{
given array int arr[5] ={1,3,3,3,5},num=3,len =
5;
Answer: b int indx = search_num(arr,num,len);
Explanation: The code finds the index of the printf("Index of %d is %d",num,indx
first occurrence of the number that is );
return 0;
searched. }

4. What is the output of the following code? a) O(1)


b) O(n)
#include<stdio.h>
int search_num(int *arr, int num, int len c) O(n2)
) d) O(n3)
{
int i;
for(i = 0; i < len; i++) Answer: b
if(arr[i] == num) Explanation: The time complexity of the
return i;
return -1;

Downloaded From: https://cse-r17.blogspot.com 51


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

above code used to search an element in an , idx+1, len);


array is O(n). }
int main()
{
6. Consider the following recursive int arr[8] ={1,2,3,3,3,5,6,7},num=5
implementation of linear search: ,len = 8;
int indx = recursive_search_num(arr
#include<stdio.h> ,num,0,len);
int recursive_search_num(int *arr, int nu printf("Index of %d is %d",num,indx
m, int idx, int len) );
{ return 0;
if(idx == len) }
return -1;
if(arr[idx] == num) a) Index of 5 is 5
return idx;
b) Index of 5 is 6
return __________;
} c) Index of 5 is 7
int main() d) Index of 5 is 8
{
int arr[5] ={1,3,3,3,5},num=2,len = Answer: a
5; Explanation: The program prints the index of
int indx = recursive_search_num(arr
,num,0,len);
5, which is 5.
printf("Index of %d is %d",num,indx
); 8. How many times is the function
return 0; recursive_search_num() called when the
} following code is executed?
Which of the following recursive calls should #include<stdio.h>
be added to complete the above code? int recursive_search_num(int *arr, int nu
a) recursive_search_num(arr, num+1, idx, m, int idx, int len)
{
len);
if(idx == len)
b) recursive_search_num(arr, num, idx, len); return -1;
c) recursive_search_num(arr, num, idx+1, if(arr[idx] == num)
len); return idx;
d) recursive_search_num(arr, num+1, idx+1, return recursive_search_num(arr, num
, idx+1, len);
len); }
int main()
Answer: c {
Explanation: The recursive call int arr[8] ={1,2,3,3,3,5,6,7},num=5
“recursive_search_num(arr, num, idx+1, len)” ,len = 8;
should be added to complete the above code. int indx = recursive_search_num(arr
,num,0,len);
printf("Index of %d is %d",num,indx
7. What is the output of the following code? );
return 0;
#include<stdio.h> }
int recursive_search_num(int *arr, int nu
m, int idx, int len)
a) 5
{
if(idx == len) b) 6
return -1; c) 7
if(arr[idx] == num) d) 8
return idx;
return recursive_search_num(arr, num

Downloaded From: https://cse-r17.blogspot.com 52


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: b , idx+1, len);


Explanation: The function }
int main()
recursive_search_num() is called 6 times {
when the above code is executed. int arr[8] ={-11,2,-3,0,3,5,-6,7},n
um = -2,len = 8;
9. What is the time complexity of the int indx = recursive_search_num(arr
following recursive implementation of linear ,num,0,len);
search? printf("Index of %d is %d",num,indx
);
return 0;
#include<stdio.h>
}
int recursive_search_num(int *arr, int nu
m, int idx, int len)
{ a) Index of -2 is 1
if(idx == len) b) Index of -2 is 0
return -1; c) Index of -2 is -1
if(arr[idx] == num) d) None of the mentioned
return idx;
return recursive_search_num(arr, num
, idx+1, len);
Answer: c
} Explanation: The program prints the index of
int main() the first occurrence of -2. Since, -2 doesn’t
{ exist in the array, the program prints -1.
int arr[8] ={1,2,3,3,3,5,6,7},num=5
,len = 8; 2. What does the following code do?
int indx = recursive_search_num(arr
,num,0,len);
#include<stdio.h>
printf("Index of %d is %d",num,indx
int cnt = 0;
);
int recursive_search_num(int *arr, int nu
return 0;
m, int idx, int len)
}
{
int cnt = 0;
a) O(1) if(idx == len)
b) O(n) return cnt;
c) O(n2) if(arr[idx] == num)
cnt++;
d) O(n3) return cnt + recursive_search_num(a
rr, num, idx+1, len);
Answer: b }
Explanation: The time complexity of the int main()
{
above recursive implementation of linear int arr[8] ={0,0,0,0,3,5,-6,7},num
search is O(n). = 0,len = 8;
int ans = recursive_search_num(arr,
num,0,len);
1. What is the output of the following code? printf("%d",ans);
return 0;
#include<stdio.h> }
int recursive_search_num(int *arr, int nu
m, int idx, int len) a) Adds all the indexes of the number 0
{ b) Finds the first last occurrence of the
if(idx == len) number 0
return -1;
if(arr[idx] == num)
c) Counts the number of occurrences of the
return idx; number 0
return recursive_search_num(arr, num d) None of the mentioned

Downloaded From: https://cse-r17.blogspot.com 53


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: c if(arr[mid] == num)


Explanation: The above code counts the return mid;
else if(arr[mid] < num)
number of occurrences of the number 0. lo = mid + 1;
else
3. Consider the following recursive hi = mid - 1;
implementation of the binary search: return recursive_binary_search(arr,
num, lo, hi);
#include<stdio.h> }
int recursive_binary_search(int *arr, int int main()
num, int lo, int hi) {
{ int arr[8] = {1,2,3,4,5,6,7,8},num
if(lo > hi) = 7,len = 8;
return -1; int indx = recursive_binary_search(
int mid = (lo + hi)/2; arr,num,0,len-1);
if(arr[mid] == num) printf("Index of %d is %d",num,indx
return mid; );
else if(arr[mid] < num) return 0;
__________; }
else
hi = mid - 1; a) Index of 7 is 4
return recursive_binary_search(arr, b) Index of 7 is 5
num, lo, hi);
c) Index of 7 is 6
}
int main() d) Index of 7 is 7
{
int arr[8] ={0,0,0,0,3,5,6,7},num = Answer: c
7,len = 8; Explanation: The program prints the index of
int indx = recursive_binary_search( number 7, which is 6.
arr,num,0,len-1);
printf("Index of %d is %d",num,indx
); 5. What is the output of the following code?
return 0;
} #include<stdio.h>
int recursive_binary_search(int *arr, int
num, int lo, int hi)
Which of the following lines should be added
{
to complete the above code? if(lo > hi)
a) hi = mid – 1 return -1;
b) mid = (lo + hi)/2 int mid = (lo + hi)/2;
c) mid = lo – 1 if(arr[mid] == num)
return mid;
d) lo = mid + 1
else if(arr[mid] < num)
lo = mid + 1;
Answer: d else
Explanation: The line “lo = mid + 1” should hi = mid - 1;
be added to complete the above code. return recursive_binary_search(arr,
num, lo, hi);
4. What is the output of the following code? }
int main()
{
#include<stdio.h>
int arr[8] = {0,0,0,0,3,5,6,7},num
int recursive_binary_search(int *arr, int
= 0,len = 8;
num, int lo, int hi)
int indx = recursive_binary_search(
{
arr,num,0,len-1);
if(lo > hi)
printf("Index of %d is %d",num,indx
return -1;
);
int mid = (lo + hi)/2;

Downloaded From: https://cse-r17.blogspot.com 54


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

return 0; c) Array: {5,4,3,2,1} Search: 1


} d) Array: {-5,-4,-3,-2,-1} Search: -1
a) Index of 0 is 0 Answer: c
b) Index of 0 is 1 Explanation: Since the array {5,4,3,2,1} is
c) Index of 0 is 2 sorted in descending order, it will produce a
d) Index of 0 is 3 wrong output.
Answer: d 8. How many times is the function
Explanation: In this case, when the function recursive_binary_search() called when the
recursive_binary_search() is called for the following code is executed?
first time we have: lo = 0 and hi = 7. So, the
value of mid is: #include<stdio.h>
mid = (lo + hi)/2 = (0 + 7)/2 = 3. Since, int recursive_binary_search(int *arr, int
arr[mid] = arr[3] = 0, the function returns the num, int lo, int hi)
{
value of mid, which is 3.
if(lo > hi)
return -1;
6. What is the time complexity of the above int mid = (lo + hi)/2;
recursive implementation of binary search? if(arr[mid] == num)
a) O(n) return mid;
else if(arr[mid] < num)
b) O(2n) lo = mid + 1;
c) O(logn) else
d) O(n!) hi = mid - 1;
return recursive_binary_search(arr,
Answer: c num, lo, hi);
}
Explanation: The time complexity of the
int main()
above recursive implementation of binary {
search is O(logn). int arr[5] = {1,2,3,4,5},num = 1,le
n = 5;
7. In which of the below cases will the int indx = recursive_binary_search(
following code produce a wrong output? arr,num,0,len-1);
printf("Index of %d is %d",num,indx
);
int recursive_binary_search(int *arr, int
return 0;
num, int lo, int hi)
}
{
if(lo > hi)
return -1; a) 0
int mid = (lo + hi)/2; b) 1
if(arr[mid] == num) c) 2
return mid; d) 3
else if(arr[mid] < num)
lo = mid + 1;
else Answer: c
hi = mid - 1; Explanation: The function
return recursive_binary_search(arr, recursive_binary_search() is called 2 times,
num, lo, hi); when the above code is executed.
}
9. What is the output of the following code?
a) Array: {0,0,0,0,0,0} Search: -10
b) Array: {1,2,3,4,5} Search: 0 #include<stdio.h>
int recursive_binary_search(int *arr, int

Downloaded From: https://cse-r17.blogspot.com 55


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

num, int lo, int hi) 2. Consider the following code snippet to
{ search an element in a linked list:
if(lo > hi)
return -1;
struct Node
int mid = (lo + hi)/2;
{
if(arr[mid] == num)
int val;
return mid;
struct Node* next;
else if(arr[mid] < num)
}*head;
lo = mid + 1;
int linear_search(int value)
else
{
hi = mid - 1;
struct Node *temp = head->next;
return recursive_binary_search(arr,
while(temp != 0)
num, lo, hi);
{
}
if(temp->val == value)
int main()
return 1;
{
_________;
int arr[5] = {5,4,3,2,1},num = 1,le
}
n = 5;
return 0;
int indx = recursive_binary_search(
}
arr,num,0,len-1);
printf("Index of %d is %d",num,indx
); Which of the following lines should be
return 0; inserted to complete the above code?
} a) temp = next
b) temp->next = temp
a) Index of 1 is 4 c) temp = temp->next
b) Index of 1 is 5 d) return 0
c) Index of 1 is -1
d) Index of 1 is 0 Answer: c
Explanation: The line “temp = temp->next”
Answer: c should be inserted to complete the above
Explanation: Since the array is sorted in code.
descending order, the above implementation
of binary search will not work for the given 3. What does the following code do?
array. Even though 1 is present in the array,
binary search won’t be able to search it and it #include<stdio.h>
will produce -1 as an answer. #include<stdlib.h>
struct Node
{
int val;
1. Which of the following methods can be struct Node* next;
used to search an element in a linked list? }*head;
a) Iterative linear search int linear_search(int value)
b) Iterative binary search {
struct Node *temp = head->next;
c) Recursive binary search while(temp != 0)
d) Normal binary search {
if(temp->val == value)
Answer: a return 1;
Explanation: Iterative linear search can be temp = temp->next;
}
used to search an element in a linked list. return 0;
Binary search can be used only when the list }
is sorted. int main()
{

Downloaded From: https://cse-r17.blogspot.com 56


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

int arr[5] = {1,2,3,4,5}; }


int n = 5,i; return 0;
head = (struct Node*)malloc(sizeof( }
struct Node)); int main()
head->next = 0; {
struct Node *temp; int arr[5] = {1,2,3,4,5};
temp = head; int n = 5,i;
for(i=0; i<n; i++) head = (struct Node*)malloc(sizeof(s
{ truct Node));
struct Node *newNode = (struct head->next = 0;
Node*)malloc(sizeof(struct Node)); struct Node *temp;
newNode->next = 0; temp = head;
newNode->val = arr[i]; for(i=0; i<n; i++)
temp->next = newNode; {
temp = temp->next; struct Node *newNode = (struct
} Node*)malloc(sizeof(struct Node));
int ans = linear_search(60); newNode->next = 0;
if(ans == 1) newNode->val = arr[i];
printf("Found"); temp->next = newNode;
else temp = temp->next;
printf("Not found"); }
return 0; int ans = linear_search(-1);
} if(ans == 1)
printf("Found");
a) Finds the index of the first occurrence of a else
number in a linked list printf("Not found");
return 0;
b) Finds the index of the last occurrence of a }
number in a linked list
c) Checks if a number is present in a linked a) Found
list b) Not found
d) Checks whether the given list is sorted or c) Compile time error
not d) Runtime error
Answer: c Answer: b
Explanation: The above code checks if a Explanation: Since the number -1 is not
number is present in a linked list. present in the linked list, the program prints
not found.
4. What is the output of the following code?
5. What is the time complexity of the
#include<stdio.h>
#include<stdlib.h>
following implementation of linear search on
struct Node a linked list?
{
int val; #include<stdio.h>
struct Node* next; #include<stdlib.h>
}*head; struct Node
int linear_search(int value) {
{ int val;
struct Node *temp = head->next; struct Node* next;
while(temp != 0) }*head;
{ int linear_search(int value)
if(temp->val == value) {
return 1; struct Node *temp = head->next;
temp = temp->next; while(temp != 0)
{

Downloaded From: https://cse-r17.blogspot.com 57


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

if(temp->val == value) while(temp -> next != 0)


return 1; {
temp = temp->next; if(temp->val == value)
} return 1;
return 0; temp = temp->next;
} }
int main() return 0;
{ }
int arr[5] = {1,2,3,4,5}; int main()
int n = 5,i; {
head = (struct Node*)malloc(sizeof(s int arr[6] = {1,2,3,4,5,6};
truct Node)); int n = 6,i;
head->next = 0; head = (struct Node*)malloc(sizeof(s
struct Node *temp; truct Node));
temp = head; head->next = 0;
for(i=0; i<n; i++) struct Node *temp;
{ temp = head;
struct Node *newNode = (struct for(i=0; i<n; i++)
Node*)malloc(sizeof(struct Node)); {
newNode->next = 0; struct Node *newNode = (struct
newNode->val = arr[i]; Node*)malloc(sizeof(struct Node));
temp->next = newNode; newNode->next = 0;
temp = temp->next; newNode->val = arr[i];
} temp->next = newNode;
int ans = linear_search(-1); temp = temp->next;
if(ans == 1) }
printf("Found"); int ans = linear_search(60);
else if(ans == 1)
printf("Not found"); printf("Found");
return 0; else
} printf("Not found");
return 0;
a) O(1) }
b) O(n)
a) Found
c) O(n2)
b) Not found
d) O(n3) c) Compile time error
d) Runtime error
Answer: b
Explanation: The time complexity of the Answer: b
above implementation of linear search on a Explanation: The condition in the while loop
linked list is O(n). “temp->next == 0”, checks if the current
element is the last element. If the current
6. What is the output of the following code? element is the last element, the value of the
#include<stdio.h>
current element is not compared with the
#include<stdlib.h> value to be searched. So, even though the
struct Node number 6 is present in the linked list, it will
{ print not found.
int val;
struct Node* next; 7. Can binary search be applied on a sorted
}*head;
int linear_search(int value)
linked list in O(Logn) time?
{ a) No
struct Node *temp = head->next; b) Yes

Downloaded From: https://cse-r17.blogspot.com 58


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: a #include<stdio.h>
Explanation: Since linked list doesn’t allow #include<stdlib.h>
struct Node
random access, binary search cannot be {
applied on a sorted linked list in O(Logn) int val;
time. struct Node* next;
}*head;
8. What will be time complexity when binary int linear_search(struct Node *temp,int v
search is applied on a linked list? alue)
{
a) O(1) if(temp == 0)
b) O(n) return 0;
c) O(n2) if(temp->val == value)
return 1;
d) O(n3) return linear_search(temp->next, va
lue);
Answer: b }
Explanation: The time complexity will be int main()
O(n) when binary search is applied on a {
int arr[6] = {1,2,3,4,5,6};
linked list. int n = 6,i;
head = (struct Node*)malloc(sizeof(s
9. Consider the following recursive truct Node));
implementation of linear search on a linked head->next = 0;
list: struct Node *temp;
temp = head;
struct Node for(i=0; i<n; i++)
{ {
int val; struct Node *newNode = (struct
struct Node* next; Node*)malloc(sizeof(struct Node));
}*head; newNode->next = 0;
int linear_search(struct Node *temp,int v newNode->val = arr[i];
alue) temp->next = newNode;
{ temp = temp->next;
if(temp == 0) }
return 0; int ans = linear_search(head->next,6
if(temp->val == value) );
return 1; if(ans == 1)
return _________; printf("Found");
} else
printf("Not found");
return 0;
Which of the following lines should be }
inserted to complete the above code?
a) 1 a) Found
b) 0 b) Not found
c) linear_search(temp, value) c) Compile time error
d) linear_search(temp->next, value) d) Runtime error
Answer: d Answer: a
Explanation: The line “linear_search(temp- Explanation: Since the element 6 is present
>next, value)”, should be inserted to complete in the linked list, the program prints “Found”.
the above code.
11. How many times is the function
10. What is the output of the following code? linear_search() called when the following

Downloaded From: https://cse-r17.blogspot.com 59


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

code is executed? 12. What is the time complexity of the


following recursive implementation of linear
#include<stdio.h> search?
#include<stdlib.h>
struct Node #include<stdio.h>
{ #include<stdlib.h>
int val; struct Node
struct Node* next; {
}*head; int val;
int linear_search(struct Node *temp,int v struct Node* next;
alue) }*head;
{ int linear_search(struct Node *temp,int v
if(temp == 0) alue)
return 0; {
if(temp->val == value) if(temp == 0)
return 1; return 0;
return linear_search(temp->next, va if(temp->val == value)
lue); return 1;
} return linear_search(temp->next, va
int main() lue);
{ }
int arr[6] = {1,2,3,4,5,6}; int main()
int n = 6,i; {
head = (struct Node*)malloc(sizeof(s int arr[6] = {1,2,3,4,5,6};
truct Node)); int n = 6,i;
head->next = 0; head = (struct Node*)malloc(sizeof(s
struct Node *temp; truct Node));
temp = head; head->next = 0;
for(i=0; i<n; i++) struct Node *temp;
{ temp = head;
struct Node *newNode = (struct for(i=0; i<n; i++)
Node*)malloc(sizeof(struct Node)); {
newNode->next = 0; struct Node *newNode = (struct
newNode->val = arr[i]; Node*)malloc(sizeof(struct Node));
temp->next = newNode; newNode->next = 0;
temp = temp->next; newNode->val = arr[i];
} temp->next = newNode;
int ans = linear_search(head->next,6 temp = temp->next;
); }
if(ans == 1) int ans = linear_search(head->next,6
printf("Found"); );
else if(ans == 1)
printf("Not found"); printf("Found");
return 0; else
} printf("Not found");
return 0;
a) 5 }
b) 6
c) 7 a) O(1)
d) 8 b) O(n)
c) O(n2)
Answer: b
Explanation: The function linear_search() is d) O(n3)
called 6 times when the above code is
executed.

Downloaded From: https://cse-r17.blogspot.com 60


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: b wer(x, y/2);


Explanation: The time complexity of the }
int main()
above recursive implementation of linear {
search is O(n). int x = 2;
int y = 3;

1. What will be the output for following printf("%d", power(x, y));


code? return 0;
}

M
#include<stdio.h>
int func(int x, int y) a) O(n)
b) O(log n)

O
{
if (y == 0) c) O(n log n)
return 1;
d) O(n2)

C
else if (y%2 == 0)
return func(x, y/2)*func(

T.
x, y/2); Answer: a
else Explanation: The recurrence relation for the
return x*func(x, y/2)*fun above code is given by T(n)=2T(n/2)+c. By

O
c(x, y/2); using master theorem we can calculate the
}
result for this relation. It is found to be equal
int main()
{
int x = 2;
int y = 3;
SP
to O(n).

3. What is the space complexity of the given


G
code?
printf("%d", func(x, y));
return 0;
LO

#include<stdio.h>
} int power(int x, int y)
{
a) 9 if (y == 0)
b) 6 return 1;
.B

c) 8 else if (y%2 == 0)
d) 5 return power(x, y/2)*powe
r(x, y/2);
17

else
Answer: c return x*power(x, y/2)*po
Explanation: The given program calculates wer(x, y/2);
the value of x raised to power y. Thus 23 = 8. }
-R

int main()
{
2. What will be the time complexity of the int x = 2;
SE

following code which raises an integer x to int y = 3;


the power y?
printf("%d", power(x, y));
#include<stdio.h> return 0;
C

int power(int x, int y) }


{
if (y == 0) a) O(1)
return 1; b) O(n)
else if (y%2 == 0)
c) O(log n)
return power(x, y/2)*powe
r(x, y/2); d) O(n log n)
else
return x*power(x, y/2)*po

Downloaded From: https://cse-r17.blogspot.com 61


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: a int y = 3;
Explanation: The space complexity of the
printf("%d", power(x, y));
given code will be equal to O(1) as it uses return 0;
only constant space in the memory. }

4. Recursive program to raise an integer x to a) O(1)


power y uses which of the following b) O(n)
algorithm? c) O(log n)
a) Dynamic programming d) O(n log n)
b) Backtracking
c) Divide and conquer Answer: c
d) Greedy algorithm Explanation: The given code is the optimized
version for finding the power of a number. It
Answer: c forms a recurrence relation given by
Explanation: The recursive approach uses T(n)=T(n/2)+c which can be solved using
divide and conquer algorithm as we break the master theorem. It is calculated to be equal to
problem into smaller parts and then solve the O(log n).
smaller parts and finally combine their results
to get the overall solution. 7. What is the advantage of iterative code for
finding power of number over recursive
5. What is the least time in which we can code?
raise a number x to power y? a) Iterative code requires less time
a) O(x) b) Iterative code requires less space
b) O(y) c) Iterative code is more compiler friendly
c) O(log x) d) It has no advantage
d) O(log y)
Answer: b
Answer: d Explanation: Both iterative and recursive
Explanation: We can optimize the code for approach can be implemented in log n time
finding power of a number by calculating x but the recursive code requires memory in
raised to power y/2 only once and using it call stack which makes it less preferable.
depending on whether y is even or odd.
8. Which of the following correctly
6. What will be the time complexity of the implements iterative code for finding power
following code? of a number?
a)
#include<stdio.h>
int power(int x, int y) #include <stdio.h>
{ int power(int x, int y)
int temp; {
if( y == 0) int res = 1;
return 1; while (y > 0)
temp = power(x, y/2); {
if (y%2 == 0)
return temp*temp; if (y & 1)
else res = res * x;
return x*temp*temp; y = y >> 1;
} x = x * x;
int main() }
{ return res;
int x = 2;

Downloaded From: https://cse-r17.blogspot.com 62


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

} d)
int main()
{ #include <stdio.h>
int x = 3; int power(int x, int y)
unsigned int y = 5; {
printf("%d", power(x, y)); int res = 1;
return 0; while (y > 0)
} {
if (y & 1)
b) res = x * x;
y = y >> 1;
#include <stdio.h> x = x * y;
int power(int x, int y) }
{ return res;
int res = 1; }
while (y > 0) int main()
{ {
int x = 3;
if (y && 1) unsigned int y = 5;
res = res * x; printf("%d", power(x, y));
y = y >> 1; return 0;
x = x * x; }
}
return res; Answer: a
} Explanation: It represents the iterative
int main() version of required code. It has a time and
{
int x = 3;
space complexity of O(log n) and O(1)
unsigned int y = 5; respectively.
printf("%d", power(x, y));
return 0;
}
9. Recursive approach to find power of a
c) number is preferred over iterative approach.
a) True
#include <stdio.h>
int power(int x, int y) b) False
{
int res = 1; Answer: b
while (y > 0) Explanation: The recursive code requires
{ memory in call stack which makes it less
if (y && 1)
res = x * x;
preferable as compared to iterative approach.
y = y >> 1;
x = x * y; 10. What will be the output for following
} code?
return res;
} float power(float x, int y)
int main() {
{ float temp;
int x = 3; if( y==0)
unsigned int y = 5; return 1;
printf("%d", power(x, y)); temp = power(x, y/2);
return 0; if (y%2 == 0)
} return temp*temp;
else

Downloaded From: https://cse-r17.blogspot.com 63


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

{ 2. Which of the following is NOT a rule of


if(y > 0) tower of hanoi puzzle?
return x*temp*tem
p;
a) No disk should be placed over a smaller
else disk
return (temp*temp b) Disk can only be moved if it is the
)/x; uppermost disk of the stack
} c) No disk should be placed over a larger disk
}
int main()
d) Only one disk can be moved at a time
{
float x = 2; Answer: c
int y = -3; Explanation: The rule is to not put a disk
printf("%f", power(x, y)); over a smaller one. Putting a smaller disk
return 0; over larger one is allowed.
}

a) Error 3. The time complexity of the solution tower


of hanoi problem using recursion is
b) 1/4
_________
c) 4
d) 0.25 a) O(n2)
b) O(2n)
Answer: d c) O(n log n)
Explanation: The given code is capable of d) O(n)
handling negative powers too. Thus, the
output will be 2-2 = 0.25. Answer: b
Explanation: Time complexity of the
Sanfoundry Global Education & Learning problem can be found out by solving the
Series – Data Structures & Algorithms. recurrence relation: T(n)=2T(n-1)+c. Result
of this relation is found to be equal to 2n. It
can be solved using substitution.
1. What is the objective of tower of hanoi
puzzle? 4. Recurrence equation formed for the tower
a) To move all disks to some other rod by of hanoi problem is given by _________
following rules a) T(n) = 2T(n-1)+n
b) To divide the disks equally among the b) T(n) = 2T(n/2)+c
three rods by following rules c) T(n) = 2T(n-1)+c
c) To move all disks to some other rod in d) T(n) = 2T(n/2)+n
random order
d) To divide the disks equally among three Answer: c
rods in random order Explanation: As there are 2 recursive calls to
n-1 disks and one constant time operation so
Answer: a the recurrence relation will be given by T(n)
Explanation: Objective of tower of hanoi = 2T(n-1)+c.
problem is to move all disks to some other
rod by following the following rules-1) Only 5. Minimum number of moves required to
one disk can be moved at a time. 2) Disk can solve a tower of hanoi problem with n disks is
only be moved if it is the uppermost disk of __________
the stack. 3) No disk should be placed over a a) 2n
smaller disk.
b) 2n-1

Downloaded From: https://cse-r17.blogspot.com 64


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

c) n2 }
}
d) n2-1
c)
Answer: b
Explanation: Minimum number of moves void ToH(int n,int a,int b,int c)
can be calculated by solving the recurrence {
relation – T(n)=2T(n-1)+c. Alternatively we If(n>0)
{
can observe the pattern formed by the series ToH(n-1,a,c,b);
of number of moves 1,3,7,15…..Either way it cout<<”move a disk from” <<a<<”
turn out to be equal to 2n-1. to”<< c;
ToH(n-1,a,b,c);
}
6. Space complexity of recursive solution of }
tower of hanoi puzzle is ________
a) O(1) d)
b) O(n)
c) O(log n) void ToH(int n,int a,int b,int c)
d) O(n log n) {
If(n>0)
{
Answer: b
ToH(n-1,b,a,c);
Explanation: Space complexity of tower of cout<<”move a disk from” <<a<<” t
hanoi problem can be found out by solving o”<< c;
the recurrence relation T(n)=T(n-1)+c. Result ToH(n-1,a,c,b);
of this relation is found out to be n. It can be }
}
solved using substitution.
Answer: a
7. Which of the following functions correctly Explanation: The first recursive call moves
represent the solution to tower of hanoi n-1 disks from a to b using c. Then we move
puzzle? a disk from a to c. Finally the second
a) recursive call moves n-1 disks from b to c
void ToH(int n,int a,int b,int c)
using a.
{
If(n>0)
{
ToH(n-1,a,c,b); 8. Recursive solution of tower of hanoi
cout<<”move a disk from” <<a<<” t problem is an example of which of the
o”<< c;
ToH(n-1,b,a,c); following algorithm?
} a) Dynamic programming
} b) Backtracking
c) Greedy algorithm
b) d) Divide and conquer
void ToH(int n,int a,int b,int c Answer: d
{
If(n>0)
Explanation: The recursive approach uses
{ divide and conquer algorithm as we break the
ToH(n-1,a,b,c); problem into smaller parts and then solve the
cout<<”move a disk from” <<a<<” t smaller parts and finally combine their results
o”<< c; to get the overall solution.
ToH(n-1,b,a,c);

Downloaded From: https://cse-r17.blogspot.com 65


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

9. Tower of hanoi problem can be solved Answer: b


iteratively. Explanation: There are primarily 3 cases
a) True under master’s theorem. We can solve any
b) False recurrence that falls under any one of these
three cases.
Answer: a
Explanation: Iterative solution to tower of 3. What is the result of the recurrences which
hanoi puzzle also exists. Its approach depends fall under first case of Master’s theorem (let
on whether the total numbers of disks are the recurrence be given by T(n)=aT(n/b)+f(n)
even or odd. and f(n)=nc?
a) T(n) = O(n^logba)
10. Minimum time required to solve tower of
hanoi puzzle with 4 disks assuming one move b) T(n) = O(nc log n)
takes 2 seconds, will be __________ c) T(n) = O(f(n))
a) 15 seconds d) T(n) = O(n2)
b) 30 seconds
c) 16 seconds Answer: a
d) 32 seconds Explanation: In first case of master’s
theorem the necessary condition is that c <
Answer: b logba. If this condition is true then T(n) =
Explanation: Number of moves = 24-1=16- O(n^logba).
1=15
Time for 1 move = 2 seconds 4. What is the result of the recurrences which
Time for 15 moves = 15×2 = 30 seconds. fall under second case of Master’s theorem
(let the recurrence be given by
Sanfoundry Global Education & Learning
T(n)=aT(n/b)+f(n) and f(n)=nc?
Series – Data Structures & Algorithms.
a) T(n) = O(nlogba)
b) T(n) = O(nc log n)
1. Master’s theorem is used for? c) T(n) = O(f(n))
a) solving recurrences d) T(n) = O(n2)
b) solving iterative relations
c) analysing loops Answer: b
d) calculating the time complexity of any Explanation: In second case of master’s
code theorem the necessary condition is that c =
logba. If this condition is true then T(n) =
Answer: a
Explanation: Master’s theorem is a direct O(nc log n)
method for solving recurrences. We can solve
any recurrence that falls under any one of the 5. What is the result of the recurrences which
three cases of master’s theorem. fall under third case of Master’s theorem (let
the recurrence be given by T(n)=aT(n/b)+f(n)
2. How many cases are there under Master’s and f(n)=nc?
theorem? b) T(n) = O(nlogba)
a) 2 b) T(n) = O(nc log n)
b) 3 c) T(n) = O(f(n))
c) 4
d) T(n) = O(n2)
d) 5

Downloaded From: https://cse-r17.blogspot.com 66


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: c c) 3
Explanation: In third case of master’s d) No case can be extended
theorem the necessary condition is that c >
logba. If this condition is true then T(n) = Answer: b
O(f(n)). Explanation: The second case of master’s
theorem can be extended for a case where f(n)
6. We can solve any recurrence by using = nc (log n)k and the resulting recurrence
Master’s theorem. becomes T(n)= O(nc (log n))k+1.
a) true
b) false 10. What is the result of the recurrences
which fall under the extended second case of
Answer: b Master’s theorem (let the recurrence be given
Explanation: No we cannot solve all the by T(n)=aT(n/b)+f(n) and f(n)=nc(log n)k?
recurrences by only using master’s theorem. a) T(n) = O(nlogba)
We can solve only those which fall under the
three cases prescribed in the theorem. b) T(n) = O(nc log n)
c) T(n)= O(nc (log n)k+1
7. Under what case of Master’s theorem will
d) T(n) = O(n2)
the recurrence relation of merge sort fall?
a) 1 Answer: c
b) 2 Explanation: In the extended second case of
c) 3 master’s theorem the necessary condition is
d) It cannot be solved using master’s theorem that c = logba. If this condition is true then
Answer: b T(n)= O(nc(log n))k+1.
Explanation: The recurrence relation of
merge sort is given by T(n) = 2T(n/2) + O(n). 11. Under what case of Master’s theorem will
So we can observe that c = Logba so it will the recurrence relation of binary search fall?
a) 1
fall under case 2 of master’s theorem.
b) 2
8. Under what case of Master’s theorem will c) 3
the recurrence relation of stooge sort fall? d) It cannot be solved using master’s theorem
a) 1
Answer: b
b) 2
Explanation: The recurrence relation of
c) 3
binary search is given by T(n) = T(n/2) +
d) It cannot be solved using master’s theorem
O(1). So we can observe that c = Logba so it
Answer: a will fall under case 2 of master’s theorem.
Explanation: The recurrence relation of
stooge sort is given as T(n) = 3T(2/3n) +
1. Solve the following recurrence using
O(1). It is found too be equal to O(n2.7) using
Master’s theorem.
master’s theorem first case.
T(n) = 4T (n/2) + n2
9. Which case of master’s theorem can be a) T(n) = O(n)
extended further? b) T(n) = O(log n)
a) 1 c) T(n) = O(n2log n)
b) 2 d) T(n) = O(n2)

Downloaded From: https://cse-r17.blogspot.com 67


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: c solved by using the Master’s theorem. It is


Explanation: The given recurrence can be because this recurrence relation does not fit
solved by using the second case of Master’s into any case of Master’s theorem.
theorem.
T(n) = O(nc log n) = Here nc = n2 5. Solve the following recurrence using
Master’s theorem.
So the solution becomes T(n) = O(n2log n). T(n) = 0.7 T (n/2) + 1/n
a) T(n) = O(n)
2. Solve the following recurrence using
b) T(n) = O(log n)
Master’s theorem.
T(n) = T (n/2) + 2n c) T(n) = O(n2log n)
d) cannot be solved using master’s theorem
a) T(n) = O(n2)
b) T(n) = O(n2 log n) Answer: d
c) T(n) = O(2n) Explanation: The given recurrence cannot be
d) cannot be solved solved by using the Master’s theorem. It is
because in this recurrence relation a < 1 so
Answer: c master’s theorem cannot be applied.
Explanation: The given recurrence can be
solved by using the third case (as f(n) > 6. Solve the following recurrence using
log21) of Master’s theorem. Master’s theorem.
T(n) = O(f(n)) = Here f(n) = 2n. T(n) = 4 T (n/2) + n!
So the solution becomes T(n) = O(2n). a) T(n) = O(n!)
b) T(n) = O(n! log n)
3. Solve the following recurrence using c) T(n) = O(n2log n)
Master’s theorem. d) cannot be solved using master’s theorem
T(n) = 16T (n/4) + n
a) T(n) = O(n) Answer: a
b) T(n) = O(log n) Explanation: The given recurrence can be
c) T(n) = O(n2log n) solved by using the third case of Master’s
theorem. So the solution becomes T(n) =
d) T(n) = O(n2)
O(n!).
Answer: d
Explanation: The given recurrence can be 7. Solve the following recurrence using
solved by using the first case of Master’s Master’s theorem.
theorem. So the solution becomes T(n) = T(n) = 4T (n/4) + n log n
a) T(n) = O(n (log n)2)
O(n2).
b) T(n) = O(n log n)
4. Solve the following recurrence using c) T(n) = O(n2log n)
Master’s theorem. d) cannot be solved using master’s theorem
T(n) = 2T (n/2) + n/ log n
a) T(n) = O(n) Answer: a
b) T(n) = O(log n) Explanation: The given recurrence can be
solved by using the extended second case of
c) T(n) = O(n2log n)
Master’s theorem. So the solution becomes
d) cannot be solved using master’s theorem
T(n) = O(n (log n)2).
Answer: d
Explanation: The given recurrence cannot be

Downloaded From: https://cse-r17.blogspot.com 68


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

8. What will be the recurrence relation of the int xpowy(int x, int n)


following code? {
if (n==0)
return 1;
Int sum(int n)
if (n==1)
{
return x;
If(n==1)
if ((n % 2) == 0)
return 1;
return xpowy(x*x, n/2);
else
else
return n+sum(n-1);
return xpowy(x*x, n/2) * x;
}
}
a) T(n) = T(n/2) + n a) O(log n)
b) T(n) = T(n-1) + n b) O(n)
c) T(n) = T(n-1) + O(1) c) O(n log n)
d) T(n) = T(n/2) + O(1)
d) O(n2)
Answer: c
Explanation: As after every recursive call the Answer: a
integer up to which the sum is to be Explanation: As the recurrence relation of
calculated decreases by 1. So the recurrence the code is given by T(n) = T(n/2) + O(1) so
relation for the given code will be T(n) = T(n- it can be solved by using master’s theorem
1) + O(1). second case.

9. What will be the recurrence relation of the


following code?

int xpowy(int x, int n)


if (n==0) return 1; UNIT II BRUTE FORCE
if (n==1) return x;
if ((n % 2) == 0)
AND DIVIDE-AND-
return xpowy(x*x, n/2); CONQUER
else
return xpowy(x*x, n/2) * x;
1. Which of the following is a sub string of
a) T(n) = T(n/2) + n “SANFOUNDRY”?
b) T(n) = T(n-1) + n a) SANO
c) T(n) = T(n-1) + O(1) b) FOUND
d) T(n) = T(n/2) + O(1) c) SAND
d) FOND
Answer: d
Explanation: As after every recursive call the Answer: b
integer up to which the power is to be Explanation: A sub string is a subset of
calculated decreases by half. So the another string. So “FOUND” is the only
recurrence relation for the given code will be possible sub string out of the given options.
T(n) = T(n/2) + O(1). It can be solved by
using master’s theorem. 2. What will be the output of the following
code?
10. What will be the time complexity of the
following code? #include<bits/stdc++.h>
using namespace std;

void func(char* str2, char* str1)

Downloaded From: https://cse-r17.blogspot.com 69


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

{ = str2[j])
int m = strlen(str2); break;
int n = strlen(str1);
for (int i = 0; i <= n - m; i++) if (j == m)
{ cout << i << endl
int j; ;
}
}
for (j = 0; j < m; j++)
if (str1[i + j] ! int main()
= str2[j]) {
break; char str1[] = "1253234";
char str2[] = "323";
if (j == m) func(str2, str1);
cout << i << endl return 0;
; }
}
} a) O(n)
b) O(m)
int main()
{ c) O(m * n)
char str1[] = "1253234"; d) O(m + n)
char str2[] = "323";
func(str2, str1); Answer: c
return 0; Explanation: The given code describes the
}
naive method of pattern searching. By
a) 1 observing the nested loop in the code we can
say that the time complexity of the loop is
b) 2
O(m*n).
c) 3
d) 4 4. What will be the auxiliary space
complexity of the following code?
Answer: c
Explanation: The given code describes the #include<bits/stdc++.h>
naive method of finding a pattern in a string. using namespace std;
So the output will be 3 as the given sub string
begins at that index in the pattern. void func(char* str2, char* str1)
{
int m = strlen(str2);
3. What will be the worst case time int n = strlen(str1);
complexity of the following code? for (int i = 0; i <= n - m; i++)
{
#include<bits/stdc++.h> int j;
using namespace std;
for (j = 0; j < m; j++)
void func(char* str2, char* str1) if (str1[i + j] !
{ = str2[j])
int m = strlen(str2); break;
int n = strlen(str1);
for (int i = 0; i <= n - m; i++) if (j == m)
{ cout << i << endl
int j; ;
}
}
for (j = 0; j < m; j++)
if (str1[i + j] !

Downloaded From: https://cse-r17.blogspot.com 70


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

int main() if (j == m)
{ cout << i << endl
char str1[] = "1253234"; ;
char str2[] = "323"; }
func(str2, str1); }
return 0;
} int main()
{
a) O(n) char str1[] = "1253234";
b) O(1) char str2[] = "323";
func(str2, str1);
c) O(log n) return 0;
d) O(m) }

Answer: b a) O(n)
Explanation: The given code describes the b) O(m)
naive method of pattern searching. Its c) O(m * n)
auxiliary space requirement is O(1). d) O(m + n)

5. What is the worst case time complexity of Answer: b


KMP algorithm for pattern searching (m = Explanation: The given code describes the
length of text, n = length of pattern)? naive method of pattern searching. The best
a) O(n) case of the code occurs when the first
b) O(n*m) character of the pattern does not appear in the
c) O(m) text at all. So in such a case, only one
d) O(log n) iteration is required thus time complexity will
be O(m).
Answer: c
Explanation: KMP algorithm is an efficient 7. What is the time complexity of Z algorithm
pattern searching algorithm. It has a time for pattern searching (m = length of text, n =
complexity of O(m) where m is the length of length of pattern)?
text. a) O(n + m)
b) O(m)
6. What will be the best case time complexity c) O(n)
of the following code? d) O(m * n)
#include<bits/stdc++.h> Answer: a
using namespace std;
void func(char* str2, char* str1) Explanation: Z algorithm is an efficient
{ pattern searching algorithm as it searches the
int m = strlen(str2); pattern in linear time. It has a time
int n = strlen(str1); complexity of O(m + n) where m is the length
of text and n is the length of the pattern.
for (int i = 0; i <= n - m; i++)
{
int j; 8. What is the auxiliary space complexity of
Z algorithm for pattern searching (m = length
of text, n = length of pattern)?
for (j = 0; j < m; j++) a) O(n + m)
if (str1[i + j] !
= str2[j])
b) O(m)
break; c) O(n)
d) O(m * n)

Downloaded From: https://cse-r17.blogspot.com 71


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: b Answer: a
Explanation: Z algorithm is an efficient Explanation: In quick sort, the array is
pattern searching algorithm as it searches the divided into sub-arrays and then it is sorted
pattern in linear time. It an auxiliary space of (divide-and-conquer strategy).
O(m) for maintaining Z array.
3. What is the worst case time complexity of
9. The naive pattern searching algorithm is an a quick sort algorithm?
in place algorithm. a) O(N)
a) true b) O(N log N)
b) false c) O(N2)
d) O(log N)
Answer: a
Explanation: The auxiliary space complexity Answer: c
required by naive pattern searching algorithm Explanation: The worst case performance of
is O(1). So it qualifies as an in place a quick sort algorithm is mathematically
algorithm.
found to be O(N2).
10. Rabin Karp algorithm and naive pattern
4. Which of the following methods is the
searching algorithm have the same worst case
most effective for picking the pivot element?
time complexity.
a) first element
a) true
b) last element
b) false
c) median-of-three partitioning
Answer: a d) random element
Explanation: The worst case time complexity
Answer: c
of Rabin Karp algorithm is O(m*n) but it has
Explanation: Median-of-three partitioning is
a linear average case time complexity. So
the best method for choosing an appropriate
Rabin Karp and naive pattern searching
pivot element. Picking a first, last or random
algorithm have the same worst case time
element as a pivot is not much effective.
complexity.
5. Find the pivot element from the given input
using median-of-three partitioning method.
1. Which of the following sorting algorithms
8, 1, 4, 9, 6, 3, 5, 2, 7, 0.
is the fastest?
a) 8
a) Merge sort
b) 7
b) Quick sort
c) 9
c) Insertion sort
d) 6
d) Shell sort
Answer: d
Answer: b
Explanation: Left element=8, right
Explanation: Quick sort is the fastest known
element=0,
sorting algorithm because of its highly
Centre=[position(left+right)/2]=6.
optimized inner loop.
6. Which is the safest method to choose a
2. Quick sort follows Divide-and-Conquer
pivot element?
strategy. a) choosing a random element as pivot
a) True b) choosing the first element as pivot
b) False

Downloaded From: https://cse-r17.blogspot.com 72


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

c) choosing the last element as pivot c) three


d) median-of-three partitioning method d) four

Answer: a Answer: b
Explanation: This is the safest method to Explanation: The entire array is divided into
choose the pivot element since it is very two partitions, 1st sub array containing
unlikely that a random pivot would elements less than the pivot element and 2nd
consistently provide a poor partition. sub array containing elements greater than the
pivot element.
7. What is the average running time of a
quick sort algorithm? 11. Which is the worst method of choosing a
a) O(N2) pivot element?
b) O(N) a) first element as pivot
c) O(N log N) b) last element as pivot
d) O(log N) c) median-of-three partitioning
d) random element as pivot
Answer: c
Explanation: The best case and average case Answer: a
analysis of a quick sort algorithm are Explanation: Choosing the first element as
mathematically found to be O(N log N). pivot is the worst method because if the input
is pre-sorted or in reverse order, then the
8. Which of the following sorting algorithms pivot provides a poor partition.
is used along with quick sort to sort the sub
arrays? 12. Which among the following is the best
a) Merge sort cut-off range to perform insertion sort within
b) Shell sort a quick sort?
c) Insertion sort a) N=0-5
d) Bubble sort b) N=5-20
c) N=20-30
Answer: c d) N>30
Explanation: Insertion sort is used along with
quick sort to sort the sub arrays. Answer: b
It is used only at the end. Explanation: A good cut-off range is
anywhere between N=5 and N=20 to avoid
9. Quick sort uses join operation rather than nasty degenerate cases.
merge operation.
a) true
b) false 1. The shortest distance between a line and a
point is achieved when?
Answer: a a) a line is drawn at 90 degrees to the given
Explanation: Quick sort uses join operation line from the given point
since join is a faster operation than merge. b) a line is drawn at 180 degrees to the given
line from the given point
10. How many sub arrays does the quick sort c) a line is drawn at 60 degrees to the given
algorithm divide the entire array into? line from the given point
a) one d) a line is drawn at 270 degrees to the given
b) two line from the given point

Downloaded From: https://cse-r17.blogspot.com 73


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: a
Explanation: The shortest distance between a
line and a point is achieved when a line is b)
drawn at 90 degrees to the given line from the
given point.
c)
2. What is the shortest distance between the
d) c1+c2
line given by ax + by + c = 0 and the point
(x1,y1)? Answer: b
Explanation: The general formula for finding
the shortest distance between two parallel
a) lines given by ax+by+c1 and ax+by+c2 is
(c1-c2)/(√a2+b2). We can find this by
considering the distance of any one point on
b)
one of the line to the other line.

5. What is the distance between the lines 3x-


c) 4y+7=0 and 3x-4y+5=0?
d) ax1+by1+c a) 1 unit
b) 0.5 unit
Answer: a
c) 0.8 unit
Explanation: The shortest distance between a
d) 0.4 unit
line and a point is given by the formula
(ax1+by1+c)/(√a2+b2). This formula can be Answer: d
derived using the formula of area of a Explanation: As the given lines are parallel
triangle. so the distance between them can be
calculated by using the formula (c1-
3. What is the shortest distance between the
c2)/(√a2+b2). So we get the distance as 0.4
line given by -2x + 3y + 4 = 0 and the point
unit.
(5,6)?
a) 4.5 units 6. What will be the slope of the line given by
b) 5.4 units ax + by + c = 0?
c) 4.3 units a) -a/b
d) 3.3 units b) -b/a
c) -c/a
Answer: d
d) a/c
Explanation: The shortest distance between a
line and a point is given by the formula Answer: a
(ax1+by1+c)/(√a2+b2). Using this formula we Explanation: The slope of a line given by the
get the answer 3.3 units. equation ax + by + c=0 has the slope of -a/b.
So two lines having the same ratio of the
4. What is the general formula for finding the coefficient of x and y will be parallel to each
shortest distance between two parallel lines other.
given by ax+by+c1=0 and ax+by+c2=0?
7. What will be the slope of the line given by
10x + 5y + 8=0?
a) a) -5

Downloaded From: https://cse-r17.blogspot.com 74


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

b) -2 line is 2 so the slope of line perpendicular to


c) -1.25 it will be -1/2.
d) 5
11. Find the output of the following code.
Answer: b
Explanation: The slope of a line given by the #include<math.h>
#include<iostream>
equation ax + by + c=0 has the slope of -a/b.
using namespace std;
So the slope of the given line will be -2. void distance(float x, float y, float a,
float b, float c)
8. What will be the co-ordinates of foot of {
perpendicular line drawn from the point (-1,3) float d = fabs((a * x + b * y + c
to the line 3x-4y-16=0? )) / (sqrt(a * a + b * b));
cout<<d;
a) (1/5,2/5) return;
b) (2/25,5/25) }
c) (68/25,-49/25) int main()
d) (-49/25,68/25) {
float x = -2;
Answer: c float y = -3;
float a = 5;
Explanation: The foot of perpendicular can float b = -2;
be found by equating the distance between float c = - 4;
the two points and the distance between point distance(x, y, a, b, c);
and line. This is found to be (68/25,-49/25). return 0;
}
9. Which of the following is used to find the
absolute value of the argument in C++? a) 2.8
a) abs() b) 1.8
b) fabs() c) 1.4
c) mod() d) 2.4
d) ab()
Answer: c
Answer: b Explanation: The given code calculates the
Explanation: In C++ the absolute value of an shortest distance between line and a point. So
argument can be found by using the function the output will be 1.4.
fabs(). It is available under the header file
math.h.
1. Which of the following areas do closest
10. What will be the slope of the line pair problem arise?
perpendicular to the line 6x-3y-16=0? a) computational geometry
a) 1/2 b) graph colouring problems
b) -1/2 c) numerical problems
c) 2 d) string matching
d) -2
Answer: a
Answer: b Explanation: Closest pair problem arises in
Explanation: For two lines to be two most important areas- computational
perpendicular the product of their slopes geometry and operational research.
should be equal to -1. So as the slope of given
2. Which approach is based on computing the
distance between each pair of distinct points

Downloaded From: https://cse-r17.blogspot.com 75


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

and finding a pair with the smallest distance? pair algorithm is Euclidean distance and its
a) Brute force formula is given by d=√(xi-xj)2+(yi-yj)2.
b) Exhaustive search
c) Divide and conquer 6. Which of the following is similar to
d) Branch and bound Euclidean distance?
a) Manhattan distance
Answer: a
b) Pythagoras metric
Explanation: Brute force is a straight forward c) Chebyshev distance
approach that solves closest pair problem d) Heuristic distance
using that algorithm.
Answer: b
3. What is the runtime efficiency of using Explanation: In older times, Euclidean
brute force technique for the closest pair distance metric is also called a Pythagoras
problem? metric which is the length of the line segment
a) O(N) connecting two points.
b) O(N log N)
c) O(N2) 7. Which of the following strategies does the
d) O(N3 log N) following diagram depict?

Answer: c
Explanation: The efficiency of closest pair
algorithm by brute force technique is
mathematically found to be O(N2).

4. The most important condition for which


closest pair is calculated for the points (pi, pj)
is? a) Divide and conquer strategy
a) i>j b) Brute force
b) i!=j c) Exhaustive search
c) i=j d) Backtracking
d) i<j
Answer: b
Answer: d Explanation: Brute force is a straight forward
Explanation: To avoid computing the approach to solve critical problems. Here, we
distance between the same pair of points use brute force technique to find the closest
twice, we consider only the pair of points (pi, distance between p1 and p2.
pj) for which i<j.
8. Manhattan distance is an alternative way to
define a distance between two points.
5. What is the basic operation of closest pair a) true
algorithm using brute force technique? b) false
a) Euclidean distance
b) Radius Answer: a
c) Area Explanation: Manhattan distance is an
d) Manhattan distance alternative way to calculate distance. It is the
distance between two points measured along
Answer: a axes at right angles.
Explanation: The basic operation of closest

Downloaded From: https://cse-r17.blogspot.com 76


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

9. What is the optimal time required for


solving the closest pair problem using divide
and conquer approach?
a) O(N)
b) O(log N)
c) O(N log N)
d) O(N2)

Answer: c
Explanation: The optimal time for solving
using a divide and conquer approach is a) Brute force
mathematically found to be O(N log N). b) Divide and conquer
c) Exhaustive search
10. In divide and conquer, the time is taken d) Branch and bound
for merging the subproblems is?
a) O(N) Answer: b
b) O(N log N) Explanation: The above diagram depicts the
c) O(N2) implementation of divide and conquer. The
d) O(log N) problem is divided into sub problems and are
separated by a line.
Answer: b
Explanation: The time taken for merging the 13. Which of the points are closer to each
smaller subproblems in a divide and conquer other?
approach is mathematically found to be O(N
log N).

11. The optimal time obtained through divide


and conquer approach using merge sort is the
best case efficiency.
a) true
b) false

Answer: a a) p1 and p11


Explanation: The optimal time obtained b) p3 and p8
through divide and conquer approach is the c) p2 and p3
best class efficiency and it is given by Ω(N d) p9 and p10
log N).
Answer: c
12. Which of the following strategies does the Explanation: From symmetry, we determine
following diagram depict? that the closest pair is p2 and p3. But the
exact calculations have to be done using
Euclid’s algorithm.

1. Cross product is a mathematical operation


performed between ________________
a) 2 scalar numbers

Downloaded From: https://cse-r17.blogspot.com 77


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

b) a scalar and a vector is |a|.|b| sin(θ). Its direction is perpendicular to


c) 2 vectors the plane containing a and b.
d) any 2 numbers
5. The concept of cross product is applied in
Answer: c the field of computer graphics.
Explanation: Cross product is a a) true
mathematical operation that is performed on 2 b) false
vectors in a 3D plane. It has many
applications in computer programming and Answer: a
physics. Explanation: The concept of cross product
find its application in the field of computer
2. Cross product is also known as? graphics. It can be used to find the winding of
a) scalar product polygon about a point.
b) vector product
c) dot product 6. Which of the following equals the a x b ( a
d) multiplication and b are two vectors)?
a) – (a x b)
Answer: b b) a.b
Explanation: Cross product is also known as c) b x a
a vector product. It is a mathematical d) – (b x a)
operation that is performed on 2 vectors in 3D
plane. Answer: d
Explanation: The vector product a x b is
3. What is the magnitude of resultant of cross equal to – (b x a). The minus sign shows that
product of two parallel vectors a and b? these vectors have opposite directions.
a) |a|.|b|
b) |a|.|b| cos(180) 7. Cross product of two vectors can be used to
c) |a|.|b| sin(180) find?
d) 1 a) area of rectangle
b) area of square
Answer: c c) area of parallelogram
Explanation: The resultant of cross product d) perimeter of rectangle
of 2 parallel vectors is always 0 as the angle
between them is 0 or 180 degrees. So the Answer: c
answer is |a|.|b| sin(180). Explanation: Cross product of two vectors
can be used to find the area of parallelogram.
4. What is the general formula for finding the For this, we need to consider the vectors as
magnitude of the cross product of two vectors the adjacent sides of the parallelogram.
a and b with angle θ between them?
a) |a|.|b| 8. The resultant vector from the cross product
b) |a|.|b| cos(θ) of two vectors is _____________
c) |a|.|b| sin(θ) a) perpendicular to any one of the two vectors
d) |a|.|b| tan(θ) involved in cross product
b) perpendicular to the plane containing both
Answer: c vectors
Explanation: The general formula for finding c) parallel to to any one of the two vectors
the magnitude of cross product of two vectors involved in cross product

Downloaded From: https://cse-r17.blogspot.com 78


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

d) parallel to the plane containing both cross[2] = A[0] * B[1] - A[1] * B


vectors [0];
}
int main()
Answer: b {
Explanation: The resultant vector from the int A[] = { 1, 2, 4 };
cross product of two vectors is perpendicular int B[] = { 2, 3, 2 };
to the plane containing both vectors. In other int cross[3];
words, it should be perpendicular to both the crossP(A, B, cross);
for (int i = 0; i < 3; i++)
vectors involved in the cross product. cout << cross[i] << " ";
return 0;
9. What will be the cross product of the }
vectors 2i + 3j + k and 3i + 2j + k?
a) i + 2j + k a) 1 2 5
b) 2i + 3j + k b) -1 -5 -3
c) i + j – 5k c) -6 -8 -1
d) 2i – j – 5k d) -8 -6 -1

Answer: c Answer: d
Explanation: We can find the cross product Explanation: The given code calculates the
of the given vectors by solving the cross product of the vectors stored in arrays A
determinant. and B respectively. So the output will be -8 -6
-1.

12. Which of the following operation will


give a vector that is perpendicular to both
vectors a and b?
a) a x b
10. What will be the cross product of the b) a.b
vectors 2i + 3j + k and 6i + 9j + 3k? c) b x a
a) i + 2j + k d) both a x b and b x a
b) i – j – 5k
c) 0 Answer: d
d) 2i – j – 5k Explanation: The resultant vector from the
cross product of two vectors is perpendicular
Answer: c to the plane containing both vectors. So both
Explanation: The given vectors are parallel a x b and b x a will give a vector that is
to each other. The cross product of parallel perpendicular to both vectors a and b.
vectors is 0 because sin(0) is 0.

11. Find the output of the following code. 1. ___________ is a method of constructing a
smallest polygon out of n given points.
#include <bits/stdc++.h>
using namespace std; a) closest pair problem
void crossP(int A[], int B[], int cross[] b) quick hull problem
) c) path compression
{ d) union-by-rank
cross[0] = A[1] * B[2] - A[2] * B
[1];
cross[1] = A[0] * B[2] - A[2] * B
Answer: b
[0]; Explanation: Quick hull is a method of

Downloaded From: https://cse-r17.blogspot.com 79


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

constructing a smallest convex polygon out of Answer: c


n given points in a plane. Explanation: The worst case complexity of
quickhull algorithm using divide and conquer
2. What is the other name for quick hull approach is mathematically found to be
problem? O(N2).
a) convex hull
b) concave hull 6. What does the following diagram depict?
c) closest pair
d) path compression

Answer: a
Explanation: The other name for quick hull
problem is convex hull problem whereas the
closest pair problem is the problem of finding
the closest distance between two points. a) closest pair
b) convex hull
3. How many approaches can be applied to c) concave hull
solve quick hull problem? d) path compression
a) 1
b) 2 Answer: b
c) 3 Explanation: The above diagram is a
d) 4 depiction of convex hull, also known as quick
hull, since it encloses n points into a convex
Answer: b polygon.
Explanation: Most commonly, two
approaches are adopted to solve quick hull 7. Which of the following statement is not
problem- brute force approach and divide and related to quickhull algorithm?
conquer approach. a) finding points with minimum and
maximum coordinates
4. What is the average case complexity of a b) dividing the subset of points by a line
quick hull algorithm? c) eliminating points within a formed triangle
a) O(N) d) finding the shortest distance between two
b) O(N log N) points
c) O(N2)
d) O(log N) Answer: d
Explanation: Finding the shortest distance
Answer: b between two points belongs to closest pair
Explanation: The average case complexity of algorithm while the rest is quickhull.
quickhull algorithm using divide and conquer
approach is mathematically found to be O(N 8. The quick hull algorithm runs faster if the
log N). input uses non- extreme points.
a) true
5. What is the worst case complexity of quick b) false
hull?
a) O(N) Answer: a
b) O(N log N) Explanation: It is proved that the quick hull
c) O(N2) algorithm runs faster if the input uses non-
d) O(log N)

Downloaded From: https://cse-r17.blogspot.com 80


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

extreme points and also, if it uses less Answer: a


memory. Explanation: The time taken to find the ‘n’
points that lie in a convex quadrilateral is
9. To which type of problems does quick hull mathematically found to be O(N).
belong to?
a) numerical problems
b) computational geometry 1. Chan’s algorithm is used for computing
c) graph problems _________
d) string problems a) Closest distance between two points
b) Convex hull
Answer: b c) Area of a polygon
Explanation: Quick hull problem and closest d) Shortest path between two points
pair algorithms are some of the examples of
computational problems. Answer: b
Explanation: Chan’s algorithm is an output-
10. Which of the following algorithms is sensitive algorithm used to compute the
similar to a quickhull algorithm? convex hull set of n points in a 2D or 3D
a) merge sort space. Closest pair algorithm is used to
b) shell sort compute the closest distance between two
c) selection sort points.
d) quick sort
2. What is the running time of Chan’s
Answer: d algorithm?
Explanation: Quickhull algorithm is similar a) O(log n)
to a quick sort algorithm with respect to the b) O(n log n)
run time average case and worst case c) O(n log h)
efficiencies. d) O(log h)

11. Who formulated quick hull algorithm? Answer: c


a) Eddy Explanation: The running time of Chan’s
b) Andrew algorithm is calculated to be O(n log h) where
c) Chan h is the number of vertices of the convex hull.
d) Graham
3. Who formulated Chan’s algorithm?
Answer: a a) Timothy
Explanation: Eddy formulated quick hull b) Kirkpatrick
algorithm. Graham invented graham scan. c) Frank Nielsen
Andrew formulated Andrew’s algorithm and d) Seidel
Chan invented Chan’s algorithm.
Answer: a
12. The time is taken to find the ‘n’ points Explanation: Chan’s algorithm was
that lie in a convex quadrilateral is? formulated by Timothy Chan. Kirkpatrick and
a) O(N) Seidel formulated the Kirkpatrick-Seidel
b) O(N log N) algorithm. Frank Nielsen developed a
c) O(N2) paradigm relating to Chan’s algorithm.
d) O(log N)
4. The running time of Chan’s algorithm is
obtained from combining two algorithms.

Downloaded From: https://cse-r17.blogspot.com 81


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

a) True time was originally O(n log n). He used


b) False Chan’s algorithm to speed up to O(n log h)
where h is the number of edges.
Answer: a
Explanation: The O(n log h) running time of 8. Which of the following statements is not a
Chan’s algorithm is obtained by combining part of Chan’s algorithm?
the running time of Graham’s scan [O(n log a) eliminate points not in the hull
n)] and Jarvis match [O(nh)]. b) recompute convex hull from scratch
c) merge previously calculated convex hull
5. Which of the following is called the d) reuse convex hull from the previous
“ultimate planar convex hull algorithm”? iteration
a) Chan’s algorithm
b) Kirkpatrick-Seidel algorithm Answer: b
c) Gift wrapping algorithm Explanation: Chan’s algorithm implies that
d) Jarvis algorithm the convex hulls of larger points can be
arrived at by merging previously calculated
Answer: b convex hulls. It makes the algorithm simpler
Explanation: Kirkpatrick-Seidel algorithm is instead of recomputing every time from
called as the ultimate planar convex hull scratch.
algorithm. Its running time is the same as that
of Chan’s algorithm (i.e.) O(n log h). 9. Which of the following factors account
more to the cost of Chan’s algorithm?
6. Which of the following algorithms is the a) computing a single convex hull
simplest? b) locating points that constitute a hull
a) Chan’s algorithm c) computing convex hull in groups
b) Kirkpatrick-Seidel algorithm d) merging convex hulls
c) Gift wrapping algorithm
d) Jarvis algorithm Answer: c
Explanation: The majority of the cost of the
Answer: a algorithm lies in the pre-processing (i.e.)
Explanation: Chan’s algorithm is very computing convex hull in groups. To reduce
practical for moderate sized problems cost, we reuse convex hulls from previous
whereas Kirkpatrick-Seidel algorithm is not. iterations.
Although, they both have the same running
time. Gift wrapping algorithm is a non-output 10. Chan’s algorithm can be used to compute
sensitive algorithm and has a longer running the lower envelope of a trapezoid.
time. a) true
b) false
7. What is the running time of Hershberger
algorithm? Answer: a
a) O(log n) Explanation: An extension of Chan’s
b) O(n log n) algorithm can be used for proving solutions to
c) O(n log h) complex problems like computing the lower
d) O(log h) envelope L(S) where S is a set of ‘n’ line
segments in a trapezoid.
Answer: b
Explanation: Hershberger’s algorithm is an
output sensitive algorithm whose running

Downloaded From: https://cse-r17.blogspot.com 82


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

1. Which of the following is false in the case Answer: b


of a spanning tree of a graph G? Explanation: In the travelling salesman
a) It is tree that spans G problem we have to find the shortest possible
b) It is a subgraph of the G route that visits every city exactly once and
c) It includes every vertex of the G returns to the starting point for the given a set
d) It can be either cyclic or acyclic of cities. So, travelling salesman problem can
be solved by contracting the minimum
Answer: d spanning tree.
Explanation: A graph can have many

M
spanning trees. Each spanning tree of a graph 5. Consider the graph M with 3 vertices. Its
G is a subgraph of the graph G, and spanning adjacency matrix is shown below. Which of

O
trees include every vertex of the gram. the following is true?
Spanning trees are always acyclic.

C
2. Every graph has only one minimum

T.
spanning tree.
a) True
b) False

O
a) Graph M has no minimum spanning tree
Answer: b b) Graph M has a unique minimum spanning
Explanation: Minimum spanning tree is a
spanning tree with the lowest cost among all
the spacing trees. Sum of all of the edges in
SP
trees of cost 2
c) Graph M has 3 distinct minimum spanning
trees, each of cost 2
G
the spanning tree is the cost of the spanning d) Graph M has 3 spanning trees of different
tree. There can be many minimum spanning costs
LO

trees for a given graph.


Answer: c
3. Consider a complete graph G with 4 Explanation: Here all non-diagonal elements
vertices. The graph G has ____ spanning
.B

in the adjacency matrix are 1. So, every


trees. vertex is connected every other vertex of the
a) 15 graph. And, so graph M has 3 distinct
17

b) 8 minimum spanning trees.


c) 16
d) 13
-R

Answer: c
Explanation: A graph can have many
SE

spanning trees. And a complete graph with n


vertices has n(n-2) spanning trees. So, the 6. Consider a undirected graph G with
vertices { A, B, C, D, E}. In graph G, every
complete graph with 4 vertices has 4(4-2) = 16 edge has distinct weight. Edge CD is edge
C

spanning trees. with minimum weight and edge AB is edge


with maximum weight. Then, which of the
4. The travelling salesman problem can be
following is false?
solved using _________
a) Every minimum spanning tree of G must
a) A spanning tree
contain CD
b) A minimum spanning tree
b) If AB is in a minimum spanning tree, then
c) Bellman – Ford algorithm
its removal must disconnect G
d) DFS traversal

Downloaded From: https://cse-r17.blogspot.com 83


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

c) No minimum spanning tree contains AB 56.


d) G has a unique minimum spanning tree

Answer: c
Explanation: Every MST will contain CD as
it is smallest edge. So, Every minimum
spanning tree of G must contain CD is true.
And G has a unique minimum spanning tree
is also true because the graph has edges with
distinct weights. So, no minimum spanning
tree contains AB is false.
9. Which of the following is not the algorithm
7. If all the weights of the graph are positive, to find the minimum spanning tree of the
then the minimum spanning tree of the graph given graph?
is a minimum cost subgraph. a) Boruvka’s algorithm
a) True b) Prim’s algorithm
b) False c) Kruskal’s algorithm
d) Bellman–Ford algorithm
Answer: a
Explanation: A subgraph is a graph formed Answer: d
from a subset of the vertices and edges of the Explanation: The Boruvka’s algorithm,
original graph. And the subset of vertices Prim’s algorithm and Kruskal’s algorithm are
includes all endpoints of the subset of the the algorithms that can be used to find the
edges. So, we can say MST of a graph is a minimum spanning tree of the given graph.
subgraph when all weights in the original The Bellman-Ford algorithm is used to find
graph are positive. the shortest path from the single source to all
other vertices.
8. Consider the graph shown below. Which of
the following are the edges in the MST of the 10. Which of the following is false?
given graph? a) The spanning trees do not have any cycles
b) MST have n – 1 edges if the graph has n
edges
c) Edge e belonging to a cut of the graph if
has the weight smaller than any other edge in
the same cut, then the edge e is present in all
the MSTs of the graph
d) Removing one edge from the spanning tree
will not make the graph disconnected

Answer: d
a) (a-c)(c-d)(d-b)(d-b) Explanation: Every spanning tree has n – 1
b) (c-a)(a-d)(d-b)(d-e) edges if the graph has n edges and has no
c) (a-d)(d-c)(d-b)(d-e) cycles. The MST follows the cut property,
d) (c-a)(a-d)(d-c)(d-b)(d-e) Edge e belonging to a cut of the graph if has
the weight smaller than any other edge in the
Answer: c same cut, then the edge e is present in all the
Explanation: The minimum spanning tree of MSTs of the graph.
the given graph is shown below. It has cost

Downloaded From: https://cse-r17.blogspot.com 84


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

1. Kruskal’s algorithm is used to ______ by adding the edges to spanning tree one-one
a) find minimum spanning tree by one. The MST for the given graph is,
b) find single source shortest path
c) find all pair shortest path algorithm
d) traverse the graph

Answer: a
Explanation: The Kruskal’s algorithm is used
to find the minimum spanning tree of the
connected graph. It construct the MST by
finding the edge having the least possible
weight that connects two trees in the forest. So, the weight of the MST is 19.

2. Kruskal’s algorithm is a ______ 4. What is the time complexity of Kruskal’s


a) divide and conquer algorithm algorithm?
b) dynamic programming algorithm a) O(log V)
c) greedy algorithm b) O(E log V)
d) approximation algorithm c) O(E2)
d) O(V log E)
Answer: c
Explanation: Kruskal’s algorithm uses a Answer: b
greedy algorithm approach to find the MST Explanation: Kruskal’s algorithm involves
of the connected weighted graph. In the sorting of the edges, which takes O(E logE)
greedy method, we attempt to find an optimal time, where E is a number of edges in graph
solution in stages. and V is the number of vertices. After sorting,
all edges are iterated and union-find
3. Consider the given graph. algorithm is applied. union-find algorithm
requires O(logV) time. So, overall Kruskal’s
algorithm requires O(E log V) time.

5. Consider the following graph. Using


Kruskal’s algorithm, which edge will be
selected first?

What is the weight of the minimum spanning


tree using the Kruskal’s algorithm?
a) 24
b) 23
c) 15
d) 19

Answer: d a) GF
Explanation: Kruskal’s algorithm constructs b) DE
the minimum spanning tree by constructing

Downloaded From: https://cse-r17.blogspot.com 85


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

c) BE disconnected graphs
d) BG c) Prim’s algorithm is simpler than Kruskal’s
algorithm
Answer: c d) In Kruskal’s sort edges are added to MST
Explanation: In Krsuskal’s algorithm the in decreasing order of their weights
edges are selected and added to the spanning
tree in increasing order of their weights. Answer: b
Therefore, the first edge selected will be the Explanation: Prim’s algorithm iterates from
minimal one. So, correct option is BE. one node to another, so it can not be applied
for disconnected graph. Kruskal’s algorithm
6. Which of the following edges form can be applied to the disconnected graphs to
minimum spanning tree on the graph using construct the minimum cost forest. Kruskal’s
kruskals algorithm? algorithm is comparatively easier and simpler
than prim’s algorithm.

8. Which of the following is false about the


Kruskal’s algorithm?
a) It is a greedy algorithm
b) It constructs MST by selecting edges in
increasing order of their weights
c) It can accept cycles in the MST
d) It uses union-find data structure

Answer: c
Explanation: Kruskal’s algorithm is a greedy
algorithm to construct the MST of the given
a) (B-E)(G-E)(E-F)(D-F) graph. It constructs the MST by selecting
b) (B-E)(G-E)(E-F)(B-G)(D-F) edges in increasing order of their weights and
c) (B-E)(G-E)(E-F)(D-E) rejects an edge if it may form the cycle. So,
d) (B-E)(G-E)(E-F)(D-F)(D-G) using Kruskal’s algorithm is never formed.
Answer: a 9. Kruskal’s algorithm is best suited for the
Explanation: Using Krushkal’s algorithm on dense graphs than the prim’s algorithm.
the given graph, the generated minimum a) True
spanning tree is shown below. b) False

Answer: b
Explanation: Prim’s algorithm outperforms
the Kruskal’s algorithm in case of the dense
graphs. It is significantly faster if graph has
more edges than the Kruskal’s algorithm.
So, the edges in the MST are, (B-E)(G-E)(E-
F)(D-F). 10. Consider the following statements.
S1. Kruskal’s algorithm might produce a non-
7. Which of the following is true? minimal spanning tree.
a) Prim’s algorithm can also be used for S2. Kruskal’s algorithm can efficiently
disconnected graphs implemented using the disjoint-set data
b) Kruskal’s algorithm can also run on the structure.

Downloaded From: https://cse-r17.blogspot.com 86


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

a) S1 is true but S2 is false Answer: c


b) Both S1 and S2 are false Explanation: In Prim’s algorithm, we select a
c) Both S1 and S2 are true vertex and add it to the MST. Then we add
d) S2 is true but S1 is false the minimum edge from the vertex in MST to
vertex not in MST. From, figure shown below
Answer: d weight of MST = 27.
Explanation: In Kruskal’s algorithm, the
disjoint-set data structure efficiently identifies
the components containing a vertex and adds
the new edges. And Kruskal’s algorithm
always finds the MST for the connected
graph.

3. Worst case is the worst case time


1. Which of the following is true? complexity of Prim’s algorithm if adjacency
a) Prim’s algorithm initialises with a vertex matrix is used?
b) Prim’s algorithm initialises with a edge a) O(log V)
c) Prim’s algorithm initialises with a vertex
b) O(V2)
which has smallest edge
d) Prim’s algorithm initialises with a forest c) O(E2)
d) O(V log E)
Answer: a
Explanation: Steps in Prim’s algorithm: (I) Answer: b
Select any vertex of given graph and add it to Explanation: Use of adjacency matrix
MST (II) Add the edge of minimum weight provides the simple implementation of the
from a vertex not in MST to the vertex in Prim’s algorithm. In Prim’s algorithm, we
MST; (III) It MST is complete the stop, need to search for the edge with a minimum
otherwise go to step (II). for that vertex. So, worst case time
complexity will be O(V2), where V is the
2. Consider the given graph. number of vertices.

4. Prim’s algorithm is a ______


a) Divide and conquer algorithm
b) Greedy algorithm
c) Dynamic Programming
d) Approximation algorithm

Answer: b
Explanation: Prim’s algorithm uses a greedy
algorithm approach to find the MST of the
connected weighted graph. In greedy method,
What is the weight of the minimum spanning we attempt to find an optimal solution in
tree using the Prim’s algorithm,starting from stages.
vertex a?
a) 23 5. Prim’s algorithm resembles Dijkstra’s
b) 28 algorithm.
c) 27 a) True
d) 11 b) False

Downloaded From: https://cse-r17.blogspot.com 87


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: a
Explanation: In Prim’s algorithm, the MST is
constructed starting from a single vertex and
adding in new edges to the MST that link the
partial tree to a new vertex outside of the So, the MST contains edges (4-3)(3-2)(2-1)
MST. And Dijkstra’s algorithm also rely on (1-5).
the similar approach of finding the next
closest vertex. So, Prim’s algorithm 8. Prim’s algorithm is also known as
resembles Dijkstra’s algorithm. __________
a) Dijkstra–Scholten algorithm
6. Kruskal’s algorithm is best suited for the b) Borůvka’s algorithm
sparse graphs than the prim’s algorithm. c) Floyd–Warshall algorithm
a) True d) DJP Algorithm
b) False
Answer: d
Answer: a Explanation: The Prim’s algorithm was
Explanation: Prim’s algorithm and Kruskal’s developed by Vojtěch Jarník and it was latter
algorithm perform equally in case of the discovered by the duo Prim and Dijkstra.
sparse graphs. But Kruskal’s algorithm is Therefore, Prim’s algorithm is also known as
simpler and easy to work with. So, it is best DJP Algorithm.
suited for sparse graphs.
9. Prim’s algorithm can be efficiently
7. Consider the graph shown below. implemented using _____ for graphs with
greater density.
a) d-ary heap
b) linear search
c) fibonacci heap
d) binary search

Answer: a
Explanation: In Prim’s algorithm, we add the
minimum weight edge for the chosen vertex
which requires searching on the array of
Which of the following edges form the MST weights. This searching can be efficiently
of the given graph using Prim’a algorithm, implemented using binary heap for dense
starting from vertex 4. graphs. And for graphs with greater density,
a) (4-3)(5-3)(2-3)(1-2) Prim’s algorithm can be made to run in linear
b) (4-3)(3-5)(5-1)(1-2) time using d-ary heap(generalization of
c) (4-3)(3-5)(5-2)(1-5) binary heap).
d) (4-3)(3-2)(2-1)(1-5)
10. Which of the following is false about
Answer: d Prim’s algorithm?
Explanation: The MST for the given graph a) It is a greedy algorithm
using Prim’s algorithm starting from vertex 4 b) It constructs MST by selecting edges in
is, increasing order of their weights
c) It never accepts cycles in the MST
d) It can be implemented using the Fibonacci
heap

Downloaded From: https://cse-r17.blogspot.com 88


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: b algorithm is O(N2) because of the use of


Explanation: Prim’s algorithm can be doubly nested for loops. It depends on how
implemented using Fibonacci heap and it the table is manipulated.
never accepts cycles. And Prim’s algorithm
follows greedy approach. Prim’s algorithms 4. Dijkstra’s Algorithm cannot be applied on
span from one vertex to another. ______________
a) Directed and weighted graphs
b) Graphs having negative weight function
1. Dijkstra’s Algorithm is used to solve c) Unweighted graphs
_____________ problems. d) Undirected and unweighted graphs
a) All pair shortest path
b) Single source shortest path Answer: b
c) Network flow Explanation: Dijkstra’s Algorithm cannot be
d) Sorting applied on graphs having negative weight
function because calculation of cost to reach a
Answer: b destination node from the source node
Explanation: Dijkstra’s Algorithm is used for becomes complex.
solving single source shortest path problems.
In this algorithm, a single node is fixed as a 5. What is the pseudo code to compute the
source node and shortest paths from this node shortest path in Dijkstra’s algorithm?
to all other nodes in graph is found. a)

2. Which of the following is the most if(!T[w].Known)


commonly used data structure for if(T[v].Dist + C(v,w) < T[w].Dist
implementing Dijkstra’s Algorithm? ) {
Decrease(T[w].Dist to T[
a) Max priority queue v].Dist +C(v,w));
b) Stack T[w].path=v; }
c) Circular queue
d) Min priority queue b)

Answer: d if(T[w].Known)
Explanation: Minimum priority queue is the if(T[v].Dist + C(v,w) < T[w].Dist
) {
most commonly used data structure for Increase (T[w].Dist to T
implementing Dijkstra’s Algorithm because [v].Dist +C(v,w));
the required operations to be performed in T[w].path=v; }
Dijkstra’s Algorithm match with specialty of
a minimum priority queue. c)

3. What is the time complexity of Dijikstra’s if(!T[w].Known)


if(T[v].Dist + C(v,w) > T[w].Dist
algorithm? ) {
a) O(N) Decrease(T[w].Dist to T[
b) O(N3) v].Dist +C(v,w);
T[w].path=v; }
c) O(N2)
d) O(logN) d)
Answer: c if(T[w].Known)
Explanation: Time complexity of Dijkstra’s if(T[v].Dist + C(v,w) < T[w].Dist
) {

Downloaded From: https://cse-r17.blogspot.com 89


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Increase(T[w].Dist to T[ c) Number of vertices – 1


v].Dist); d) Number of edges – 1
T[w].path=v; }

Answer: a Answer: b
Explanation: If the known value of the Explanation: If the total number of edges in
adjacent vertex(w) is not set then check all adjacency list is E, then there will be a
whether the sum of distance from source total of E number of iterations, hence there
vertex(v) and cost to travel from source to will be a total of at most E decrease key
adjacent vertex is less than the existing operations.
distance of the adjacent node. If so, perform
decrease key operation. 9. What is running time of Dijkstra’s
algorithm using Binary min- heap method?
a) O(V)
b) O(VlogV)
6. How many priority queue operations are c) O(E)
involved in Dijkstra’s Algorithm? d) O(ElogV)
a) 1
Answer: d
b) 3
Explanation: Time required to build a binary
c) 2
min heap is O(V). Each decrease key
d) 4
operation takes O(logV) and there are still at
Answer: b most E such operations. Hence total running
Explanation: The number of priority queue time is O(ElogV).
operations involved is 3. They are insert,
10. The running time of Bellmann Ford
extract-min and decrease key.
algorithm is lower than that of Dijkstra’s
7. How many times the insert and extract min Algorithm.
operations are invoked per vertex? a) True
a) 1 b) False
b) 2
Answer: b
c) 3
Explanation: The number of iterations
d) 0
involved in Bellmann Ford Algorithm is more
Answer: a than that of Dijkstra’s Algorithm.
Explanation: Insert and extract min
operations are invoked only once per vertex 11. Dijkstra’s Algorithm run on a weighted,
because each vertex is added only once to the directed graph G={V,E} with non-negative
set and each edge in the adjacency list is weight function w and source s, terminates
examined only once during the course of with d[u]=delta(s,u) for all vertices u in V.
a) True
algorithm.
b) False
8. The maximum number of times the
decrease key operation performed in Answer: a
Dijkstra’s algorithm will be equal to Explanation: The equality d[u]=delta(s,u)
___________ holds good when vertex u is added to set S
a) Total number of vertices and this equality is maintained thereafter by
b) Total number of edges the upper bound property.

Downloaded From: https://cse-r17.blogspot.com 90


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

12. Given pseudo code of Dijkstra’s g to e, cost is 4


Algorithm. e to f, cost is 1
hence total cost 1+4+1=6.
1. //Initialise single source(G,s)
2. S=0 14. In the given graph:
3. Q=V[G]
4. While Q != 0
5. Do u=extract-min(Q)
6. S=S union {u}
7. For each vertex v in adj[
u]
8. Do relax(u,v,w)

What happens when while loop in line 4 is


changed to while Q>1?
a) While loop gets executed for v times
b) While loop gets executed for v-1 times Identify the shortest path having minimum
c) While loop gets executed only once cost to reach vertex E if A is the source vertex
d) While loop does not get executed a) a-b-e
b) a-c-e
Answer: b c) a-c-d-e
Explanation: In the normal execution of d) a-c-d-b-e
Dijkstra’s Algorithm, the while loop gets
executed V times. The change in the while Answer: b
loop statement causes it to execute only V – 1 Explanation: The minimum cost required to
times. travel from vertex A to E is via vertex C
A to C, cost= 3
13. Consider the following graph. C to E, cost= 2
Hence the total cost is 5.

15. Dijkstra’s Algorithm is the prime example


for ___________
a) Greedy algorithm
b) Branch and bound
c) Back tracking
d) Dynamic programming

If b is the source vertex, what is the minimum Answer: a


cost to reach f vertex? Explanation: Dijkstra’s Algorithm is the
a) 8 prime example for greedy algorithms because
b) 9 greedy algorithms generally solve a problem
c) 4 in stages by doing what appears to be the best
d) 6 thing at each stage.

Answer: d
Explanation: The minimum cost to reach f 1. The Bellmann Ford algorithm returns
vertex from b vertex is 6 by having vertices g _______ value.
and e as intermediates. a) Boolean
b to g, cost is 1 b) Integer

Downloaded From: https://cse-r17.blogspot.com 91


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

c) String 5. What is the running time of Bellmann Ford


d) Double Algorithm?
a) O(V)
Answer: a b) O(V2)
Explanation: The Bellmann Ford algorithm c) O(ElogV)
returns Boolean value whether there is a d) O(VE)
negative weight cycle that is reachable from
the source. Answer: d

M
Explanation: Bellmann Ford algorithm runs
2. Bellmann ford algorithm provides solution in time O(VE), since the initialization takes
for ____________ problems. O(V) for each of V-1 passes and the for loop

O
a) All pair shortest path in the algorithm takes O(E) time. Hence the
b) Sorting total time taken by the algorithm is O(VE).

C
c) Network flow
d) Single source shortest path 6. How many times the for loop in the

T.
Bellmann Ford Algorithm gets executed?
Answer: d a) V times
Explanation: Bellmann ford algorithm is

O
b) V-1
used for finding solutions for single source c) E
shortest path problems. If the graph has no
negative cycles that are reachable from the
source then the algorithm produces the
shortest paths and their weights.
SP
d) E-1

Answer: b
Explanation: The for loop in the Bellmann
G
Ford Algorithm gets executed for V-1 times.
3. Bellmann Ford algorithm is used to After making V-1 passes, the algorithm
LO

indicate whether the graph has negative checks for a negative weight cycle and
weight cycles or not. returns appropriate boolean value.
a) True
b) False
.B

7. Dijikstra’s Algorithm is more efficient than


Bellmann Ford Algorithm.
Answer: a a) True
17

Explanation: Bellmann Ford algorithm b) False


returns true if the graph does not have any
negative weight cycles and returns false when Answer: a
the graph has negative weight cycles.
-R

Explanation: The running time of Bellmann


Ford Algorithm is O(VE) whereas Dijikstra’s
4. How many solution/solutions are available
Algorithm has running time of only O(V2).
SE

for a graph having negative weight cycle?


a) One solution
8. Identify the correct Bellmann Ford
b) Two solutions Algorithm.
c) No solution
C

a)
d) Infinite solutions
for i=1 to V[g]-1
Answer: c do for each edge (u,v) in E[g]
Explanation: If the graph has any negative do Relax(u,v,w)
weight cycle then the algorithm indicates that for each edge (u,v) in E[g]
no solution exists for that graph. do if d[v]>d[u]+w(u,v)
then return False
return True

Downloaded From: https://cse-r17.blogspot.com 92


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

b) 10. Bellmann Ford Algorithm can be applied


for _____________
for i=1 to V[g]-1 a) Undirected and weighted graphs
for each edge (u,v) in E[g]
do if d[v]>d[u]+w(u,v)
b) Undirected and unweighted graphs
then return False c) Directed and weighted graphs
return True d) All directed graphs

c) Answer: c
Explanation: Bellmann Ford Algorithm can
for i=1 to V[g]-1 be applied for all directed and weighted
do for each edge (u,v) in E[g] graphs. The weight function in the graph may
do Relax(u,v,w)
for each edge (u,v) in E[g] either be positive or negative.
do if d[v]<d[u]+w(u,v)
then return true 11. Bellmann Ford algorithm was first
return True proposed by ________
a) Richard Bellmann
d) b) Alfonso Shimbe
c) Lester Ford Jr
for i=1 to V[g]-1
do for each edge (u,v) in E[g]
d) Edward F. Moore
do Relax(u,v,w)
return True Answer: b
Explanation: Alfonso Shimbe proposed
Answer: a Bellmann Ford algorithm in the year 1955.
Explanation: After initialization, the Later it was published by Richard Bellmann
algorithm makes v-1 passes over the edges of in 1957 and Lester Ford Jr in the year 1956.
the graph. Each pass is one iteration of the for Hence it is called Bellmann Ford Algorithm.
loop and consists of relaxing each edge of the
graph once. Then it checks for the negative 12. Consider the following graph:
weight cycle and returns an appropriate
Boolean value.

9. What is the basic principle behind


Bellmann Ford Algorithm?
a) Interpolation
b) Extrapolation
c) Regression
d) Relaxation

Answer: d What is the minimum cost to travel from node


Explanation: Relaxation methods which are A to node C
also called as iterative methods in which an a) 5
approximation to the correct distance is b) 2
replaced progressively by more accurate c) 1
values till an optimum solution is found. d) 3

Downloaded From: https://cse-r17.blogspot.com 93


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: b 15. A graph is said to have a negative weight


Explanation: The minimum cost to travel cycle when?
from node A to node C is 2. a) The graph has 1 negative weighted edge
A-D, cost=1 b) The graph has a cycle
D-B, cost=-2 c) The total weight of the graph is negative
B-C, cost=3 d) The graph has 1 or more negative weighted
Hence the total cost is 2. edges

13. In the given graph: Answer: c


Explanation: When the total weight of the
graph sums up to a negative number then the
graph is said to have a negative weight cycle.
Bellmann Ford Algorithm provides no
solution for such graphs.

1. Floyd Warshall’s Algorithm is used for


Identify the path that has minimum cost to solving ____________
travel from node a to node f a) All pair shortest path problems
a) a-b-c-f b) Single Source shortest path problems
b) a-d-e-f c) Network flow problems
c) a-d-b-c-f d) Sorting problems
d) a-d-b-c-e-f
Answer: a
Answer: d Explanation: Floyd Warshall’s Algorithm is
Explanation: The minimum cost taken by the used for solving all pair shortest path
path a-d-b-c-e-f is 4. problems. It means the algorithm is used for
a-d, cost=2 finding the shortest paths between all pairs of
d-b, cost=-2 vertices in a graph.
b-c, cost=1
c-e, cost= 2 2. Floyd Warshall’s Algorithm can be applied
e-f, cost=1 on __________
Hence the total cost is 4. a) Undirected and unweighted graphs
b) Undirected graphs
14. Bellmann Ford Algorithm is an example c) Directed graphs
for ____________ d) Acyclic graphs
a) Dynamic Programming
b) Greedy Algorithms Answer: c
c) Linear Programming Explanation: Floyd Warshall Algorithm can
d) Branch and Bound be applied in directed graphs. From a given
directed graph, an adjacency matrix is framed
Answer: a and then all pair shortest path is computed by
Explanation: In Bellmann Ford Algorithm the Floyd Warshall Algorithm.
the shortest paths are calculated in bottom up
manner which is similar to other dynamic 3. What is the running time of the Floyd
programming problems. Warshall Algorithm?
a) Big-oh(V)
b) Theta(V2)

Downloaded From: https://cse-r17.blogspot.com 94


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

c) Big-Oh(VE) The procedure returns the matrix D(n) of the


d) Theta(V3) shortest path weights.

Answer: d 7. Floyd- Warshall algorithm was proposed


Explanation: The running time of the Floyd by ____________
Warshall algorithm is determined by the triply a) Robert Floyd and Stephen Warshall
nested for loops. Since each execution of the b) Stephen Floyd and Robert Warshall
for loop takes O(1) time, the algorithm runs c) Bernad Floyd and Robert Warshall
in time Theta(V3). d) Robert Floyd and Bernad Warshall

4. What approach is being followed in Floyd Answer: a


Warshall Algorithm? Explanation: Floyd- Warshall Algorithm was
proposed by Robert Floyd in the year 1962.
a) Greedy technique
The same algorithm was proposed by Stephen
b) Dynamic Programming
Warshall during the same year for finding the
c) Linear Programming
transitive closure of the graph.
d) Backtracking
8. Who proposed the modern formulation of
Answer: b
Floyd-Warshall Algorithm as three nested
Explanation: Floyd Warshall Algorithm
loops?
follows dynamic programming approach
a) Robert Floyd
because the all pair shortest paths are
b) Stephen Warshall
computed in bottom up manner.
c) Bernard Roy
5. Floyd Warshall Algorithm can be used for d) Peter Ingerman
finding _____________
a) Single source shortest path Answer: d
Explanation: The modern formulation of
b) Topological sort
Floyd-Warshall Algorithm as three nested for-
c) Minimum spanning tree
loops was proposed by Peter Ingerman in the
d) Transitive closure
year 1962.
Answer: d
9. Complete the program.
Explanation: One of the ways to compute the
transitive closure of a graph in Theta(N3) n=rows[W]
time is to assign a weight of 1 to each edge of D(0)=W
E and then run the Floyd Warshall Algorithm. for k=1 to n
do for i=1 to n
do for j=1 to n
6. What procedure is being followed in Floyd do _____________________
Warshall Algorithm? ___________
a) Top down return D(n)
b) Bottom up
c) Big bang a) dij(k)=min(dij(k-1), dik(k-1) – dkj(k-1))
d) Sandwich b) dij(k)=max(dij(k-1), dik(k-1) – dkj(k-1))
c) dij(k)=min(dij(k-1), dik(k-1) + dkj(k-1))
Answer: b d) dij(k)=max(dij(k-1), dik(k-1) + dkj(k-1))
Explanation: Bottom up procedure is being
used to compute the values of the matrix Answer: c
elements dij(k). The input is an n x n matrix. Explanation: In order to compute the shortest
path from vertex i to vertex j, we need to find

Downloaded From: https://cse-r17.blogspot.com 95


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

the minimum of 2 values which are dij(k-1) 13. In the given graph
and sum of dik(k-1) and dkj(k-1).

10. What happens when the value of k is 0 in


the Floyd Warshall Algorithm?
a) 1 intermediate vertex
b) 0 intermediate vertex
c) N intermediate vertices
d) N-1 intermediate vertices

Answer: b
Explanation: When k=0, a path from vertex i
to vertex j has no intermediate vertices at all.
Such a path has at most one edge and hence What is the minimum cost to travel from
dij(0) = wij. vertex 1 to vertex 3?
a) 3
11. Using logical operator’s instead arithmetic b) 2
operators saves time and space. c) 10
a) True d) -3
b) False
Answer: d
Answer: a Explanation: The minimum cost required to
Explanation: In computers, logical travel from node 1 to node 5 is -3.
operations on single bit values execute faster 1-5, cost is -4
than arithmetic operations on integer words of 5-4, cost is 6
data. 4-3, cost is -5
Hence total cost is -4 + 6 + -5 = -3.
12. The time taken to compute the transitive
14. In the given graph
closure of a graph is Theta(n2).
a) True
b) False

Answer: b
Explanation: The time taken to compute the
transitive closure of a graph is Theta(n3).
Transitive closure can be computed by
assigning weight of 1 to each edge and by
running Floyd Warshall Algorithm.

How many intermediate vertices are required


to travel from node a to node e at a minimum
cost?
a) 2
b) 0
c) 1
d) 3

Downloaded From: https://cse-r17.blogspot.com 96


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: c Answer: d
Explanation: The minimum cost to travel Explanation: A problem that can be solved
from node a to node e is 1 by passing via using dynamic programming possesses
nodes b and c. overlapping subproblems as well as optimal
a-b, cost 5 substructure properties.
b-c, cost 3
c-e, cost -7 2. If an optimal solution can be created for a
Hence the total cost is 1. problem by constructing optimal solutions for
its subproblems, the problem possesses
15. What is the formula to compute the ____________ property.
transitive closure of a graph? a) Overlapping subproblems
a) tij(k) = tij(k-1) AND (tik(k-1) OR tkj(k-1)) b) Optimal substructure
b) tij(k) = tij(k-1) OR (tik(k-1) AND tkj(k-1)) c) Memoization
c) tij(k) = tij(k-1) AND (tik(k-1) AND tkj(k- d) Greedy
1))
d) tij(k) = tij(k-1) OR (tik(k-1) OR tkj(k-1)) Answer: b
Explanation: Optimal substructure is the
Answer: b property in which an optimal solution is
Explanation: Transitive closure of a graph found for the problem by constructing
can be computed by using Floyd Warshall optimal solutions for the subproblems.
algorithm. This method involves substitution
of logical operations (logical OR and logical 3. If a problem can be broken into
AND) for arithmetic operations min and + in subproblems which are reused several times,
Floyd Warshall Algorithm. the problem possesses ____________
Floyd Warshall Algorithm: dij(k)=min(dij(k- property.
1), dik(k-1) + dkj(k-1)) a) Overlapping subproblems
Transitive closure: tij(k)= tij(k-1) OR (tik(k- b) Optimal substructure
1) AND tkj(k-1)). c) Memoization
d) Greedy

Answer: a
Explanation: Overlapping subproblems is the
property in which value of a subproblem is
UNIT III DYNAMIC used several times.
PROGRAMMING AND
4. If a problem can be solved by combining
GREEDY TECHNIQUE optimal solutions to non-overlapping
problems, the strategy is called
1. Which of the following is/are _____________
property/properties of a dynamic a) Dynamic programming
programming problem? b) Greedy
a) Optimal substructure c) Divide and conquer
b) Overlapping subproblems d) Recursion
c) Greedy approach
d) Both optimal substructure and overlapping Answer: c
subproblems Explanation: In divide and conquer, the
problem is divided into smaller non-
overlapping subproblems and an optimal

Downloaded From: https://cse-r17.blogspot.com 97


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

solution for each of the subproblems is found. in which previously calculated values are
The optimal solutions are then combined to stored, so that, these values can be used to
get a global optimal solution. For example, solve other subproblems.
mergesort uses divide and conquer strategy.
8. When a top-down approach of dynamic
5. When dynamic programming is applied to programming is applied to a problem, it
a problem, it takes far less time as compared usually _____________
to other methods that don’t take advantage of a) Decreases both, the time complexity and
overlapping subproblems. the space complexity
a) True b) Decreases the time complexity and
b) False increases the space complexity
c) Increases the time complexity and
Answer: a decreases the space complexity
Explanation: Dynamic programming d) Increases both, the time complexity and the
calculates the value of a subproblem only space complexity
once, while other methods that don’t take
advantage of the overlapping subproblems Answer: b
property may calculate the value of the same Explanation: The top-down approach uses
subproblem several times. So, dynamic the memoization technique which stores the
programming saves the time of recalculation previously calculated values. Due to this, the
and takes far less time as compared to other time complexity is decreased but the space
methods that don’t take advantage of the complexity is increased.
overlapping subproblems property.
9. Which of the following problems is NOT
6. A greedy algorithm can be used to solve all solved using dynamic programming?
the dynamic programming problems. a) 0/1 knapsack problem
a) True b) Matrix chain multiplication problem
b) False c) Edit distance problem
d) Fractional knapsack problem
Answer: b
Explanation: A greedy algorithm gives Answer: d
optimal solution for all subproblems, but Explanation: The fractional knapsack
when these locally optimal solutions are problem is solved using a greedy algorithm.
combined it may NOT result into a globally
optimal solution. Hence, a greedy algorithm 10. Which of the following problems should
CANNOT be used to solve all the dynamic be solved using dynamic programming?
programming problems. a) Mergesort
b) Binary search
7. In dynamic programming, the technique of c) Longest common subsequence
storing the previously calculated values is d) Quicksort
called ___________
a) Saving value property Answer: c
b) Storing value property Explanation: The longest common
c) Memoization subsequence problem has both, optimal
d) Mapping substructure and overlapping subproblems.
Hence, dynamic programming should be used
Answer: c the solve this problem.
Explanation: Memoization is the technique

Downloaded From: https://cse-r17.blogspot.com 98


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

1. The following sequence is a fibonacci Answer: d


sequence: Explanation: The recurrence relation is given
0, 1, 1, 2, 3, 5, 8, 13, 21,….. by fibo(n) = fibo(n – 1) + fibo(n – 2). So, the
Which technique can be used to get the nth time complexity is given by:
fibonacci term? T(n) = T(n – 1) + T(n – 2)
a) Recursion Approximately,
b) Dynamic programming T(n) = 2 * T(n – 1)
c) A single for loop = 4 * T(n – 2)
d) Recursion, Dynamic Programming, For = 8 * T(n – 3)
loops :
:
Answer: d :
Explanation: Each of the above mentioned = 2k * T(n – k)
methods can be used to find the nth fibonacci This recurrence will stop when n – k = 0
term. i.e. n = k
2. Consider the recursive implementation to Therefore, T(n) = 2n * O(0) = 2n
find the nth fibonacci number: Hence, it takes exponential time.
It can also be proved by drawing the
int fibo(int n) recursion tree and counting the number of
if n <= 1 leaves.
return n
return __________ 4. Suppose we find the 8th term using the
recursive implementation. The arguments
Which line would make the implementation
passed to the function calls will be as follows:
complete?
a) fibo(n) + fibo(n) fibonacci(8)
b) fibo(n) + fibo(n – 1)
c) fibo(n – 1) + fibo(n + 1) fibonacci(7) + fibonacci(6)
d) fibo(n – 1) + fibo(n – 2)
fibonacci(6) + fibonacci(5) + fibonacci
(5) + fibonacci(4)
Answer: d
Explanation: Consider the first five terms of fibonacci(5) + fibonacci(4) + fibonacci
the fibonacci sequence: 0,1,1,2,3. The 6th (4) + fibonacci(3) + fibonacci(4) + fibon
term can be found by adding the two previous acci(3) + fibonacci(3) + fibonacci(2)
terms, i.e. fibo(6) = fibo(5) + fibo(4) = 3 + 2
:
= 5. Therefore,the nth term of a fibonacci
sequence would be given by: :
fibo(n) = fibo(n-1) + fibo(n-2).
:
3. What is the time complexity of the
recursive implementation used to find the nth Which property is shown by the above
fibonacci term? function calls?
a) O(1) a) Memoization
b) Optimal substructure
b) O(n2)
c) Overlapping subproblems
c) O(n!)
d) Greedy
d) Exponential

Downloaded From: https://cse-r17.blogspot.com 99


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: c c) O(n2)
Explanation: From the function calls, we can d) O(n3)
see that fibonacci(4) is calculated twice and
fibonacci(3) is calculated thrice. Thus, the Answer: a
same subproblem is solved many times and Explanation: The recursive implementation
hence the function calls show the overlapping doesn’t store any values and calculates every
subproblems property. value from scratch. So, the space complexity
is O(1).
5. What is the output of the following
program? 7. Consider the following code to find the nth
fibonacci term:
#include<stdio.h>
int fibo(int n)
{ int fibo(int n)
if(n<=1) if n == 0
return n; return 0
return fibo(n-1) + fibo(n-2); else
} prevFib = 0
int main() curFib = 1
{ for i : 1 to n-1
int r = fibo(50000); nextFib = prevFib + curFib
printf("%d",r); __________
return 0; __________
} return curFib

a) 1253556389 Complete the above code.


b) 5635632456 a)
c) Garbage value
prevFib = curFib
d) Runtime error
curFib = curFib
Answer: d
Explanation: The value of n is 50000. The b)
function is recursive and it’s time complexity
is exponential. So, the function will be called prevFib = nextFib
almost 250000 times. Now, even though NO curFib = prevFib
variables are stored by the function, the space
required to store the addresses of these c)
function calls will be enormous. Stack
memory is utilized to store these addresses prevFib = curFib
and only a particular amount of stack memory
curFib = nextFib
can be used by any program. So, after a
certain function call, no more stack space will d)
be available and it will lead to stack overflow
causing runtime error. prevFib = nextFib

6. What is the space complexity of the nextFib = curFib


recursive implementation used to find the nth
fibonacci term? Answer: c
a) O(1) Explanation: The lines, prevFib = curFib and
b) O(n) curFib = nextFib, make the code complete.

Downloaded From: https://cse-r17.blogspot.com 100


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: a
Explanation: To calculate the nth term, we
just store the previous term and the current
8. What is the time complexity of the term and then calculate the next term using
following for loop method used to compute these two terms. It takes a constant space to
the nth fibonacci term? store these two terms and hence O(1) is the
answer.
int fibo(int n)
if n == 0
return 0
10. What will be the output when the
else following code is executed?
prevFib = 0
curFib = 1 #include<stdio.h>
for i : 1 to n-1 int fibo(int n)
nextFib = prevFib + curFib {
prevFib = curFib if(n==0)
curFib = nextFib return 0;
return curFib int i;
int prevFib=0,curFib=1;
a) O(1) for(i=1;i<=n-1;i++)
{
b) O(n) int nextFib = prevFib + curFib
c) O(n2) ;
d) Exponential prevFib = curFib;
curFib = nextFib;
}
Answer: b return curFib;
Explanation: To calculate the nth term, the }
for loop runs (n – 1) times and each time a for int main()
loop is run, it takes a constant time. {
Therefore, the time complexity is of the order int r = fibo(10);
printf("%d",r);
of n. return 0;
}
9. What is the space complexity of the
following for loop method used to compute a) 34
the nth fibonacci term? b) 55
c) Compile error
int fibo(int n)
if n == 0
d) Runtime error
return 0
else Answer: b
prevFib = 0 Explanation: The output is the 10th fibonacci
curFib = 1 number, which is 55.
for i : 1 to n-1
nextFib = prevFib + curFib 11. Consider the following code to find the
prevFib = curFib
curFib = nextFib nth fibonacci term using dynamic
return curFib programming:

a) O(1) 1. int fibo(int n)


2. int fibo_terms[100000] //arr to sto
b) O(n)
re the fibonacci numbers
c) O(n2) 3. fibo_terms[0] = 0
d) Exponential 4. fibo_terms[1] = 1
5.

Downloaded From: https://cse-r17.blogspot.com 101


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

6. for i: 2 to n implementation used to compute the nth


7. fibo_terms[i] = fibo_terms[i - 1 fibonacci term?
] + fibo_terms[i - 2]
8.
1. int fibo(int n)
9. return fibo_terms[n]
2. int fibo_terms[100000] //arr to
store the fibonacci numbers
Which property is shown by line 7 of the 3. fibo_terms[0] = 0
above code? 4. fibo_terms[1] = 1
a) Optimal substructure 5.
b) Overlapping subproblems 6. for i: 2 to n
7. fibo_terms[i] = fibo_term
c) Both overlapping subproblems and optimal s[i - 1] + fibo_terms[i - 2]
substructure 8.
d) Greedy substructure 9. return fibo_terms[n]

Answer: a a) O(1)
Explanation: We find the nth fibonacci term b) O(n)
by finding previous fibonacci terms, i.e. by c) O(n2)
solving subproblems. Hence, line 7 shows the d) Exponential
optimal substructure property.
Answer: b
12. Consider the following code to find the Explanation: To calculate the nth term, the
nth fibonacci term using dynamic for loop runs (n – 1) times and each time a for
programming: loop is run, it takes a constant time.
Therefore, the time complexity is of the order
1. int fibo(int n)
2. int fibo_terms[100000] //arr to
of n.
store the fibonacci numbers
3. fibo_terms[0] = 0 14. What is the space complexity of the
4. fibo_terms[1] = 1 following dynamic programming
5. implementation used to compute the nth
6. for i: 2 to n fibonacci term?
7. fibo_terms[i] = fibo_term
s[i - 1] + fibo_terms[i - 2]
1. int fibo(int n)
8.
2. int fibo_terms[100000] //arr to
9. return fibo_terms[n]
store the fibonacci numbers
3. fibo_terms[0] = 0
Which technique is used by line 7 of the 4. fibo_terms[1] = 1
above code? 5.
a) Greedy 6. for i: 2 to n
b) Recursion 7. fibo_terms[i] = fibo_term
s[i - 1] + fibo_terms[i - 2]
c) Memoization
8.
d) Overlapping subproblems 9. return fibo_terms[n]

Answer: c a) O(1)
Explanation: Line 7 stores the current value b) O(n)
that is calculated, so that the value can be c) O(n2)
used later directly without calculating it from d) Exponential
scratch. This is memoization.
Answer: b
13. What is the time complexity of the
Explanation: To calculate the nth term, we
following dynamic programming

Downloaded From: https://cse-r17.blogspot.com 102


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

store all the terms from 0 to n – 1. So, it takes be found by finding optimal solutions for
O(n) space. subproblems). So, dynamic programming can
be used to solve the coin change problem.
15. What will be the output when the
following code is executed? 2. Suppose you have coins of denominations
1, 3 and 4. You use a greedy algorithm, in
#include<stdio. which you choose the largest denomination
int fibo(int n)
{
coin which is not greater than the remaining
int i; sum. For which of the following sums, will
int fibo_terms[100]; the algorithm NOT produce an optimal
fibo_terms[0]=0; answer?
fibo_terms[1]=1; a) 20
for(i=2;i<=n;i++)
b) 12
fibo_terms[i] = fibo_terms[i-2]
+ fibo_terms[i-1]; c) 6
return fibo_terms[n]; d) 5
}
int main() Answer: c
{ Explanation: Using the greedy algorithm,
int r = fibo(8);
printf("%d",r);
three coins {4,1,1} will be selected to make a
return 0; sum of 6. But, the optimal answer is two
} coins {3,3}.

a) 34 3. Suppose you have coins of denominations


b) 55 1,3 and 4. You use a greedy algorithm, in
c) Compile error which you choose the largest denomination
d) 21 coin which is not greater than the remaining
sum. For which of the following sums, will
Answer: d the algorithm produce an optimal answer?
Explanation: The program prints the 8th a) 14
fibonacci term, which is 21. b) 10
c) 6
d) 100
1. You are given infinite coins of
denominations v1, v2, v3,…..,vn and a sum S. Answer: d
The coin change problem is to find the Explanation: Using the greedy algorithm,
minimum number of coins required to get the three coins {4,1,1} will be selected to make a
sum S. This problem can be solved using sum of 6. But, the optimal answer is two
____________ coins {3,3}. Similarly, four coins {4,4,1,1}
a) Greedy algorithm will be selected to make a sum of 10. But, the
b) Dynamic programming optimal answer is three coins {4,3,3}. Also,
c) Divide and conquer five coins {4,4,4,1,1} will be selected to
d) Backtracking make a sum of 14. But, the optimal answer is
four coins {4,4,3,3}. For a sum of 100,
Answer: b twenty-five coins {all 4’s} will be selected
Explanation: The coin change problem has and the optimal answer is also twenty-five
overlapping subproblems(same subproblems coins {all 4’s}.
are solved multiple times) and optimal
substructure(the solution to the problem can 4. Fill in the blank to complete the code.

Downloaded From: https://cse-r17.blogspot.com 103


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

#include<stdio.h> The coin change problem is to find the


int main() minimum number of coins required to get the
{
int coins[10]={1,3,4},lookup[100000
sum S. What is the space complexity of a
]; dynamic programming implementation used
int i,j,tmp,num_coins = 3,sum=100; to solve the coin change problem?
lookup[0]=0; a) O(N)
for(i = 1; i <= sum; i++) b) O(S)
{
int min_coins = i; c) O(N2)
for(j = 0;j < num_coins; j++) d) O(S*N)
{
tmp = i - coins[j]; Answer: b
if(tmp < 0)
Explanation: To get the optimal solution for
continue;
if(lookup[tmp] < min_coin a sum S, the optimal solution is found for
s) each sum less than equal to S and each
______________; solution is stored. So, the space complexity is
} O(S).
lookup[i] = min_coins + 1;
}
printf("%d",lookup[sum]);
7. You are given infinite coins of
return 0; denominations 1, 3, 4. What is the total
} number of ways in which a sum of 7 can be
achieved using these coins if the order of the
a) lookup[tmp] = min_coins coins is not important?
b) min_coins = lookup[tmp] a) 4
c) break b) 3
d) continue c) 5
d) 6
Answer: b
Explanation: min_coins = lookup[tmp] will Answer: c
complete the code. Explanation: A sum of 7 can be achieved in
the following ways:
5. You are given infinite coins of N {1,1,1,1,1,1,1}, {1,1,1,1,3}, {1,3,3},
denominations v1, v2, v3,…..,vn and a sum S. {1,1,1,4}, {3,4}.
The coin change problem is to find the Therefore, the sum can be achieved in 5
minimum number of coins required to get the ways.
sum S. What is the time complexity of a
dynamic programming implementation used 8. You are given infinite coins of
to solve the coin change problem? denominations 1, 3, 4. What is the minimum
a) O(N) number of coins required to achieve a sum of
b) O(S) 7?
c) O(N2) a) 1
d) O(S*N) b) 2
c) 3
Answer: d d) 4
Explanation: The time complexity is
O(S*N). Answer: b
Explanation: A sum of 7 can be achieved by
6. Suppose you are given infinite coins of N using a minimum of two coins {3,4}.
denominations v1, v2, v3,…..,vn and a sum S.

Downloaded From: https://cse-r17.blogspot.com 104


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

9. You are given infinite coins of tmp=i-coins[j];


denominations 5, 7, 9. Which of the following if(tmp<0)
continue;
sum CANNOT be achieved using these if(lookup[tmp] < min_coi
coins? ns)
a) 50 min_coins=lookup[tmp];
b) 21 }
c) 13 lookup[i] = min_coins + 1;
}
d) 23 printf("%d",lookup[sum]);
return 0;
Answer: c }
Explanation: One way to achieve a sum of
50 is to use ten coins of 5. A sum of 21 can be a) 2
achieved by using three coins of 7. One way b) 3
to achieve a sum of 23 is to use two coins of 7 c) 4
and one coin of 9. A sum of 13 cannot be d) 5
achieved.
Answer: b
10. You are given infinite coins of Explanation: The program prints the
denominations 3, 5, 7. Which of the following minimum number of coins required to get a
sum CANNOT be achieved using these sum of 10, which is 3.
coins?
a) 15 12. What is the output of the following
b) 16 program?
c) 17
d) 4 #include<stdio.h>
int main()
{
Answer: d int coins[10]={1,3,4},lookup[100];
Explanation: Sums can be achieved as int i,j,tmp,num_coins = 3,sum=14;
follows: lookup[0]=0;
15 = {5,5,5} for(i=1;i<=sum;i++)
{
16 = {3,3,5,5} int min_coins = i;
17 = {3,7,7} for(j=0;j<num_coins;j++)
we can’t achieve for sum=4 because our {
available denominations are 3,5,7 and sum of tmp=i-coins[j];
any two denominations is greater than 4. if(tmp<0)
continue;
if(lookup[tmp] < min_coi
11. What is the output of the following ns)
program? min_coins=lookup[tmp];
}
#include<stdio.h> lookup[i] = min_coins + 1;
int main() }
{ printf("%d",lookup[sum]);
int coins[10]={1,3,4},lookup[100]; return 0;
int i,j,tmp,num_coins = 3,sum=10; }
lookup[0]=0;
for(i=1;i<=sum;i++) a) 2
{
int min_coins = i;
b) 3
for(j=0;j<num_coins;j++) c) 4
{ d) 5

Downloaded From: https://cse-r17.blogspot.com 105


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: c -1 and therefore, the maximum sub-array sum


Explanation: The program prints the is -1.
minimum number of coins required to get a
sum of 14, which is 4. 4. Consider the following naive method to
find the maximum sub-array sum:

1. Given a one-dimensional array of integers, #include<stdio.h>


int main()
you have to find a sub-array with maximum {
sum. This is the maximum sub-array sum int arr[1000]={2, -1, 3, -4, 1, -2,
problem. Which of these methods can be used -1, 5, -4}, len=9;
to solve the problem? int cur_max, tmp_max, strt_idx, sub_
a) Dynamic programming arr_idx;
cur_max = arr[0];
b) Two for loops (naive method)
for(strt_idx = 0; strt_idx < len; st
c) Divide and conquer rt_idx++)
d) Dynamic programming, naïve method and {
Divide and conquer methods tmp_max=0;
for(sub_arr_idx = strt_idx; sub
Answer: d _arr_idx < len; sub_arr_idx++)
{
Explanation: Dynamic programming, naïve tmp_max +=arr[sub_arr_idx]
method and Divide and conquer methods can ;
be used to solve the maximum sub array sum if(tmp_max > cur_max)
problem. _____________;
}
2. Find the maximum sub-array sum for the }
printf("%d",cur_max);
given elements. return 0;
{2, -1, 3, -4, 1, -2, -1, 5, -4} }
a) 3
b) 5 Which line should be inserted to complete the
c) 8 above code?
d) 6 a) tmp_max = cur_max
b) break
Answer: b c) continue
Explanation: The maximum sub-array sum is d) cur_max = tmp_max
5.
Answer: d
3. Find the maximum sub-array sum for the Explanation: If the tmp_max element is
given elements. greater than the cur_max element, we make
{-2, -1, -3, -4, -1, -2, -1, -5, -4} cur_max equal to tmp_max, i.e. cur_max =
a) -3 tmp_max.
b) 5
c) 3 5. What is the time complexity of the
d) -1 following naive method used to find the
maximum sub-array sum in an array
Answer: d containing n elements?
Explanation: All the elements are negative.
So, the maximum sub-array sum will be equal #include<stdio.h>
to the largest element. The largest element is int main()
{
int arr[1000]={2, -1, 3, -4, 1, -2,

Downloaded From: https://cse-r17.blogspot.com 106


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

-1, 5, -4}, len=9; {


int cur_max, tmp_max, strt_idx, sub_ int arr[1000]={2, -1, 3, -4, 1, -2,
arr_idx; -1, 5, -4}, len=9;
cur_max = arr[0]; int cur_max, tmp_max, strt_idx, sub_
for(strt_idx = 0; strt_idx < len; st arr_idx;
rt_idx++) cur_max = arr[0];
{ for(strt_idx = 0; strt_idx < len; st
tmp_max=0; rt_idx++)
for(sub_arr_idx = strt_idx; sub {
_arr_idx < len; sub_arr_idx++) tmp_max=0;
{ for(sub_arr_idx = strt_idx; sub
tmp_max +=arr[sub_arr_idx] _arr_idx < len; sub_arr_idx++)
; {
if(tmp_max > cur_max) tmp_max +=arr[sub_arr_idx]
_____________; ;
} if(tmp_max > cur_max)
} _____________;
printf("%d",cur_max); }
return 0; }
} printf("%d",cur_max);
return 0;
}
a) O(n2)
b) O(n)
a) O(n2)
c) O(n3) b) O(1)
d) O(1)
c) O(n3)
Answer: a d) O(n)
Explanation: The naive method uses two for
loops. The outer loop runs from 0 to n, Answer: b
i.e. i = 0 : n. Explanation: The naive method uses only a
The inner loop runs from i to n, i.e. j = i : n. constant space. So, the space complexity is
Therefore, the inner loop runs: O(1).
n times when the outer loop runs the first
time. 7. What is the output of the following naive
(n-1) times when the outer loop runs the method used to find the maximum sub-array
sum?
second time.
: #include<stdio.h>
: int main()
: {
2 times when the outer loop runs (n-1)th time. int arr[1000] = {-2, -5, 6, -2, 3, -
1 time when the outer loop runs nth time. 1, 0,-5, 6}, len = 9;
int cur_max, tmp_max, strt_idx, sub_
Therefore, time complexity = n + (n-1) + (n- arr_idx;
2) + …… + 2 + 1 = n * (n + 1) /2 = O(n2). cur_max = arr[0];
for(strt_idx = 0; strt_idx < len; st
6. What is the space complexity of the rt_idx++)
{
following naive method used to find the tmp_max = 0;
maximum sub-array sum in an array for(sub_arr_idx = strt_idx; su
containing n elements? b_arr_idx < len; sub_arr_idx++)
{
#include<stdio.h> tmp_max += arr[sub_arr_id
int main() x];

Downloaded From: https://cse-r17.blogspot.com 107


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

if(tmp_max > cur_max) #include<stdio.h>


cur_max = tmp_max; int max_num(int a,int b)
} {
} if(a> b)
printf("%d",cur_max); return a;
return 0; return b;
} }
int maximum_subarray_sum(int *arr, int le
a) 6 n)
b) 9 {
int sum[len], idx;
c) 7 sum[0] = arr[0];
d) 4 for(idx = 1; idx < len; idx++)
sum[idx] = _____________________
Answer: c __;
Explanation: The naive method prints the int mx = sum[0];
for(idx = 0; idx < len; idx++)
maximum sub-array sum, which is 7. if(sum[idx] > mx)
mx =sum[idx];
8. What is the time complexity of the divide return mx;
and conquer algorithm used to find the }
maximum sub-array sum? int main()
a) O(n) {
int arr[] = {-2, -5, 6, -2, 3, -1,
b) O(logn) 0,-5, 6}, len = 9;
c) O(nlogn) int ans = maximum_subarray_sum(arr,
d) O(n2) len);
printf("%d",ans);
return 0;
Answer: c }
Explanation: The time complexity of the
divide and conquer algorithm used to find the a) max_num(sum[idx – 1] + arr[idx], arr[idx])
maximum sub-array sum is O(nlogn). b) sum[idx – 1] + arr[idx].
c) min_num(sum[idx – 1] + arr[idx], arr[idx])
9. What is the space complexity of the divide d) arr[idx].
and conquer algorithm used to find the
maximum sub-array sum? Answer: a
a) O(n) Explanation: The array “sum” is used to
b) O(1) store the maximum sub-array sum. The
c) O(n!) appropriate way to do this is by using:
d) O(n2) sum[idx] = max_num(sum[idx – 1] + arr[idx],
arr[idx]).
Answer: b
Explanation: The divide and conquer 2. What is the time complexity of the
algorithm uses a constant space. So, the space following dynamic programming algorithm
complexity is O(1). used to find the maximum sub-array sum?

#include<stdio.h>
1. Which line should be inserted in the blank int max_num(int a,int b)
{
to complete the following dynamic if(a> b)
programming implementation of the return a;
maximum sub-array sum problem? return b;
}

Downloaded From: https://cse-r17.blogspot.com 108


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

int maximum_subarray_sum(int *arr, int le for(idx = 0; idx < len; idx++)


n) if(sum[idx] > mx)
{ mx =sum[idx];
int sum[len], idx; return mx;
sum[0] = arr[0]; }
for(idx = 1; idx < len; idx++) int main()
sum[idx] = max_num(sum[idx - 1] {
+ arr[idx], arr[idx]); int arr[] = {-2, -5, 6, -2, 3, -1,
int mx = sum[0]; 0,-5, 6}, len = 9;
for(idx = 0; idx < len; idx++) int ans = maximum_subarray_sum(arr,
if(sum[idx] > mx) len);
mx =sum[idx]; printf("%d",ans);
return mx; return 0;
} }
int main()
{ a) O(n)
int arr[] = {-2, -5, 6, -2, 3, -1, b) O(1)
0,-5, 6}, len = 9;
int ans = maximum_subarray_sum(arr, c) O(n!)
len); d) O(n2)
printf("%d",ans);
return 0; Answer: a
}
Explanation: The above dynamic
a) O(n) programming algorithm uses space equal to
b) O(logn) the length of the array to store the sum values.
c) O(nlogn) So, the space complexity is O(n).
d) O(n2) 4. Consider the following code snippet:
Answer: a 1. int sum[len], idx;
Explanation: The time complexity of the 2. sum[0] = arr[0];
above dynamic programming algorithm used 3. for(idx = 1; idx < len; idx++)
to solve maximum sub-array sum is O(n). 4. sum[idx] = max(sum[idx - 1] + a
rr[idx], arr[idx]);
5. int mx = sum[0];
3. What is the space complexity of the 6. for(idx = 0; idx < len; idx++)
following dynamic programming algorithm 7. if(sum[idx] > mx)
used to find the maximum sub-array sum? 8. mx =sum[idx];
9. return mx;
#include<stdio.h>
int max_num(int a,int b) Which property is shown by line 4 of the
{ above code snippet?
if(a> b) a) Optimal substructure
return a;
return b; b) Overlapping subproblems
} c) Both overlapping subproblems and optimal
int maximum_subarray_sum(int *arr, int le substructure
n) d) Greedy substructure
{
int sum[len], idx;
sum[0] = arr[0];
Answer: a
for(idx = 1; idx < len; idx++) Explanation: The current sum (i.e. sum[idx])
sum[idx] = max_num(sum[idx - 1] uses the previous sum (i.e. sum[idx – 1]) to
+ arr[idx], arr[idx]); get an optimal value. So, line 4 shows the
int mx = sum[0]; optimal substructure property.

Downloaded From: https://cse-r17.blogspot.com 109


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

5. Consider the following code snippet: n)


{
1. int sum[len], idx; int sum[len], idx;
2. sum[0] = arr[0]; sum[0] = arr[0];
3. for(idx = 1; idx < len; idx++) for(idx = 1; idx < len; idx++)
4. sum[idx] = max(sum[idx - 1] + a sum[idx] = max_num(sum[idx - 1] +
rr[idx], arr[idx]); arr[idx], arr[idx]);
5. int mx = sum[0]; int mx = sum[0];
6. for(idx = 0; idx < len; idx++) for(idx = 0; idx < len; idx++)
7. if(sum[idx] > mx) if(sum[idx] > mx)
8. mx =sum[idx]; mx =sum[idx];
9. return mx; return mx;
}
int main()
Which method is used by line 4 of the above {
code snippet? int arr[] = {-20, 23, 10, 3, -10, 11
a) Divide and conquer , -5},len = 7;
b) Recursion int ans = maximum_subarray_sum(arr,
c) Both memoization and divide and conquer len);
printf("%d",ans);
d) Memoization return 0;
}
Answer: d
Explanation: The array “sum” is used to a) 27
store the previously calculated values, so that b) 37
they aren’t recalculated. So, line 4 uses the c) 36
memoization technique. d) 26
6. Find the maximum sub-array sum for the Answer: b
following array: Explanation: The program prints the value of
{3, 6, 7, 9, 3, 8} maximum sub-array sum, which is 37.
a) 33
b) 36 8. What is the value stored in sum[4] after the
c) 23 following program is executed?
d) 26
#include<stdio.h>
Answer: b int max_num(int a,int b)
Explanation: All the elements of the array {
if(a> b)
are positive. So, the maximum sub-array sum return a;
is equal to the sum of all the elements, which return b;
is 36. }
int maximum_subarray_sum(int *arr, int le
7. What is the output of the following n)
{
program?
int sum[len], idx;
sum[0] = arr[0];
#include<stdio.h> for(idx = 1; idx < len; idx++)
int max_num(int a,int b) sum[idx] = max_num(sum[idx - 1
{ ] + arr[idx], arr[idx]);
if(a> b) int mx = sum[0];
return a; for(idx = 0; idx < len; idx++)
return b; if(sum[idx] > mx)
} mx =sum[idx];
int maximum_subarray_sum(int *arr, int le return mx;

Downloaded From: https://cse-r17.blogspot.com 110


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

} a) {0,1,2,3}
int main() b) {-1,0,1}
{
int arr[] = {-2, 14, 11, -13, 10, -
c) {-1,-2,-3,0}
5, 11, -6, 3, -5},len = 10; d) {-4,-3,-2,-1}
int ans = maximum_subarray_sum(arr,
len); Answer: d
printf("%d",ans); Explanation: Kadane’s algorithm works if
return 0; the input array contains at least one non-
}
negative element. Every element in the array
a) 28 {-4,-3,-2,-1} is negative. Hence Kadane’s
b) 25 algorithm won’t work.
c) 22
d) 12 4. For which of the following inputs would
Kadane’s algorithm produce a WRONG
Answer: c output?
Explanation: After the program is executed a) {1,0,-1}
the value stored in sum[4] is 22. b) {-1,-2,-3}
Note: You are asked to find the value stored c) {1,2,3}
in sum[4] and NOT the output of the d) {0,0,0}
program.
Answer: b
Explanation: Kadane’s algorithm doesn’t
1. Kadane’s algorithm is used to find work for all negative numbers. So, the answer
____________ is {-1,-2,-3}.
a) Longest increasing subsequence
5. Complete the following code for Kadane’s
b) Longest palindrome subsequence
algorithm:
c) Maximum sub-array sum
d) Longest decreasing subsequence #include<stdio.h>
int max_num(int a, int b)
Answer: c {
Explanation: Kadane’s algorithm is used to if(a > b)
find the maximum sub-array sum for a given return a;
return b;
array.
}
int kadane_algo(int *arr, int len)
2. Kadane’s algorithm uses which of the {
following techniques? int ans, sum, idx;
a) Divide and conquer ans =0;
b) Dynamic programming sum =0;
for(idx =0; idx < len; idx++)
c) Recursion {
d) Greedy algorithm sum = max_num(0,sum + arr[idx]);
ans = ___________;
Answer: b }
Explanation: Kadane’s algorithm uses return ans;
dynamic programming. }
int main()
{
3. For which of the following inputs would int arr[] = {-2, -3, 4, -1, -2, 1, 5
Kadane’s algorithm produce the , -3},len=7;
INCORRECT output? int ans = kadane_algo(arr,len);

Downloaded From: https://cse-r17.blogspot.com 111


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

printf("%d",ans); {
return 0; int ans, sum, idx;
} ans =0;
sum =0;
a) max_num(sum, sum + arr[idx]) for(idx =0; idx < len; idx++)
b) sum {
sum = max_num(0,sum + arr[id
c) sum + arr[idx] x]);
d) max_num(sum,ans) ans = max_num(sum,ans);
}
Answer: d return ans;
Explanation: The maximum of sum and ans, }
int main()
is stored in ans. So, the answer is {
max_num(sum, ans). int arr[] = {2, 3, -3, -1, 2, 1, 5,
-3}, len = 8;
6. What is the time complexity of Kadane’s int ans = kadane_algo(arr,len);
algorithm? printf("%d",ans);
a) O(1) return 0;
}
b) O(n)
c) O(n2) a) 6
d) O(5) b) 7
c) 8
Answer: b d) 9
Explanation: The time complexity of
Kadane’s algorithm is O(n) because there is Answer: d
only one for loop which scans the entire array Explanation: Kadane’s algorithm produces
exactly once. the maximum sub-array sum, which is equal
to 9.
7. What is the space complexity of Kadane’s
algorithm? 9. What is the output of the following
a) O(1) implementation of Kadane’s algorithm?
b) O(n)
c) O(n2) #include<stdio.h>
int max_num(int a, int b)
d) None of the mentioned {
if(a > b)
Answer: a return a;
Explanation: Kadane’s algorithm uses a return b;
constant space. So, the space complexity is }
O(1). int kadane_algo(int *arr, int len)
{
int ans, sum, idx;
8. What is the output of the following ans =0;
implementation of Kadane’s algorithm? sum =0;
for(idx =0; idx < len; idx++)
#include<stdio.h> {
int max_num(int a, int b) sum = max_num(0,sum + arr[idx])
{ ;
if(a > b) ans = max_num(sum,ans);
return a; }
return b; return ans;
} }
int kadane_algo(int *arr, int len) int main()

Downloaded From: https://cse-r17.blogspot.com 112


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

{ Change 1 = Line 10: int sum = arr


int arr[] = {-2, -3, -3, -1, -2, -1 [0], ans = arr[0]
, -5, -3},len = 8; Change 2 = Line 13: sum = max_num
int ans = kadane_algo(arr,len); (arr[idx],sum+arr[idx])
printf("%d",ans);
return 0; a) Only Change 1 is sufficient
} b) Only Change 2 is sufficient
c) Both Change 1 and Change 2 are necessary
a) 1
d) No change is required
b) -1
c) -2 Answer: c
d) 0 Explanation: Both change 1 and change 2
should be made to Kadane’s algorithm so that
Answer: d
it produces the right output even when all the
Explanation: Kadane’s algorithm produces a
array elements are negative.
wrong output when all the elements are
negative. The output produced is 0.
1. The longest increasing subsequence
10. Consider the following implementation of
problem is a problem to find the length of a
Kadane’s algorithm:
subsequence from a sequence of array
1. #include<stdio.h> elements such that the subsequence is sorted
2. int max_num(int a, int b) in increasing order and it’s length is
3. { maximum. This problem can be solved using
4. if(a > b) __________
5. return a;
a) Recursion
6. return b;
7. } b) Dynamic programming
8. int kadane_algo(int *arr, int len) c) Brute force
9. { d) Recursion, Dynamic programming, Brute
10. int ans = 0, sum = 0, idx; force
11. for(idx =0; idx < len; idx++)
12. {
13. sum = max_num(0,sum + arr
Answer: d
[idx]); Explanation: The longest increasing
14. ans = max_num(sum,ans); subsequence problem can be solved using all
15. } of the mentioned methods.
16. return ans;
17. } 2. Find the longest increasing subsequence
18. int main()
19. { for the given sequence:
20. int arr[] = {-2, -3, -3, -1, -2 {10, -10, 12, 9, 10, 15, 13, 14}
, -1, -5, -3},len = 8; a) {10, 12, 15}
21. int ans = kadane_algo(arr,len); b) {10, 12, 13, 14}
22. printf("%d",ans); c) {-10, 12, 13, 14}
23. return 0;
24. } d) {-10, 9, 10, 13, 14}

What changes should be made to the Answer: d


Kadane’s algorithm so that it produces the Explanation: The longest increasing
right output even when all array elements are subsequence is {-10, 9, 10, 13, 14}.
negative?
3. Find the length of the longest increasing
subsequence for the given sequence:

Downloaded From: https://cse-r17.blogspot.com 113


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

{-10, 24, -9, 35, -21, 55, -41, 76, 84} subsequence is found. What is the time
a) 5 complexity of this brute force
b) 4 implementation?
c) 3 a) O(n)
d) 6 b) O(n2)
c) O(n!)
Answer: d
Explanation: The longest increasing d) O(2n)
subsequence is {-10, 24, 35, 55, 76, 84} and Answer: d
it’s length is 6. Explanation: The time required to find all the
4. For any given sequence, there will subsequences of a given sequence is 2n,
ALWAYS be a unique increasing where ‘n’ is the number of elements in the
subsequence with the longest length. sequence. So, the time complexity is O(2n).
a) True
b) False 7. Complete the following dynamic
programming implementation of the longest
Answer: b increasing subsequence problem:
Explanation: For a given sequence, it is
possible that there is more than one #include<stdio.h>
int longest_inc_sub(int *arr, int len)
subsequence with the longest length.
{
Consider, the following sequence: int i, j, tmp_max;
{10,11,12,1,2,3}: int LIS[len]; // array to store th
There are two longest increasing e lengths of the longest increasing subse
subsequences: {1,2,3} and {10,11,12}. quence
LIS[0]=1;
for(i = 1; i < len; i++)
5. The number of increasing subsequences {
with the longest length for the given sequence tmp_max = 0;
are: for(j = 0; j < i; j++)
{10, 9, 8, 7, 6, 5} {
a) 3 if(arr[j] < arr[i])
{
b) 4 if(LIS[j] > tmp_max)
c) 5 ___________;
d) 6 }
}
Answer: d LIS[i] = tmp_max + 1;
Explanation: Each array element individually }
int max = LIS[0];
forms a longest increasing subsequence and for(i = 0; i < len; i++)
so, the length of the longest increasing if(LIS[i] > max)
subsequence is 1. So, the number of max = LIS[i];
increasing subsequences with the longest return max;
length is 6. }
int main()
{
6. In the brute force implementation to find int arr[] = {10,22,9,33,21,50,41,60
the longest increasing subsequence, all the ,80}, len = 9;
subsequences of a given sequence are found. int ans = longest_inc_sub(arr, len)
All the increasing subsequences are then ;
printf("%d",ans);
selected and the length of the longest

Downloaded From: https://cse-r17.blogspot.com 114


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

return 0; return 0;
} }

a) tmp_max = LIS[j] a) O(1)


b) LIS[i] = LIS[j] b) O(n)
c) LIS[j] = tmp_max c) O(n2)
d) tmp_max = LIS[i] d) O(nlogn)
Answer: a Answer: c
Explanation: tmp_max is used to store the Explanation: The time complexity of the
maximum length of an increasing above dynamic programming implementation
subsequence for any ‘j’ such that: arr[j] < used to find the length of the longest
arr[i] and 0 < j < i.
increasing subsequence is O(n2).
So, tmp_max = LIS[j] completes the code.
9. What is the space complexity of the
8. What is the time complexity of the
following dynamic programming
following dynamic programming
implementation used to find the length of the
implementation used to find the length of the
longest increasing subsequence?
longest increasing subsequence?
#include<stdio.h>
#include<stdio.h> int longest_inc_sub(int *arr, int len)
int longest_inc_sub(int *arr, int len) {
{ int i, j, tmp_max;
int i, j, tmp_max; int LIS[len]; // array to store th
int LIS[len]; // array to store th e lengths of the longest increasing subse
e lengths of the longest increasing subse quence
quence LIS[0]=1;
LIS[0]=1; for(i = 1; i < len; i++)
for(i = 1; i < len; i++) {
{ tmp_max = 0;
tmp_max = 0; for(j = 0; j < i; j++)
for(j = 0; j < i; j++) {
{ if(arr[j] < arr[i])
if(arr[j] < arr[i]) {
{ if(LIS[j] > tmp_max)
if(LIS[j] > tmp_max) tmp_max = LIS[j];
tmp_max = LIS[j]; }
} }
} LIS[i] = tmp_max + 1;
LIS[i] = tmp_max + 1; }
} int max = LIS[0];
int max = LIS[0]; for(i = 0; i < len; i++)
for(i = 0; i < len; i++) if(LIS[i] > max)
if(LIS[i] > max) max = LIS[i];
max = LIS[i]; return max;
return max; }
} int main()
int main() {
{ int arr[] = {10,22,9,33,21,50,41,60
int arr[] = {10,22,9,33,21,50,41,60 ,80}, len = 9;
,80}, len = 9; int ans = longest_inc_sub(arr, len)
int ans = longest_inc_sub(arr, len) ;
; printf("%d",ans);
printf("%d",ans);

Downloaded From: https://cse-r17.blogspot.com 115


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

return 0; return 0;
} }

a) O(1) a) 3
b) O(n) b) 4
c) O(n2) c) 5
d) O(nlogn) d) 6

Answer: b Answer: d

M
Explanation: The above dynamic Explanation: The program prints the length
programming implementation uses space of the longest increasing subsequence, which

O
equal to the length of the sequence. So, the is 6.
space complexity of the above dynamic
11. What is the value stored in LIS[5] after

C
programming implementation used to find the
length of the longest increasing subsequence the following program is executed?

T.
is O(n).
#include<stdio.h>
int longest_inc_sub(int *arr, int len)
10. What is the output of the following

O
{
program? int i, j, tmp_max;
int LIS[len]; // array to store th
#include<stdio.h>
int longest_inc_sub(int *arr, int len)
{
int i, j, tmp_max;
SP
e lengths of the longest increasing subse
quence
LIS[0]=1;
for(i = 1; i < len; i++)
G
int LIS[len]; // array to store th {
e lengths of the longest increasing subse tmp_max = 0;
LO

quence for(j = 0; j < i; j++)


LIS[0]=1; {
for(i = 1; i < len; i++) if(arr[j] < arr[i])
{ {
.B

tmp_max = 0; if(LIS[j] > tmp_max)


for(j = 0; j < i; j++) tmp_max = LIS[j];
{ }
17

if(arr[j] < arr[i]) }


{ LIS[i] = tmp_max + 1;
if(LIS[j] > tmp_max) }
tmp_max = LIS[j]; int max = LIS[0];
-R

} for(i = 0; i < len; i++)


} if(LIS[i] > max)
LIS[i] = tmp_max + 1; max = LIS[i];
} return max;
SE

int max = LIS[0]; }


for(i = 0; i < len; i++) int main()
if(LIS[i] > max) {
max = LIS[i]; int arr[] = {10,22,9,33,21,50,41,60
C

return max; ,80}, len = 9;


} int ans = longest_inc_sub(arr, len)
int main() ;
{ printf("%d",ans);
int arr[] = {10,22,9,33,21,50,41,60 return 0;
,80}, len = 9; }
int ans = longest_inc_sub(arr, len)
;
printf("%d",ans);

Downloaded From: https://cse-r17.blogspot.com 116


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

a) 2 Answer: c
b) 3 Explanation: The pieces {1,2 2} give the
c) 4 maximum value of 12.
d) 5
3. Consider the brute force implementation of
Answer: c the rod cutting problem in which all the
Explanation: The value stored in LIS[5] after possible cuts are found and the maximum
the program is executed is 4. value is calculated. What is the time
complexity of this brute force
implementation?
1. Given a rod of length n and the selling a) O(n2)
prices of all pieces smaller than equal to n,
b) O(n3)
find the most beneficial way of cutting the
c) O(nlogn)
rod into smaller pieces. This problem is called
the rod cutting problem. Which of these d) O(2n)
methods can be used to solve the rod cutting
problem? Answer: d
a) Brute force Explanation: The brute force implementation
b) Dynamic programming finds all the possible cuts. This takes O(2n)
c) Recursion time.
d) Brute force, Dynamic programming and
Recursion 4. You are given a rod of length 10 and the
following prices.
Answer: d
Explanation: Brute force, Dynamic length price
programming and Recursion can be used to 1 2
solve the rod cutting problem.
2 5
2. You are given a rod of length 5 and the
prices of each length are as follows: 3 6

length price 4 9

1 2 5 9

2 5 6 17

3 6 7 17

4 9 8 18

5 9 9 20

10 22
What is the maximum value that you can get
after cutting the rod and selling the pieces? Which of these pieces give the maximum
a) 10 price?
b) 11 a) {1,2,7}
c) 12 b) {10}
d) 13 c) {2,2,6}
d) {1,4,5}

Downloaded From: https://cse-r17.blogspot.com 117


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: c #include<stdio.h>
Explanation: The pieces {2,2,6} give the #include<limits.h>
int max_of_two(int a, int b)
maximum value of 27. {
if(a > b)
5. Consider the following recursive return a;
implementation of the rod cutting problem: return b;
}
#include<stdio.h> int rod_cut(int *prices, int len)
#include<limits.h> {
int max_of_two(int a, int b) int max_price = INT_MIN; // INT_MIN
{ is the min value an integer can take
if(a > b) int i;
return a; if(len <= 0 )
return b; return 0;
} for(i = 0; i < len; i++)
int rod_cut(int *prices, int len) max_price = max_of_two(max_price
{ , prices[i] + rod_cut(prices,len - i - 1)
int max_price = INT_MIN; // INT_MIN ); // subtract 1 because index starts fro
is the min value an integer can take m 0
int i; return max_price;
if(len <= 0 ) }
return 0; int main()
for(i = 0; i < len; i++) {
max_price = max_of_two(_________ int prices[]={2, 5, 6, 9, 9, 17, 17
____); // subtract 1 because index starts , 18, 20, 22},len_of_rod = 10;
from 0 int ans = rod_cut(prices, len_of_ro
return max_price; d);
} printf("%d",ans);
int main() return 0;
{ }
int prices[]={2, 5, 6, 9, 9, 17, 17
, 18, 20, 22},len_of_rod = 10; a) O(n)
int ans = rod_cut(prices, len_of_ro
d);
b) O(n2)
printf("%d",ans); c) O(n3)
return 0;
}
d) O(2n)

Complete the above code. Answer: d


a) max_price, prices[i] + rod_cut(prices,len – Explanation: The time complexity of the
i – 1) above recursive implementation is O(2n).
b) max_price, prices[i – 1].
c) max_price, rod_cut(prices, len – i – 1) 7. What is the space complexity of the
d) max_price, prices[i – 1] + following recursive implementation?
rod_cut(prices,len – i – 1)
#include<stdio.h>
#include<limits.h>
Answer: a int max_of_two(int a, int b)
Explanation: max_price, prices[i] + {
rod_cut(prices,len – i – 1) completes the if(a > b)
above code. return a;
return b;
}
6. What is the time complexity of the int rod_cut(int *prices, int len)
following recursive implementation? {

Downloaded From: https://cse-r17.blogspot.com 118


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

int max_price = INT_MIN; // INT_MIN return max_price;


is the min value an integer can take }
int i; int main()
if(len <= 0 ) {
return 0; int prices[]={2, 5, 6, 9, 9, 17, 1
for(i = 0; i < len; i++) 7, 18, 20, 22},len_of_rod = 3;
max_price = max_of_two(max_price int ans = rod_cut(prices, len_of_r
, prices[i] + rod_cut(prices,len - i - 1) od);
); // subtract 1 because index starts fro printf("%d",ans);
m 0 return 0;
return max_price; }
}
int main() a) 5
{ b) 6
int prices[]={2, 5, 6, 9, 9, 17, 17
, 18, 20, 22},len_of_rod = 10; c) 7
int ans = rod_cut(prices, len_of_ro d) 8
d);
printf("%d",ans); Answer: c
return 0; Explanation: The value stored in max_value
}
after the code is executed is equal to 7.
a) O(1)
9. For every rod cutting problem there will be
b) O(logn)
a unique set of pieces that give the maximum
c) O(nlogn)
price.
d) O(n!)
a) True
Answer: a b) False
Explanation: The space complexity of the
Answer: b
above recursive implementation is O(1)
Explanation: Consider a rod of length 3. The
because it uses a constant space.
prices are {2,3,6} for lengths {1,2,3}
8. What will be the value stored in max_value respectively. The pieces {1,1,1} and {3} both
when the following code is executed? give the maximum value of 6.

#include<stdio.h> 10.Consider the following dynamic


#include<limits.h> programming implementation of the rod
int max_of_two(int a, int b) cutting problem:
{
if(a > b) #include<stdio.h>
return a; #include<limits.h>
return b; int rod_cut(int *prices, int len)
} {
int rod_cut(int *prices, int len) int max_val[len + 1];
{ int i,j,tmp_price,tmp_idx;
int max_price = INT_MIN; // INT_MI max_val[0] = 0;
N is the min value an integer can take for(i = 1; i <= len; i++)
int i; {
if(len <= 0 ) int tmp_max = INT_MIN; // mini
return 0; mum value an integer can hold
for(i = 0; i < len; i++) for(j = 1; j <= i; j++)
max_price = max_of_two(prices[i {
] + rod_cut(prices,len - i - 1), max_pric tmp_idx = i - j;
e); // subtract 1 because index starts fr tmp_price = ____________
om 0 _; //subtract 1 because index of prices s

Downloaded From: https://cse-r17.blogspot.com 119


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

tarts from 0 }
if(tmp_price > tmp_max) int main()
tmp_max = tmp_price; {
} int prices[]={2, 5, 6, 9, 9, 17, 1
max_val[i] = tmp_max; 7, 18, 20, 22},len_of_rod = 5;
} int ans = rod_cut(prices, len_of_r
return max_val[len]; od);
} printf("%d",ans);
int main() return 0;
{ }
int prices[]={2, 5, 6, 9, 9, 17, 1
7, 18, 20, 22},len_of_rod = 5; a) O(1)
int ans = rod_cut(prices, len_of_r b) O(n)
od);
printf("%d",ans); c) O(n2)
return 0; d) O(2n)
}
Answer: c
Which line will complete the ABOVE code?
Explanation: The time complexity of the
a) prices[j-1] + max_val[tmp_idx]
above dynamic programming implementation
b) prices[j] + max_val[tmp_idx]
c) prices[j-1] + max_val[tmp_idx – 1] of the rod cutting problem is O(n2).
d) prices[j] + max_val[tmp_idx – 1]
12. What is the space complexity of the
Answer: a following dynamic programming
Explanation: prices[j-1] + max_val[tmp_idx] implementation of the rod cutting problem?
completes the code.
#include<stdio.h>
#include<limits.h>
11. What is the time complexity of the int rod_cut(int *prices, int len)
following dynamic programming {
implementation of the rod cutting problem? int max_val[len + 1];
int i,j,tmp_price,tmp_idx;
#include<stdio.h> max_val[0] = 0;
#include<limits.h> for(i = 1; i <= len; i++)
int rod_cut(int *prices, int len) {
{ int tmp_max = INT_MIN; // mini
int max_val[len + 1]; mum value an integer can hold
int i,j,tmp_price,tmp_idx; for(j = 1; j <= i; j++)
max_val[0] = 0; {
for(i = 1; i <= len; i++) tmp_idx = i - j;
{ tmp_price = prices[j-1]
int tmp_max = INT_MIN; // mini + max_val[tmp_idx]; //subtract 1 because
mum value an integer can hold index of prices starts from 0
for(j = 1; j <= i; j++) if(tmp_price > tmp_max)
{ tmp_max = tmp_price;
tmp_idx = i - j; }
tmp_price = prices[j-1] max_val[i] = tmp_max;
+ max_val[tmp_idx]; //subtract 1 because }
index of prices starts from 0 return max_val[len];
if(tmp_price > tmp_max) }
tmp_max = tmp_price; int main()
} {
max_val[i] = tmp_max; int prices[]={2, 5, 6, 9, 9, 17, 1
} 7, 18, 20, 22},len_of_rod = 5;
return max_val[len]; int ans = rod_cut(prices, len_of_r

Downloaded From: https://cse-r17.blogspot.com 120


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

od); a) 9
printf("%d",ans); b) 10
return 0;
}
c) 11
d) 12
a) O(1)
b) O(n) Answer: d
Explanation: The program prints the
c) O(n2)
maximum price that can be achieved by
d) O(2n) cutting the rod into pieces, which is equal to
27.
Answer: b
Explanation: The space complexity of the 14. What is the value stored in max_val[5]
above dynamic programming implementation after the following program is executed?
of the rod cutting problem is O(n) because it
uses a space equal to the length of the rod. #include<stdio.h>
#include<limits.h>
13. What is the output of the following int rod_cut(int *prices, int len)
{
program?
int max_val[len + 1];
int i,j,tmp_price,tmp_idx;
#include<stdio.h> max_val[0] = 0;
#include<limits.h> for(i = 1; i <= len; i++)
int rod_cut(int *prices, int len) {
{ int tmp_max = INT_MIN; // mini
int max_val[len + 1]; mum value an integer can hold
int i,j,tmp_price,tmp_idx; for(j = 1; j <= i; j++)
max_val[0] = 0; {
for(i = 1; i <= len; i++) tmp_idx = i - j;
{ tmp_price = prices[j-1]
int tmp_max = INT_MIN; // mini + max_val[tmp_idx];//subtract 1 because i
mum value an integer can hold ndex of prices starts from 0
for(j = 1; j <= i; j++) if(tmp_price > tmp_max)
{ tmp_max = tmp_price;
tmp_idx = i - j; }
tmp_price = prices[j-1] + max_val[i] = tmp_max;
max_val[tmp_idx];//subtract 1 because ind }
ex of prices starts from 0 return max_val[len];
if(tmp_price > tmp_max) }
tmp_max = tmp_price; int main()
} {
max_val[i] = tmp_max; int prices[]={2, 5, 6, 9, 9, 17, 17
} , 18, 20, 22},len_of_rod = 5;
return max_val[len]; int ans = rod_cut(prices, len_of_ro
} d);
int main() printf("%d",ans);
{ return 0;
int prices[]={2, 5, 6, 9, 9, 17, 17 }
, 18, 20, 22},len_of_rod = 5;
int ans = rod_cut(prices, len_of_ro
d); a) 12
printf("%d",ans); b) 27
return 0; c) 10
} d) 17

Downloaded From: https://cse-r17.blogspot.com 121


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: a return INT_MAX;


Explanation: The value stored in max_val[5] int min = INT_MAX;
for(idx = 1; idx <= arr[strt] && str
after the program is executed is 12. t + idx <= end; idx++)
{
int jumps = min_jumps(____,____
1. You are given an array of elements where ,____) + 1;
each array element represents the if(jumps < min)
MAXIMUM number of jumps that can be min = jumps;
}
made in the forward direction from that return min;
element. You have to find the minimum }
number of jumps that are required to reach int main()
the end of the array. Which of these methods {
can be used to solve the problem? int arr[] ={1, 3, 5, 8, 9, 2, 6, 7,
6},len = 9;
a) Dynamic Programming int ans = min_jumps(arr, 0, len-1);
b) Greedy Algorithm printf("%d\n",ans);
c) Recursion return 0;
d) Recursion and Dynamic Programming }

Answer: d Which of these arguments should be passed


Explanation: Both recursion and dynamic by the min_jumps function represented by the
programming can be used to solve minimum blanks?
number of jumps problem. a) arr, strt + idx, end
b) arr + idx, strt, end
2. Consider the following array: c) arr, strt, end
{1, 3, 5, 8, 9, 2, 6, 7, 6} d) arr, strt, end + idx
What is the minimum number of jumps
required to reach the end of the array? Answer: a
a) 1 Explanation: arr, strt + idx, end should be
b) 2 passed as arguments.
c) 3
d) 4 4. For a given array, there can be multiple
ways to reach the end of the array using
Answer: c minimum number of jumps.
Explanation: The jumps made will be:{1 -> a) True
2 -> 4 -> 9}. So, the number of jumps is b) False
three.
Answer: a
3. Consider the following recursive Explanation: Consider the array {1,2,3,4,5}.
implementation: It is possible to reach the end in the following
ways: {1 -> 2 -> 3 -> 5} or {1 -> 2 -> 4 -> 5}.
#include<stdio.h> In both the cases the number of jumps is 3,
#include<limits.h> which is minimum. Hence, it is possible to
int min_jumps(int *arr, int strt, int end reach the end of the array in multiple ways
)
{ using minimum number of jumps.
int idx;
if(strt == end) 5. What is the output of the following
return 0; program?
if(arr[strt] == 0) // jump cannot be
made

Downloaded From: https://cse-r17.blogspot.com 122


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

#include<stdio.h> In this case, only one element is 0 but it is not


#include<limits.h> possible to reach the end of the array.
int min_jumps(int *arr, int strt, int end
)
{ 7. Consider the following dynamic
int idx; programming implementation of the
if(strt == end) minimum jumps problem:
return 0;
if(arr[strt] == 0) // jump cannot b #include<stdio.h>
e made #include<limits.h>

M
return INT_MAX; int min_jump(int *arr, int len)
int min = INT_MAX; {
for(idx = 1; idx <= arr[strt] && st int j, idx, jumps[len];

O
rt + idx <= end; idx++) jumps[len - 1] = 0;
{ for(idx = len - 2; idx >= 0; idx--)

C
int jumps = min_jumps(arr, str {
t + idx, end) + 1; int tmp_min = INT_MAX;
if(jumps < min)

T.
for(j = 1; j <= arr[idx] && idx
min = jumps; + j < len; j++)
} {
return min; if(jumps[idx + j] + 1 <

O
} tmp_min)
int main() tmp_min = jumps[idx
{
int arr[] ={1, 2, 3, 4, 5, 4, 3, 2,
1},len = 9;
int ans = min_jumps(arr, 0, len-1);
SP
+ j] + 1;

}
}
jumps[idx] = tmp_min;
G
printf("%d\n",ans); return jumps[0];
return 0; }
LO

} int main()
{
a) 4 int arr[] ={1, 1, 1, 1, 1, 1, 1, 1,
b) 5 1},len = 9;
.B

int ans = min_jump(arr,len);


c) 6
printf("%d\n",ans);
d) 7 return 0;
}
17

Answer: a
Explanation: The program prints the Which of the following “for” loops can be
minimum number of jumps required to reach used instead of the inner for loop so that the
-R

the end of the array. One way reach the end output doesn’t change?
using minimum number of jumps is a) for(j = 1; j < arr[idx] + len; j++)
{1 -> 2 -> 4 -> 8 -> 9}. So, the number of b) for(j = 0; j < arr[idx] – len; j++)
SE

jumps is 4. c) for(j = idx + 1; j < len && j <= arr[idx] +


idx; j++)
6. For any array, given that at most one d) No change is required
element is non-zero, it is ALWAYS possible
C

to reach the end of the array using minimum Answer: d


jumps. Explanation: None of the above mentioned
a) True “for” loops can be used instead of the inner
b) False for loop. Note, for(j = idx + 1; j < len && j
<= arr[idx] + idx; j++) covers the same range
Answer: b as the inner for loop but it produces the
Explanation: Consider the array {1,0,2,3,4}. wrong output because the indexing inside the

Downloaded From: https://cse-r17.blogspot.com 123


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

loops changes as “j” takes different values in #include<stdio.h>


the two “for” loops. #include<limits.h>
int min_jump(int *arr, int len)
{
8. What is the time complexity of the int j, idx, jumps[len];
following dynamic programming jumps[len - 1] = 0;
implementation used to find the minimum for(idx = len - 2; idx >= 0; idx--)
number of jumps? {
int tmp_min = INT_MAX;
#include<stdio.h> for(j = 1; j <= arr[idx] && idx
#include<limits.h> + j < len; j++)
int min_jump(int *arr, int len) {
{ if(jumps[idx + j] + 1 <
int j, idx, jumps[len]; tmp_min)
jumps[len - 1] = 0; tmp_min = jumps[idx
for(idx = len - 2; idx >= 0; idx--) + j] + 1;
{ }
int tmp_min = INT_MAX; jumps[idx] = tmp_min;
for(j = 1; j <= arr[idx] && idx }
+ j < len; j++) return jumps[0];
{ }
if(jumps[idx + j] + 1 < int main()
tmp_min) {
tmp_min = jumps[idx int arr[] ={1, 1, 1, 1, 1, 1, 1, 1,
+ j] + 1; 1},len = 9;
} int ans = min_jump(arr,len);
jumps[idx] = tmp_min; printf("%d\n",ans);
} return 0;
return jumps[0]; }
}
int main() a) O(1)
{ b) O(n)
int arr[] ={1, 1, 1, 1, 1, 1, 1, 1,
1},len = 9;
c) O(n2)
int ans = min_jump(arr,len); d) O(5)
printf("%d\n",ans);
return 0; Answer: b
} Explanation: The space complexity of the
above dynamic programming implementation
a) O(1) is O(n).
b) O(n)
c) O(n2) 10. What is the output of the following
d) None of the mentioned program?

Answer: c #include<stdio.h>
Explanation: The time complexity of the #include<limits.h>
int min_jump(int *arr, int len)
above dynamic programming implementation {
is O(n2). int j, idx, jumps[len];
jumps[len - 1] = 0;
9. What is the space complexity of the for(idx = len - 2; idx >= 0; idx--)
{
following dynamic programming int tmp_min = INT_MAX;
implementation used to find the minimum for(j = 1; j <= arr[idx] &&
number of jumps? idx + j < len; j++)

Downloaded From: https://cse-r17.blogspot.com 124


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

{ int arr[] ={9, 9, 9, 9, 9, 9, 9, 9,


if(jumps[idx + j] + 1 9},len = 9;
< tmp_min) int ans = min_jump(arr,len);
tmp_min = jumps[idx printf("%d\n",ans);
+ j] + 1; return 0;
} }
jumps[idx] = tmp_min;
} a) 1
return jumps[0]; b) 6
}
int main() c) 2
{ d) 7
int arr[] ={1, 1, 1, 1, 1, 1, 1, 1,
1},len = 9; Answer: a
int ans = min_jump(arr,len); Explanation: The program prints the
printf("%d\n",ans);
return 0;
minimum jumps required to reach the end of
} the array, which is 1 and so the output is 1.

a) 7
b) 8 1. The Knapsack problem is an example of
c) 9 ____________
d) 10 a) Greedy algorithm
b) 2D dynamic programming
Answer: b c) 1D dynamic programming
Explanation: The program prints the d) Divide and conquer
minimum jumps required to reach the end of
the array, which is 8 and so the output is 8. Answer: b
Explanation: Knapsack problem is an
11. What is the output of the following example of 2D dynamic programming.
program?
2. Which of the following methods can be
#include<stdio.h> used to solve the Knapsack problem?
#include<limits.h> a) Brute force algorithm
int min_jump(int *arr, int len) b) Recursion
{
int j, idx, jumps[len]; c) Dynamic programming
jumps[len - 1] = 0; d) Brute force, Recursion and Dynamic
for(idx = len - 2; idx >= 0; idx--) Programming
{
int tmp_min = INT_MAX; Answer: d
for(j = 1; j <= arr[idx] && idx
+ j < len; j++)
Explanation: Brute force, Recursion and
{ Dynamic Programming can be used to solve
if(jumps[idx + j] + 1 < t the knapsack problem.
mp_min)
tmp_min = jumps[idx + j 3. You are given a knapsack that can carry a
] + 1; maximum weight of 60. There are 4 items
}
jumps[idx] = tmp_min;
with weights {20, 30, 40, 70} and values {70,
} 80, 90, 200}. What is the maximum value of
return jumps[0]; the items you can carry using the knapsack?
} a) 160
int main() b) 200
{

Downloaded From: https://cse-r17.blogspot.com 125


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

c) 170 problem?
d) 90 a) O(n)
b) O(n!)
Answer: a c) O(2n)
Explanation: The maximum value you can
get is 160. This can be achieved by choosing d) O(n3)
the items 1 and 3 that have a total weight of Answer: c
60. Explanation: In the brute force algorithm all
the subsets of the items are found and the
4. Which of the following problems is
value of each subset is calculated. The subset
equivalent to the 0-1 Knapsack problem?
of items with the maximum value and a
a) You are given a bag that can carry a
weight less than equal to the maximum
maximum weight of W. You are given N
allowed weight gives the answer. The time
items which have a weight of {w1, w2,
w3,…., wn} and a value of {v1, v2, v3,…., taken to calculate all the subsets is O(2n).
vn}. You can break the items into smaller
pieces. Choose the items in such a way that 6. The 0-1 Knapsack problem can be solved
you get the maximum value using Greedy algorithm.
b) You are studying for an exam and you have a) True
to study N questions. The questions take {t1, b) False
t2, t3,…., tn} time(in hours) and carry {m1,
Answer: b
m2, m3,…., mn} marks. You can study for a
Explanation: The Knapsack problem cannot
maximum of T hours. You can either study a
be solved using the greedy algorithm.
question or leave it. Choose the questions in
such a way that your score is maximized 7. Consider the following dynamic
c) You are given infinite coins of
programming implementation of the
denominations {v1, v2, v3,….., vn} and a
Knapsack problem:
sum S. You have to find the minimum
number of coins required to get the sum S #include<stdio.h>
d) You are given a suitcase that can carry a int find_max(int a, int b)
maximum weight of 15kg. You are given 4 {
items which have a weight of {10, 20, 15,40} if(a > b)
return a;
and a value of {1, 2, 3,4}. You can break the return b;
items into smaller pieces. Choose the items in }
such a way that you get the maximum value int knapsack(int W, int *wt, int *val,int
n)
Answer: b {
Explanation: In this case, questions are used int ans[n + 1][W + 1];
int itm,w;
instead of items. Each question has a score for(itm = 0; itm <= n; itm++)
which is same as each item having a value. ans[itm][0] = 0;
Also, each question takes a time t which is for(w = 0;w <= W; w++)
same as each item having a weight w. You ans[0][w] = 0;
have to maximize the score in time T which is for(itm = 1; itm <= n; itm++)
{
same as maximizing the value using a bag of for(w = 1; w <= W; w++)
weight W. {
if(wt[itm - 1] <= w)
5. What is the time complexity of the brute ans[itm][w] = _________
force algorithm used to solve the Knapsack _____;

Downloaded From: https://cse-r17.blogspot.com 126


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

else {
ans[itm][w] = ans[itm - if(wt[itm - 1] <= w)
1][w]; ans[itm][w] = find_max(
} ans[itm - 1][w - wt[itm - 1]] + val[itm -
} 1], ans[itm - 1][w]);
return ans[n][W]; else
} ans[itm][w] = ans[itm -
int main() 1][w];
{ }
int w[] = {10,20,30}, v[] = {60, 100 }
, 120}, W = 50; return ans[n][W];
int ans = knapsack(W, w, v, 3); }
printf("%d",ans); int main()
return 0; {
} int w[] = {10,20,30}, v[] = {60, 100
, 120}, W = 50;
Which of the following lines completes the int ans = knapsack(W, w, v, 3);
above code? printf("%d",ans);
return 0;
a) find_max(ans[itm – 1][w – wt[itm – 1]] + }
val[itm – 1], ans[itm – 1][w])
b) find_max(ans[itm – 1][w – wt[itm – 1]], a) O(n)
ans[itm – 1][w]) b) O(n + w)
c) ans[itm][w] = ans[itm – 1][w]; c) O(nW)
d) ans[itm+1][w] = ans[itm – 1][w]; d) O(n2)
Answer: a Answer: c
Explanation: find_max(ans[itm – 1][w – Explanation: The time complexity of the
wt[itm – 1]] + val[itm – 1], ans[itm – 1][w]) above dynamic programming implementation
completes the above code. of the Knapsack problem is O(nW).
8. What is the time complexity of the 9. What is the space complexity of the
following dynamic programming following dynamic programming
implementation of the Knapsack problem implementation of the Knapsack problem?
with n items and a maximum weight of W?
#include<stdio.h>
#include<stdio.h> int find_max(int a, int b)
int find_max(int a, int b) {
{ if(a > b)
if(a > b) return a;
return a; return b;
return b; }
} int knapsack(int W, int *wt, int *val,int
int knapsack(int W, int *wt, int *val,int n)
n) {
{ int ans[n + 1][W + 1];
int ans[n + 1][W + 1]; int itm,w;
int itm,w; for(itm = 0; itm <= n; itm++)
for(itm = 0; itm <= n; itm++) ans[itm][0] = 0;
ans[itm][0] = 0; for(w = 0;w <= W; w++)
for(w = 0;w <= W; w++) ans[0][w] = 0;
ans[0][w] = 0; for(itm = 1; itm <= n; itm++)
for(itm = 1; itm <= n; itm++) {
{ for(w = 1; w <= W; w++)
for(w = 1; w <= W; w++)

Downloaded From: https://cse-r17.blogspot.com 127


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

{ ans[itm - 1][w - wt[itm - 1]] + val[itm -


if(wt[itm - 1] <= w) 1], ans[itm - 1][w]);
ans[itm][w] = find_max( else
ans[itm - 1][w - wt[itm - 1]] + val[itm - ans[itm][w] = ans[itm
1], ans[itm - 1][w]); - 1][w];
else }
ans[itm][w] = ans[itm - }
1][w]; return ans[n][W];
} }
} int main()
return ans[n][W]; {
} int w[] = {10,20,30}, v[] = {60, 100
int main() , 120}, W = 50;
{ int ans = knapsack(W, w, v, 3);
int w[] = {10,20,30}, v[] = {60, 100 printf("%d",ans);
, 120}, W = 50; return 0;
int ans = knapsack(W, w, v, 3); }
printf("%d",ans);
return 0; a) 120
} b) 100
c) 180
a) O(n)
d) 220
b) O(n + w)
c) O(nW) Answer: d
d) O(n2) Explanation: The output of the above code is
220.
Answer: c
Explanation: The space complexity of the
above dynamic programming implementation 1. Which of the following methods can be
of the Knapsack problem is O(nW). used to solve the matrix chain multiplication
problem?
10. What is the output of the following code? a) Dynamic programming
b) Brute force
#include<stdio.h>
int find_max(int a, int b) c) Recursion
{ d) Dynamic Programming, Brute force,
if(a > b) Recursion
return a;
return b; Answer: d
}
int knapsack(int W, int *wt, int *val,int
Explanation: Dynamic Programming, Brute
n) force, Recursion methods can be used to
{ solve the matrix chain multiplication
int ans[n + 1][W + 1]; problem.
int itm,w;
for(itm = 0; itm <= n; itm++) 2. Which of the following is the recurrence
ans[itm][0] = 0;
for(w = 0;w <= W; w++)
relation for the matrix chain multiplication
ans[0][w] = 0; problem where mat[i-1] * mat[i] gives the
for(itm = 1; itm <= n; itm++) dimension of the ith matrix?
{ a) dp[i,j] = 1 if i=j
for(w = 1; w <= W; w++) dp[i,j] = min{dp[i,k] + dp[k+1,j]}
{
if(wt[itm - 1] <= w)
b) dp[i,j] = 0 if i=j
ans[itm][w] = find_max( dp[i,j] = min{dp[i,k] + dp[k+1,j]}

Downloaded From: https://cse-r17.blogspot.com 128


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

c) dp[i,j] = 1 if i=j a) 6050


dp[i,j] = min{dp[i,k] + dp[k+1,j]} + mat[i- b) 7500
1]*mat[k]*mat[j]. c) 7750
d) dp[i,j] = 0 if i=j d) 12000
dp[i,j] = min{dp[i,k] + dp[k+1,j]} + mat[i-
1]*mat[k]*mat[j]. Answer: c
Explanation: The minimum number of
Answer: d multiplications required is 7750.
Explanation: The recurrence relation is given
by: 6. Consider the brute force implementation in
dp[i,j] = 0 if i=j which we find all the possible ways of
dp[i,j] = min{dp[i,k] + dp[k+1,j]} + mat[i- multiplying the given set of n matrices. What
1]*mat[k]*mat[j]. is the time complexity of this
implementation?
3. Consider the two matrices P and Q which a) O(n!)
are 10 x 20 and 20 x 30 matrices respectively. b) O(n3)
What is the number of multiplications
c) O(n2)
required to multiply the two matrices?
d) Exponential
a) 10*20
b) 20*30 Answer: d
c) 10*30 Explanation: The time complexity of finding
d) 10*20*30 all the possible ways of multiplying a set of n
Answer: d matrices is given by (n-1)th Catalan number
Explanation: The number of multiplications which is exponential.
required is 10*20*30.
7. Consider the following dynamic
4. Consider the matrices P, Q and R which are programming implementation of the matrix
10 x 20, 20 x 30 and 30 x 40 matrices chain problem:
respectively. What is the minimum number of
#include<stdio.h>
multiplications required to multiply the three #include<limits.h>
matrices? int mat_chain_multiplication(int *mat, in
a) 18000 t n)
b) 12000 {
int arr[n][n];
c) 24000 int i,k,row,col,len;
d) 32000 for(i=1;i<n;i++)
arr[i][i] = 0;
Answer: a for(len = 2; len < n; len++)
Explanation: The minimum number of {
multiplications are 18000. This is the case for(row = 1; row <= n - len +
1; row++)
when the matrices are parenthesized as {
(P*Q)*R. col = row + len - 1;
arr[row][col] = INT_MAX;
5. Consider the matrices P, Q, R and S which for(k = row; k <= col - 1;
are 20 x 15, 15 x 30, 30 x 5 and 5 x 40 k++)
matrices respectively. What is the minimum {
int tmp = ___________
number of multiplications required to _____________;
multiply the four matrices? if(tmp < arr[row][col

Downloaded From: https://cse-r17.blogspot.com 129


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

]) for(k = row; k <= col - 1;


arr[row][col] = tmp; k++)
} {
} int tmp = arr[row][k]
} + arr[k + 1][col] + mat[row - 1] * mat[k]
return arr[1][n - 1]; * mat[col];
} if(tmp < arr[row][col
int main() ])
{ arr[row][col] = tmp;
int mat[6] = {20,5,30,10,40}; }
int ans = mat_chain_multiplication(m }
at,5); }
printf("%d",ans); return arr[1][n - 1];
return 0; }
} int main()
{
Which of the following lines should be int mat[6] = {20,5,30,10,40};
inserted to complete the above code? int ans = mat_chain_multiplication(m
at,5);
a) arr[row][k] – arr[k + 1][col] + mat[row – printf("%d",ans);
1] * mat[k] * mat[col]; return 0;
b) arr[row][k] + arr[k + 1][col] – mat[row – }
1] * mat[k] * mat[col];
c) arr[row][k] + arr[k + 1][col] + mat[row – a) O(1)
1] * mat[k] * mat[col]; b) O(n)
d) arr[row][k] – arr[k + 1][col] – mat[row – c) O(n2)
1] * mat[k] * mat[col]; d) O(n3)
Answer: c Answer: d
Explanation: The line arr[row][k] + arr[k + Explanation: The time complexity of the
1][col] + mat[row – 1] * mat[k] * mat[col] above dynamic programming implementation
should be inserted to complete the above
of the matrix chain multiplication is O(n3).
code.
9. What is the space complexity of the
8. What is the time complexity of the
following dynamic programming
following dynamic programming
implementation of the matrix chain problem?
implementation of the matrix chain problem?
#include<stdio.h>
#include<stdio.h> #include<limits.h>
#include<limits.h> int mat_chain_multiplication(int *mat, in
int mat_chain_multiplication(int *mat, in t n)
t n) {
{ int arr[n][n];
int arr[n][n]; int i,k,row,col,len;
int i,k,row,col,len; for(i=1;i<n;i++)
for(i=1;i<n;i++) arr[i][i] = 0;
arr[i][i] = 0; for(len = 2; len < n; len++)
for(len = 2; len < n; len++) {
{ for(row = 1; row <= n - len +
for(row = 1; row <= n - len + 1; row++)
1; row++) {
{ col = row + len - 1;
col = row + len - 1; arr[row][col] = INT_MAX;
arr[row][col] = INT_MAX; for(k = row; k <= col - 1;

Downloaded From: https://cse-r17.blogspot.com 130


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

k++) + arr[k + 1][col] + mat[row - 1] * mat[k]


{ * mat[col];
int tmp = arr[row][k] if(tmp < arr[row][col
+ arr[k + 1][col] + mat[row - 1] * mat[k] ])
* mat[col]; arr[row][col] = tmp;
if(tmp < arr[row][col }
]) }
arr[row][col] = tmp; }
} return arr[1][n - 1];
} }
} int main()
return arr[1][n - 1]; {
} int mat[6] = {20,30,40,50};
int main() int ans = mat_chain_multiplication(m
{ at,4);
int mat[6] = {20,5,30,10,40}; printf("%d",ans);
int ans = mat_chain_multiplication(m return 0;
at,5); }
printf("%d",ans);
return 0; a) 64000
} b) 70000
c) 120000
a) O(1)
d) 150000
b) O(n)
c) O(n2) Answer: a
d) O(n3) Explanation: The program prints the
minimum number of multiplications required,
Answer: c which is 64000.
Explanation: The space complexity of the
above dynamic programming implementation 11. What is the value stored in arr[2][3] when
of the matrix chain multiplication is O(n2). the following code is executed?

#include<stdio.h>
10. What is the output of the following code?
#include<limits.h>
int mat_chain_multiplication(int *mat, in
#include<stdio.h> t n)
#include<limits.h> {
int mat_chain_multiplication(int *mat, in int arr[n][n];
t n) int i,k,row,col,len;
{ for(i=1;i<n;i++)
int arr[n][n]; arr[i][i] = 0;
int i,k,row,col,len; for(len = 2; len < n; len++)
for(i=1;i<n;i++) {
arr[i][i] = 0; for(row = 1; row <= n - len + 1
for(len = 2; len < n; len++) ; row++)
{ {
for(row = 1; row <= n - len + 1 col = row + len - 1;
; row++) arr[row][col] = INT_MAX;
{ for(k = row; k <= col - 1;
col = row + len - 1; k++)
arr[row][col] = INT_MAX; {
for(k = row; k <= col - 1; int tmp = arr[row][k
k++) ] + arr[k + 1][col] + mat[row - 1] * mat[
{ k] * mat[col];
int tmp = arr[row][k] if(tmp < arr[row][co

Downloaded From: https://cse-r17.blogspot.com 131


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

l]) return arr[1][n-1];


arr[row][col] = tmp; }
} int main()
} {
} int mat[6] = {10,10,10,10,10,10};
return arr[1][n - 1]; int ans = mat_chain_multiplication(m
} at,6);
int main() printf("%d",ans);
{ return 0;
int mat[6] = {20,30,40,50}; }
int ans = mat_chain_multiplication(m
at,4); a) 2000
printf("%d",ans); b) 3000
return 0;
} c) 4000
d) 5000
a) 64000
b) 60000 Answer: c
c) 24000 Explanation: The program prints the
d) 12000 minimum number of multiplications required
to multiply the given matrices, which is 4000.
Answer: b
Explanation: The value stored in arr[2][3] 13. What is the output of the following code?
when the above code is executed is 60000.
#include<stdio.h>
#include<limits.h>
12. What is the output of the following code? int mat_chain_multiplication(int *mat, in
t n)
#include<stdio.h> {
#include<limits.h> int arr[n][n];
int mat_chain_multiplication(int *mat, in int i,k,row,col,len;
t n) for(i=1;i<n;i++)
{ arr[i][i] = 0;
int arr[n][n]; for(len = 2; len < n; len++)
int i,k,row,col,len; {
for(i=1;i<n;i++) for(row = 1; row <= n - len + 1
arr[i][i] = 0; ; row++)
for(len = 2; len < n; len++) {
{ col = row + len - 1;
for(row = 1; row <= n - len + 1 arr[row][col] = INT_MAX;
; row++) for(k = row; k <= col - 1;
{ k++)
col = row + len - 1; {
arr[row][col] = INT_MAX; int tmp = arr[row][k]
for(k = row; k <= col - 1; + arr[k + 1][col] + mat[row - 1] * mat[k]
k++) * mat[col];
{ if(tmp < arr[row][col
int tmp = arr[row][k] ])
+ arr[k + 1][col] + mat[row - 1] * mat[k] arr[row][col] = tmp;
* mat[col]; }
if(tmp < arr[row][col }
]) }
arr[row][col] = tmp; return arr[1][n-1];
} }
} int main()
} {

Downloaded From: https://cse-r17.blogspot.com 132


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

int mat[6] = {20,25,30,35,40}; c) Longest bitonic subsequence


int ans = mat_chain_multiplication(m d) Longest decreasing subsequence
at,5);
printf("%d",ans);
return 0; Answer: b
} Explanation: To find the longest palindromic
subsequence in a given string, reverse the
a) 32000 given string and then find the longest
b) 28000 common subsequence in the given string and
c) 64000 the reversed string.
d) 70000
4. Longest common subsequence is an
Answer: c example of ____________
Explanation: The output of the program is a) Greedy algorithm
64000. b) 2D dynamic programming
c) 1D dynamic programming
d) Divide and conquer
1. Which of the following methods can be
used to solve the longest common Answer: b
subsequence problem? Explanation: Longest common subsequence
a) Recursion is an example of 2D dynamic programming.
b) Dynamic programming
c) Both recursion and dynamic programming 5. What is the time complexity of the brute
d) Greedy algorithm force algorithm used to find the longest
common subsequence?
Answer: c a) O(n)
Explanation: Both recursion and dynamic b) O(n2)
programming can be used to solve the longest c) O(n3)
subsequence problem.
d) O(2n)
2. Consider the strings “PQRSTPQRS” and
“PRATPBRQRPS”. What is the length of the Answer: d
longest common subsequence? Explanation: The time complexity of the
a) 9 brute force algorithm used to find the longest
b) 8 common subsequence is O(2n).
c) 7
d) 6 6. Consider the following dynamic
programming implementation of the longest
Answer: c common subsequence problem:
Explanation: The longest common
subsequence is “PRTPQRS” and its length is #include<stdio.h>
#include<string.h>
7. int max_num(int a, int b)
{
3. Which of the following problems can be if(a > b)
solved using the longest subsequence return a;
problem? return b;
}
a) Longest increasing subsequence int lcs(char *str1, char *str2)
b) Longest palindromic subsequence {
int i,j,len1,len2;

Downloaded From: https://cse-r17.blogspot.com 133


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

len1 = strlen(str1); return b;


len2 = strlen(str2); }
int arr[len1 + 1][len2 + 1]; int lcs(char *str1, char *str2)
for(i = 0; i <= len1; i++) {
arr[i][0] = 0; int i,j,len1,len2;
for(i = 0; i <= len2; i++) len1 = strlen(str1);
arr[0][i] = 0; len2 = strlen(str2);
for(i = 1; i <= len1; i++) int arr[len1 + 1][len2 + 1];
{ for(i = 0; i <= len1; i++)
for(j = 1; j <= len2; j++) arr[i][0] = 0;
{ for(i = 0; i <= len2; i++)
if(str1[i-1] == str2[j - arr[0][i] = 0;
1]) for(i = 1; i <= len1; i++)
______________; {
else for(j = 1; j <= len2; j++)
arr[i][j] = max_num(ar {
r[i - 1][j], arr[i][j - 1]); if(str1[i-1] == str2[j -
} 1])
} arr[i][j] = 1 + arr[i -
return arr[len1][len2]; 1][j - 1];
} else
int main() arr[i][j] = max_num(ar
{ r[i - 1][j], arr[i][j - 1]);
char str1[] = " abcedfg", str2[] = }
"bcdfh"; }
int ans = lcs(str1,str2); return arr[len1][len2];
printf("%d",ans); }
return 0; int main()
} {
char str1[] = " abcedfg", str2[] =
Which of the following lines completes the "bcdfh";
above code? int ans = lcs(str1,str2);
printf("%d",ans);
a) arr[i][j] = 1 + arr[i][j]. return 0;
b) arr[i][j] = 1 + arr[i – 1][j – 1]. }
c) arr[i][j] = arr[i – 1][j – 1].
d) arr[i][j] = arr[i][j]. a) O(n)
b) O(m)
Answer: b c) O(m + n)
Explanation: The line, arr[i][j] = 1 + arr[i – d) O(mn)
1][j – 1] completes the above code.
Answer: d
7. What is the time complexity of the Explanation: The time complexity of the
following dynamic programming above dynamic programming implementation
implementation of the longest common of the longest common subsequence is
subsequence problem where length of one O(mn).
string is “m” and the length of the other string
is “n”? 8. What is the space complexity of the
following dynamic programming
#include<stdio.h> implementation of the longest common
#include<string.h>
int max_num(int a, int b)
subsequence problem where length of one
{ string is “m” and the length of the other string
if(a > b) is “n”?
return a;

Downloaded From: https://cse-r17.blogspot.com 134


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

#include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h>
int max_num(int a, int b) int max_num(int a, int b)
{ {
if(a > b) if(a > b)
return a; return a;
return b; return b;
} }
int lcs(char *str1, char *str2) int lcs(char *str1, char *str2)
{ {
int i,j,len1,len2; int i,j,len1,len2;
len1 = strlen(str1); len1 = strlen(str1);
len2 = strlen(str2); len2 = strlen(str2);
int arr[len1 + 1][len2 + 1]; int arr[len1 + 1][len2 + 1];
for(i = 0; i <= len1; i++) for(i = 0; i <= len1; i++)
arr[i][0] = 0; arr[i][0] = 0;
for(i = 0; i <= len2; i++) for(i = 0; i <= len2; i++)
arr[0][i] = 0; arr[0][i] = 0;
for(i = 1; i <= len1; i++) for(i = 1; i <= len1; i++)
{ {
for(j = 1; j <= len2; j++) for(j = 1; j <= len2; j++)
{ {
if(str1[i-1] == str2[j - if(str1[i-1] == str2[j - 1]
1]) )
arr[i][j] = 1 + arr[i - arr[i][j] = 1 + arr[i -
1][j - 1]; 1][j - 1];
else else
arr[i][j] = max_num(ar arr[i][j] = max_num(arr
r[i - 1][j], arr[i][j - 1]); [i - 1][j], arr[i][j - 1]);
} }
} }
return arr[len1][len2]; return arr[len1][len2];
} }
int main() int main()
{ {
char str1[] = " abcedfg", str2[] = char str1[] = "hbcfgmnapq", str2[]
"bcdfh"; = "cbhgrsfnmq";
int ans = lcs(str1,str2); int ans = lcs(str1,str2);
printf("%d",ans); printf("%d",ans);
return 0; return 0;
} }

a) O(n) a) 3
b) O(m) b) 4
c) O(m + n) c) 5
d) O(mn) d) 6

Answer: d Answer: b
Explanation: The space complexity of the Explanation: The program prints the length
above dynamic programming implementation of the longest common subsequence, which is
of the longest common subsequence is 4.
O(mn).
10. Which of the following is the longest
9. What is the output of the following code? common subsequence between the strings
“hbcfgmnapq” and “cbhgrsfnmq” ?

Downloaded From: https://cse-r17.blogspot.com 135


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

a) hgmq a) 1
b) cfnq b) 2
c) bfmq c) 3
d) fgmna d) 4

Answer: d Answer: a
Explanation: The length of the longest Explanation: The value stored in arr[2][3] is
common subsequence is 4. But ‘fgmna’ is not 1.
the longest common subsequence as its length
is 5. 12. What is the output of the following code?

11. What is the value stored in arr[2][3] when #include<stdio.h>


#include<string.h>
the following code is executed?
int max_num(int a, int b)
{
#include<stdio.h> if(a > b)
#include<string.h> return a;
int max_num(int a, int b) return b;
{ }
if(a > b) int lcs(char *str1, char *str2)
return a; {
return b; int i,j,len1,len2;
} len1 = strlen(str1);
int lcs(char *str1, char *str2) len2 = strlen(str2);
{ int arr[len1 + 1][len2 + 1];
int i,j,len1,len2; for(i = 0; i <= len1; i++)
len1 = strlen(str1); arr[i][0] = 0;
len2 = strlen(str2); for(i = 0; i <= len2; i++)
int arr[len1 + 1][len2 + 1]; arr[0][i] = 0;
for(i = 0; i <= len1; i++) for(i = 1; i <= len1; i++)
arr[i][0] = 0; {
for(i = 0; i <= len2; i++) for(j = 1; j <= len2; j++)
arr[0][i] = 0; {
for(i = 1; i <= len1; i++) if(str1[i-1] == str2[j -
{ 1])
for(j = 1; j <= len2; j++) arr[i][j] = 1 + arr[i
{ - 1][j - 1];
if(str1[i-1] == str2[j - else
1]) arr[i][j] = max_num(ar
arr[i][j] = 1 + arr[i r[i - 1][j], arr[i][j - 1]);
- 1][j - 1]; }
else }
arr[i][j] = max_num(a return arr[len1][len2];
rr[i - 1][j], arr[i][j - 1]); }
} int main()
} {
return arr[len1][len2]; char str1[] = "abcd", str2[] = "efg
} h";
int main() int ans = lcs(str1,str2);
{ printf("%d",ans);
char str1[] = "hbcfgmnapq", str2[] return 0;
= "cbhgrsfnmq"; }
int ans = lcs(str1,str2);
printf("%d",ans);
return 0; a) 3
} b) 2

Downloaded From: https://cse-r17.blogspot.com 136


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

c) 1 4. What is the length of the longest


d) 0 palindromic subsequence for the string
“ababcdabba”?
Answer: d a) 6
Explanation: The program prints the length b) 7
of the longest common subsequence, which is c) 8
0. d) 9

Answer: b
1. Which of the following methods can be Explanation: The longest palindromic
used to solve the longest palindromic subsequence is “abbabba” and its length is 7.
subsequence problem?
a) Dynamic programming 5. What is the time complexity of the brute
b) Recursion force algorithm used to find the length of the
c) Brute force longest palindromic subsequence?
d) Dynamic programming, Recursion, Brute a) O(1)
force b) O(2n)
c) O(n)
Answer: d
d) O(n2)
Explanation: Dynamic programming,
Recursion, Brute force can be used to solve
Answer: b
the longest palindromic subsequence
Explanation: In the brute force algorithm, all
problem.
the subsequences are found and the length of
the longest palindromic subsequence is
2. Which of the following is not a
palindromic subsequence of the string calculated. This takes exponential time.
“ababcdabba”?
6. For every non-empty string, the length of
a) abcba
the longest palindromic subsequence is at
b) abba
least one.
c) abbbba
a) True
d) adba
b) False
Answer: d
Answer: a
Explanation: ‘adba’ is not a palindromic Explanation: A single character of any string
sequence. can always be considered as a palindrome and
its length is one.
3. For which of the following, the length of
the string is not equal to the length of the 7. Longest palindromic subsequence is an
longest palindromic subsequence?
example of ______________
a) A string that is a palindrome a) Greedy algorithm
b) A string of length one b) 2D dynamic programming
c) A string that has all the same letters(e.g. c) 1D dynamic programming
aaaaaa) d) Divide and conquer
d) Some strings of length two
Answer: b
Answer: d Explanation: Longest palindromic
Explanation: A string of length 2 for eg: ab subsequence is an example of 2D dynamic
is not a palindrome.
programming.

Downloaded From: https://cse-r17.blogspot.com 137


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

8. Consider the following code: subsequence, we need to reverse the copy of


the string, which is done by strrev.
#include<stdio.h>
#include<string.h> 9. What is the time complexity of the
int max_num(int a, int b)
{
following dynamic programming
if(a > b) implementation to find the longest
return a; palindromic subsequence where the length of
return b; the string is n?
}
int lps(char *str1) #include<stdio.h>
{ #include<string.h>
int i,j,len; int max_num(int a, int b)
len = strlen(str1); {
char str2[len + 1]; if(a > b)
strcpy(str2, str1); return a;
______________; return b;
int arr[len + 1][len + 1]; }
for(i = 0; i <= len; i++) int lps(char *str1)
arr[i][0] = 0; {
for(i = 0; i <= len; i++) int i,j,len;
arr[0][i] = 0; len = strlen(str1);
for(i = 1; i <= len; i++) char str2[len + 1];
{ strcpy(str2, str1);
for(j = 1; j <= len; j++) strrev(str2);
{ int arr[len + 1][len + 1];
if(str1[i-1] == str2[j - 1 for(i = 0; i <= len; i++)
]) arr[i][0] = 0;
arr[i][j] = 1 + arr[i for(i = 0; i <= len; i++)
- 1][j - 1]; arr[0][i] = 0;
else for(i = 1; i <= len; i++)
arr[i][j] = max_num(ar {
r[i - 1][j], arr[i][j - 1]); for(j = 1; j <= len; j++)
} {
} if(str1[i-1] == str2[j - 1
return arr[len][len]; ])
} arr[i][j] = 1 + arr[i
int main() - 1][j - 1];
{ else
char str1[] = "ababcdabba"; arr[i][j] = max_num(ar
int ans = lps(str1); r[i - 1][j], arr[i][j - 1]);
printf("%d",ans); }
return 0; }
} return arr[len][len];
}
Which of the following lines completes the int main()
above code? {
a) strrev(str2) char str1[] = "ababcdabba";
int ans = lps(str1);
b) str2 = str1 printf("%d",ans);
c) len2 = strlen(str2) return 0;
d) strlen(str2) }

Answer: a a) O(n)
Explanation: To find the longest palindromic b) O(1)

Downloaded From: https://cse-r17.blogspot.com 138


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

c) O(n2) printf("%d",ans);
return 0;
d) O(2) }

Answer: c a) O(n)
Explanation: The time complexity of the b) O(1)
above dynamic programming implementation
c) O(n2)
to find the longest palindromic subsequence
d) O(2)
is O(n2).
Answer: c
10. What is the space complexity of the Explanation: The space complexity of the
following dynamic programming above dynamic programming implementation
implementation to find the longest to find the longest palindromic subsequence
palindromic subsequence where the length of
is O(n2).
the string is n?
#include<stdio.h>
11. What is the value stored in arr[3][3] when
#include<string.h> the following code is executed?
int max_num(int a, int b)
{ #include<stdio.h>
if(a > b) #include<string.h>
return a; int max_num(int a, int b)
return b; {
} if(a > b)
int lps(char *str1) return a;
{ return b;
int i,j,len; }
len = strlen(str1); int lps(char *str1)
char str2[len + 1]; {
strcpy(str2, str1); int i,j,len;
strrev(str2); len = strlen(str1);
int arr[len + 1][len + 1]; char str2[len + 1];
for(i = 0; i <= len; i++) strcpy(str2, str1);
arr[i][0] = 0; strrev(str2);
for(i = 0; i <= len; i++) int arr[len + 1][len + 1];
arr[0][i] = 0; for(i = 0; i <= len; i++)
for(i = 1; i <= len; i++) arr[i][0] = 0;
{ for(i = 0; i <= len; i++)
for(j = 1; j <= len; j++) arr[0][i] = 0;
{ for(i = 1; i <= len; i++)
if(str1[i-1] == str2[j - 1 {
]) for(j = 1; j <= len; j++)
arr[i][j] = 1 + arr[i {
- 1][j - 1]; if(str1[i-1] == str2[j -
else 1])
arr[i][j] = max_num(ar arr[i][j] = 1 + arr[i
r[i - 1][j], arr[i][j - 1]); - 1][j - 1];
} else
} arr[i][j] = max_num(a
return arr[len][len]; rr[i - 1][j], arr[i][j - 1]);
} }
int main() }
{ return arr[len][len];
char str1[] = "ababcdabba"; }
int ans = lps(str1); int main()

Downloaded From: https://cse-r17.blogspot.com 139


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

{ char str1[] = "abcd";


char str1[] = "ababcdabba"; int ans = lps(str1);
int ans = lps(str1); printf("%d",ans);
printf("%d",ans); return 0;
return 0; }
}
a) 0
a) 2 b) 1
b) 3 c) 2
c) 4 d) 3
d) 5
Answer: b
Answer: a Explanation: The program prints the length
Explanation: The value stored in arr[3][3] of the longest palindromic subsequence,
when the above code is executed is 2. which is 1.
12. What is the output of the following code? 13. What is the output of the following code?
#include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h>
int max_num(int a, int b) int max_num(int a, int b)
{ {
if(a > b) if(a > b)
return a; return a;
return b; return b;
} }
int lps(char *str1) int lps(char *str1)
{ {
int i,j,len; int i,j,len;
len = strlen(str1); len = strlen(str1);
char str2[len + 1]; char str2[len + 1];
strcpy(str2, str1); strcpy(str2, str1);
strrev(str2); strrev(str2);
int arr[len + 1][len + 1]; int arr[len + 1][len + 1];
for(i = 0; i <= len; i++) for(i = 0; i <= len; i++)
arr[i][0] = 0; arr[i][0] = 0;
for(i = 0; i <= len; i++) for(i = 0; i <= len; i++)
arr[0][i] = 0; arr[0][i] = 0;
for(i = 1; i <= len; i++) for(i = 1; i <= len; i++)
{ {
for(j = 1; j <= len; j++) for(j = 1; j <= len; j++)
{ {
if(str1[i-1] == str2[j - 1 if(str1[i-1] == str2[j - 1]
]) )
arr[i][j] = 1 + arr[i - arr[i][j] = 1 + arr[i -
1][j - 1]; 1][j - 1];
else else
arr[i][j] = max_num(arr arr[i][j] = max_num(arr
[i - 1][j], arr[i][j - 1]); [i - 1][j], arr[i][j - 1]);
} }
} }
return arr[len][len]; return arr[len][len];
} }
int main() int main()
{ {

Downloaded From: https://cse-r17.blogspot.com 140


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

char str1[] = "abdgkagdjbccbba"; c) Similarity of DNA


int ans = lps(str1); d) Approximate string matching, Spelling
printf("%d",ans);
return 0;
Correction and Similarity of DNA
}
Answer: d
a) 5 Explanation: All of the mentioned are the
b) 7 applications of the edit distance problem.
c) 9
d) 11 4. In which of the following cases will the
edit distance between two strings be zero?
Answer: c a) When one string is a substring of another
Explanation: The program prints the length b) When the lengths of the two strings are
of the longest palindromic subsequence, equal
which is 9. c) When the two strings are equal
d) The edit distance can never be zero

1. Which of the following methods can be Answer: c


used to solve the edit distance problem? Explanation: The edit distance will be zero
a) Recursion only when the two strings are equal.
b) Dynamic programming
c) Both dynamic programming and recursion 5. Suppose each edit (insert, delete, replace)
d) Greedy Algorithm has a cost of one. Then, the maximum edit
distance cost between the two strings is equal
Answer: c to the length of the larger string.
Explanation: Both dynamic programming a) True
and recursion can be used to solve the edit b) False
distance problem.
Answer: a
2. The edit distance satisfies the axioms of a Explanation: Consider the strings “abcd” and
metric when the costs are non-negative. “efghi”. The string “efghi” can be converted
a) True to “abcd” by deleting “i” and converting
b) False “efgh” to “abcd”. The cost of transformation
is 5, which is equal to the length of the larger
Answer: a string.
Explanation: d(s,s) = 0, since each string can
be transformed into itself without any change. 6. Consider the strings “monday” and
d(s1, s2) > 0 when s1 != s2, since the “tuesday”. What is the edit distance between
transformation would require at least one the two strings?
operation. a) 3
d(s1, s2) = d(s2, s1) b) 4
d(s1, s3) <= d(s1, s2) + d(s2, s3) c) 5
Thus, the edit distance satisfies the axioms of d) 6
a metric.
Answer: b
3. Which of the following is an application of Explanation: “monday” can be converted to
the edit distance problem? “tuesday” by replacing “m” with “t”, “o” with
a) Approximate string matching “u”, “n” with “e” and inserting “s” at the
b) Spelling correction appropriate position. So, the edit distance is 4.

Downloaded From: https://cse-r17.blogspot.com 141


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

7. Consider the two strings “”(empty string) -1] + 1;


and “abcd”. What is the edit distance between }
_____________;
the two strings? }
a) 0 }
b) 4 return arr[len1][len2];
c) 2 }
d) 3 int main()
{
char s1[] = "abcd", s2[] = "defg";
Answer: b

M
int ans = edit_distance(s1, s2);
Explanation: The empty string can be printf("%d",ans);
transformed into “abcd” by inserting “a”, “b”, return 0;

O
“c” and “d” at appropriate positions. Thus, }
the edit distance is 4.

C
Which of the following lines should be added
8. Consider the following dynamic to complete the above code?

T.
programming implementation of the edit a) arr[i-1][j] = min
distance problem: b) arr[i][j-1] = min
c) arr[i-1][j-1] = min

O
#include<stdio.h> d) arr[i][j] = min
#include<string.h>
int get_min(int a, int b)
{
if(a < b)
return a;
SP
Answer: d
Explanation: The line arr[i][j] = min
completes the above code.
G
return b;
} 9. What is the time complexity of the
LO

int edit_distance(char *s1, char *s2) following dynamic programming


{ implementation of the edit distance problem
int len1,len2,i,j,min;
len1 = strlen(s1);
where “m” and “n” are the lengths of two
strings?
.B

len2 = strlen(s2);
int arr[len1 + 1][len2 + 1];
for(i = 0;i <= len1; i++) #include<stdio.h>
arr[i][0] = i; #include<string.h>
17

for(i = 0; i <= len2; i++) int get_min(int a, int b)


arr[0][i] = i; {
for(i = 1; i <= len1; i++) if(a < b)
return a;
-R

{
for(j = 1; j <= len2; j++) return b;
{ }
min = get_min(arr[i-1][j], int edit_distance(char *s1, char *s2)
SE

arr[i][j-1]) + 1; {
if(s1[i - 1] == s2[j - 1]) int len1,len2,i,j,min;
{ len1 = strlen(s1);
if(arr[i-1][j-1] < mi len2 = strlen(s2);
C

n) int arr[len1 + 1][len2 + 1];


min = arr[i-1][j-1 for(i = 0;i <= len1; i++)
]; arr[i][0] = i;
} for(i = 0; i <= len2; i++)
else arr[0][i] = i;
{ for(i = 1; i <= len1; i++)
if(arr[i-1][j-1] + 1 {
< min) for(j = 1; j <= len2; j++)
min = arr[i-1][j {

Downloaded From: https://cse-r17.blogspot.com 142


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

min = get_min(arr[i-1][j], {
arr[i][j-1]) + 1; int len1,len2,i,j,min;
if(s1[i - 1] == s2[j - 1]) len1 = strlen(s1);
{ len2 = strlen(s2);
if(arr[i-1][j-1] < mi int arr[len1 + 1][len2 + 1];
n) for(i = 0;i <= len1; i++)
min = arr[i-1][j-1 arr[i][0] = i;
]; for(i = 0; i <= len2; i++)
} arr[0][i] = i;
else for(i = 1; i <= len1; i++)
{ {
if(arr[i-1][j-1] + 1 for(j = 1; j <= len2; j++)
< min) {
min = arr[i-1][j min = get_min(arr[i-1][j],
-1] + 1; arr[i][j-1]) + 1;
} if(s1[i - 1] == s2[j - 1])
arr[i][j] = min; {
} if(arr[i-1][j-1] < mi
} n)
return arr[len1][len2]; min = arr[i-1][j-1
} ];
int main() }
{ else
char s1[] = "abcd", s2[] = "defg"; {
int ans = edit_distance(s1, s2); if(arr[i-1][j-1] + 1
printf("%d",ans); < min)
return 0; min = arr[i-1][j
} -1] + 1;
}
a) O(1) arr[i][j] = min;
b) O(m + n) }
}
c) O(mn) return arr[len1][len2];
d) O(n) }
int main()
Answer: c {
Explanation: The time complexity of the char s1[] = "abcd", s2[] = "defg";
int ans = edit_distance(s1, s2);
above dynamic programming implementation
printf("%d",ans);
of the edit distance problem is O(mn). return 0;
}
10. What is the space complexity of the
following dynamic programming a) O(1)
implementation of the edit distance problem b) O(m + n)
where “m” and “n” are the lengths of the two c) O(mn)
strings? d) O(n)
#include<stdio.h> Answer: c
#include<string.h> Explanation: The space complexity of the
int get_min(int a, int b)
{ above dynamic programming implementation
if(a < b) of the edit distance problem is O(mn).
return a;
return b; 11. What is the output of the following code?
}
int edit_distance(char *s1, char *s2)

Downloaded From: https://cse-r17.blogspot.com 143


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

#include<stdio.h> Answer: d
#include<string.h> Explanation: The program prints the edit
int get_min(int a, int b)
{
distance between the strings “abcd” and
if(a < b) “defg”, which is 4.
return a;
return b; 12. What is the value stored in arr[2][2] when
} the following code is executed?
int edit_distance(char *s1, char *s2)
{ #include<stdio.h>
int len1,len2,i,j,min; #include<string.h>
len1 = strlen(s1); int get_min(int a, int b)
len2 = strlen(s2); {
int arr[len1 + 1][len2 + 1]; if(a < b)
for(i = 0;i <= len1; i++) return a;
arr[i][0] = i; return b;
for(i = 0; i <= len2; i++) }
arr[0][i] = i; int edit_distance(char *s1, char *s2)
for(i = 1; i <= len1; i++) {
{ int len1,len2,i,j,min;
for(j = 1; j <= len2; j++) len1 = strlen(s1);
{ len2 = strlen(s2);
min = get_min(arr[i-1][j],a int arr[len1 + 1][len2 + 1];
rr[i][j-1]) + 1; for(i = 0;i <= len1; i++)
if(s1[i - 1] == s2[j - 1]) arr[i][0] = i;
{ for(i = 0; i <= len2; i++)
if(arr[i-1][j-1] < min) arr[0][i] = i;
min = arr[i-1][j-1] for(i = 1; i <= len1; i++)
; {
} for(j = 1; j <= len2; j++)
else {
{ min = get_min(arr[i-1][j
if(arr[i-1][j-1] + 1 < ],arr[i][j-1]) + 1;
min) if(s1[i - 1] == s2[j - 1
min = arr[i-1][j-1] ])
+ 1; {
} if(arr[i-1][j-1] <
arr[i][j] = min; min)
} min = arr[i-1][j-
} 1];
return arr[len1][len2]; }
} else
int main() {
{ if(arr[i-1][j-1] +
char s1[] = "abcd", s2[] = "defg"; 1 < min)
int ans = edit_distance(s1, s2); min = arr[i-1][j-
printf("%d",ans); 1] + 1;
return 0; }
} arr[i][j] = min;
}
a) 1 }
b) 2 return arr[len1][len2];
c) 3 }
int main()
d) 4
{
char s1[] = "abcd", s2[] = "defg";
int ans = edit_distance(s1, s2);

Downloaded From: https://cse-r17.blogspot.com 144


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

printf("%d",ans); }
return 0; int main()
} {
char s1[] = "pqrstuv", s2[] = "prstu
a) 1 v";
b) 2 int ans = edit_distance(s1, s2);
printf("%d",ans);
c) 3 return 0;
d) 4 }

Answer: b a) 1
Explanation: The value stored in arr[2][2] b) 2
when the above code is executed is 2. c) 3
d) 4
13. What is the output of the following code?
Answer: a
#include<stdio.h> Explanation: The code prints the edit
#include<string.h>
int get_min(int a, int b) distance between the two strings, which is 1.
{
if(a < b)
return a; 1. Wagner–Fischer is a ____________
return b; algorithm.
}
a) Brute force
int edit_distance(char *s1, char *s2)
{ b) Greedy
int len1,len2,i,j,min; c) Dynamic programming
len1 = strlen(s1); d) Recursive
len2 = strlen(s2);
int arr[len1 + 1][len2 + 1]; Answer: c
for(i = 0;i <= len1; i++)
arr[i][0] = i;
Explanation: Wagner–Fischer belongs to the
for(i = 0; i <= len2; i++) dynamic programming type of algorithms.
arr[0][i] = i;
for(i = 1; i <= len1; i++) 2. Wagner–Fischer algorithm is used to find
{ ____________
for(j = 1; j <= len2; j++) a) Longest common subsequence
{
min = get_min(arr[i-1][j],a b) Longest increasing subsequence
rr[i][j-1]) + 1; c) Edit distance between two strings
if(s1[i - 1] == s2[j - 1]) d) Longest decreasing subsequence
{
if(arr[i-1][j-1] < min) Answer: c
min = arr[i-1][j-1];
}
Explanation: Wagner–Fischer algorithm is
else used to find the edit distance between two
{ strings.
if(arr[i-1][j-1] + 1 <
min) 3. What is the edit distance between the
min = arr[i-1][j-1] strings “abcd” and “acbd” when the allowed
+ 1;
}
operations are insertion, deletion and
arr[i][j] = min; substitution?
} a) 1
} b) 2
return arr[len1][len2];

Downloaded From: https://cse-r17.blogspot.com 145


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

c) 3 {
d) 4 if(arr[i-1][j-1] + 1 <
min)
min = arr[i-1][j-1]
Answer: b + 1;
Explanation: The string “abcd” can be }
changed to “acbd” by substituting “b” with arr[i][j] = min;
“c” and “c” with “b”. Thus, the edit distance }
is 2. }
return arr[len1][len2];
}
4. For which of the following pairs of strings
is the edit distance maximum? Which of the following lines should be
a) sunday & monday inserted to complete the above code?
b) monday & tuesday a) arr[i][j] = min
c) tuesday & wednesday b) min = arr[i-1][j-1] – 1;
d) wednesday & thursday c) min = arr[i-1][j-1].
d) min = arr[i-1][j-1] + 1;
Answer: d
Explanation: The edit distances are 2, 4, 4 Answer: c
and 5 respectively. Hence, the maximum edit Explanation: The line min = arr[i-1][j-1]
distance is between the strings wednesday completes the above code.
and thursday.
6. What is the time complexity of the
5. Consider the following implementation of Wagner–Fischer algorithm where “m” and
the Wagner–Fischer algorithm: “n” are the lengths of the two strings?
a) O(1)
int get_min(int a, int b)
{ b) O(n+m)
if(a < b) c) O(mn)
return a; d) O(nlogm)
return b;
} Answer: c
int edit_distance(char *s1, char *s2)
Explanation: The time complexity of the
{
int len1,len2,i,j,min; Wagner–Fischer algorithm is O(mn).
len1 = strlen(s1);
len2 = strlen(s2); 7. What is the space complexity of the above
int arr[len1 + 1][len2 + 1]; implementation of Wagner–Fischer algorithm
for(i = 0;i <= len1; i++) where “m” and “n” are the lengths of the two
arr[i][0] = i;
for(i = 0; i <= len2; i++)
strings?
arr[0][i] = i; a) O(1)
for(i = 1; i <= len1; i++) b) O(n+m)
{ c) O(mn)
for(j = 1; j <= len2; j++) d) O(nlogm)
{
min = get_min(arr[i-1][j],a
rr[i][j-1]) + 1; Answer: c
if(s1[i - 1] == s2[j - 1]) Explanation: The space complexity of the
{ above Wagner–Fischer algorithm is O(mn).
if(arr[i-1][j-1] < min)
____________; 8. What is the output of the following code?
}
else

Downloaded From: https://cse-r17.blogspot.com 146


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

#include<stdio.h> Answer: a
#include<string.h> Explanation: The program prints the edit
int get_min(int a, int b)
{
distance between the strings “somestring” and
if(a < b) “anotherthing”, which is 6.
return a;
return b; 9. What is the value stored in arr[3][3] when
} the below code is executed?
int edit_distance(char *s1, char *s2)
{ #include<stdio.h>
int len1,len2,i,j,min; #include<string.h>
len1 = strlen(s1); int get_min(int a, int b)
len2 = strlen(s2); {
int arr[len1 + 1][len2 + 1]; if(a < b)
for(i = 0;i <= len1; i++) return a;
arr[i][0] = i; return b;
for(i = 0; i <= len2; i++) }
arr[0][i] = i; int edit_distance(char *s1, char *s2)
for(i = 1; i <= len1; i++) {
{ int len1,len2,i,j,min;
for(j = 1; j <= len2; j++) len1 = strlen(s1);
{ len2 = strlen(s2);
min = get_min(arr[i-1][j], int arr[len1 + 1][len2 + 1];
arr[i][j-1]) + 1; for(i = 0;i <= len1; i++)
if(s1[i - 1] == s2[j - 1]) arr[i][0] = i;
{ for(i = 0; i <= len2; i++)
if(arr[i-1][j-1] < min arr[0][i] = i;
) for(i = 1; i <= len1; i++)
min = arr[i-1][j-1] {
; for(j = 1; j <= len2; j++)
} {
else min = get_min(arr[i-1][j]
{ ,arr[i][j-1]) + 1;
if(arr[i-1][j-1] + 1 < if(s1[i - 1] == s2[j - 1]
min) )
min = arr[i-1][j-1] {
+ 1; if(arr[i-1][j-1] < m
} in)
arr[i][j] = min; min = arr[i-1][j-1
} ];
} }
return arr[len1][len2]; else
} {
int main() if(arr[i-1][j-1] + 1
{ < min)
char s1[] = "somestring", s2[] = "a min = arr[i-1][j-1]
notherthing"; + 1;
int ans = edit_distance(s1, s2); }
printf("%d",ans); arr[i][j] = min;
return 0; }
} }
return arr[len1][len2];
a) 6 }
b) 7 int main()
c) 8 {
char s1[] = "somestring", s2[] = "a
d) 9
notherthing";

Downloaded From: https://cse-r17.blogspot.com 147


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

int ans = edit_distance(s1, s2); return arr[len1][len2];


printf("%d",ans); }
return 0; int main()
} {
char s1[] = "abcd", s2[] = "dcba";
a) 1 int ans = edit_distance(s1, s2);
b) 2 printf("%d",ans);
return 0;
c) 3 }
d) 4
a) 1
Answer: c b) 2
Explanation: The value stored in arr[3][3] is c) 3
3. d) 4
10. What is the output of the following code? Answer: d
Explanation: The program prints the edit
#include<stdio.h>
#include<string.h> distance between the strings “abcd” and
int get_min(int a, int b) “dcba”, which is 4.
{
if(a < b)
return a; 1. Which of the following is NOT a Catalan
return b;
number?
}
int edit_distance(char *s1, char *s2) a) 1
{ b) 5
int len1,len2,i,j,min; c) 14
len1 = strlen(s1); d) 43
len2 = strlen(s2);
int arr[len1 + 1][len2 + 1];
for(i = 0;i <= len1; i++)
Answer: d
arr[i][0] = i; Explanation: Catalan numbers are given by:
for(i = 0; i <= len2; i++) (2n!)/((n+1)!n!).
arr[0][i] = i; For n = 0, we get C0 = 1.
for(i = 1; i <= len1; i++) For n = 3, we get C3 = 5.
{
for(j = 1; j <= len2; j++)
For n = 4, we get C4 = 14.
{ For n = 5, we get C3 = 42.
min = get_min(arr[i-1][j],a
rr[i][j-1]) + 1; 2. Which of the following numbers is the 6th
if(s1[i - 1] == s2[j - 1]) Catalan number?
{ a) 14
if(arr[i-1][j-1] < min)
min = arr[i-1][j-1]; b) 429
} c) 132
else d) 42
{
if(arr[i-1][j-1] + 1 < Answer: d
min)
min = arr[i-1][j-1]
Explanation: Catalan numbers are given by:
+ 1; (2n!)/((n+1)!n!).
} First Catalan number is given by n = 0.
arr[i][j] = min; So the 6th Catalan number will be given by n
} = 5, which is 42.
}

Downloaded From: https://cse-r17.blogspot.com 148


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

3. Which of the following is not an ______________________;


application of Catalan Numbers? }
return arr[n-1];
a) Counting the number of Dyck words
b) Counting the number of expressions }
containing n pairs of parenthesis int main()
c) Counting the number of ways in which a {
convex polygon can be cut into triangles by int ans, n = 8;
ans = cat_number(n);
connecting vertices with straight lines printf("%d\n",ans);
d) Creation of head and tail for a given return 0;
number of tosses }

Answer: d Which of the following lines completes the


Explanation: Counting the number of Dyck above code?
words, Counting the number of expressions a) arr[i] = arr[j] * arr[k];
containing n pairs of parenthesis, Counting b) arr[j] += arr[i] * arr[k];
the number of ways in which a convex c) arr[i] += arr[j] * arr[k].
polygon can be cut into triangles by d) arr[j] = arr[i] * arr[k];
connecting vertices with straight lines are the
applications of Catalan numbers where as Answer: c
creation of head and tails for a given number Explanation: The line arr[i] += arr[j] * arr[k]
of tosses is an application of Pascal’s triangle. reflects the recursive formula Cn = ∑Ci*C(n-
i).
4. Which of the following methods can be
used to find the nth Catalan number? 6. Which of the following implementations of
a) Recursion Catalan numbers has the smallest time
b) Binomial coefficients complexity?
c) Dynamic programming a) Dynamic programming
d) Recursion, Binomial Coefficients, b) Binomial coefficients
Dynamic programming c) Recursion
d) All have equal time complexity
Answer: d
Explanation: All of the mentioned methods Answer: b
can be used to find the nth Catalan number. Explanation: The time complexities are as
follows:
5. The recursive formula for Catalan number Dynamic programming: O(n2)
is given by Cn = ∑Ci*C(n-i). Recursion: Exponential
Consider the following dynamic Binomial coefficients: O(n).
programming implementation for Catalan
numbers: 7. What is the output of the following code?
#include<stdio.h> #include<stdio.h>
int cat_number(int n) int cat_number(int n)
{ {
int i,j,arr[n],k; int i,j,arr[n],k;
arr[0] = 1; arr[0] = 1;
for(i = 1; i < n; i++) for(i = 1; i < n; i++)
{ {
arr[i] = 0; arr[i] = 0;
for(j = 0,k = i - 1; j < i; j++, for(j = 0,k = i - 1; j < i; j++,
k--) k--)

Downloaded From: https://cse-r17.blogspot.com 149


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

arr[i] += arr[j] * arr[k]; }


} int main()
return arr[n-1]; {
} int ans, n = 10;
int main() ans = cat_number(n);
{ printf("%d\n",ans);
int ans, n = 8; return 0;
ans = cat_number(n); }
printf("%d\n",ans);
return 0; a) 14

M
} b) 42
c) 132
a) 42

O
d) 429
b) 132
c) 429

C
Answer: b
d) 1430 Explanation: The 6th Catalan number will be

T.
stored in arr[5], which is 42.
Answer: c
Explanation: The program prints the 8th 10. Which of the following errors will occur

O
Catalan number, which is 429. when the below code is executed?
8. Which of the following implementations of
Catalan numbers has the largest space
complexity(Don’t consider the stack space)?
a) Dynamic programming
SP
#include<stdio.h>
int cat_number(int n)
{
int i,j,arr[n],k;
G
arr[0] = 1;
b) Binomial coefficients
for(i = 1; i < n; i++)
c) Recursion
LO

{
d) All have equal space complexities arr[i] = 0;
for(j = 0,k = i - 1; j < i; j++,
Answer: a k--)
arr[i] += arr[j] * arr[k];
.B

Explanation: The space complexities are as


}
follows: return arr[n-1];
Dynamic programming: O(n) }
17

Recursion: O(1) int main()


Binomial coefficients: O(1). {
int ans, n = 100;
ans = cat_number(n);
-R

9. What will be the value stored in arr[5]


printf("%d\n",ans);
when the following code is executed? return 0;
}
SE

#include<stdio.h>
int cat_number(int n)
a) Segmentation fault
{
int i,j,arr[n],k; b) Array size too large
c) Integer value out of range
C

arr[0] = 1;
for(i = 1; i < n; i++) d) Array index out of range
{
arr[i] = 0; Answer: c
for(j = 0,k = i - 1; j < i; j++,
k--)
Explanation: The 100th Catalan number is
arr[i] += arr[j] * arr[k]; too large to be stored in an integer. So, the
} error produced will be integer value out of
return arr[n-1];

Downloaded From: https://cse-r17.blogspot.com 150


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

range.(It will be a logical error and the 4. Consider the following assembly line
compiler wont show it). problem:

time_to_reach[2][3] = {{17, 2, 7}, {19,


1. Which of the following methods can be 4, 9}}
used to solve the assembly line scheduling time_spent[2][4] = {{6, 5, 15, 7}, {5, 1
problem? 0, 11, 4}}
a) Recursion
b) Brute force entry_time[2] = {8, 10}
c) Dynamic programming
exit_time[2] = {10, 7}
d) All of the mentioned
num_of_stations = 4
Answer: d
Explanation: All of the above mentioned For the optimal solution which should be the
methods can be used to solve the assembly starting assembly line?
line scheduling problem. a) Line 1
b) Line 2
2. What is the time complexity of the brute c) All of the mentioned
force algorithm used to solve the assembly d) None of the mentioned
line scheduling problem?
a) O(1) Answer: b
b) O(n) Explanation: For the optimal solution, the
c) O(n2) starting assembly line is line 2.
d) O(2n)
5. Consider the following assembly line
Answer: d problem:
Explanation: In the brute force algorithm, all
time_to_reach[2][3] = {{17, 2, 7}, {19,
the possible ways are calculated which are of 4, 9}}
the order of 2n.
time_spent[2][4] = {{6, 5, 15, 7}, {5, 1
3. In the dynamic programming 0, 11, 4}}
implementation of the assembly line entry_time[2] = {8, 10}
scheduling problem, how many lookup tables
are required? exit_time[2] = {10, 7}
a) 0
b) 1 num_of_stations = 4
c) 2
For the optimal solution, which should be the
d) 3
exit assembly line?
Answer: c a) Line 1
Explanation: In the dynamic programming b) Line 2
implementation of the assembly line c) All of the mentioned
scheduling problem, 2 lookup tables are d) None of the mentioned
required one for storing the minimum time
Answer: b
and the other for storing the assembly line
Explanation: For the optimal solution, the
number.
exit assembly line is line 2.

Downloaded From: https://cse-r17.blogspot.com 151


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

6. Consider the following assembly line Which of the following lines should be
problem: inserted to complete the above code?
a) t2[i] = get_min(t2[i-1]+spent[1][i], t1[i-
time_to_reach[2][3] = {{17, 2, 7}, {19, 1]+reach[0][i-1]+spent[1][i])
4, 9}}
b) t2[i] = get_min(t2[i-1]+spent[1][i], t1[i-
time_spent[2][4] = {{6, 5, 15, 7}, {5, 1 1]+spent[1][i])
0, 11, 4}} c) t2[i] = get_min(t2[i-1]+spent[1][i], t1[i-
1]+reach[0][i-1])
entry_time[2] = {8, 10} d) none of the mentioned
exit_time[2] = {10, 7}
Answer: a
num_of_stations = 4 Explanation: The line t2[i] = get_min(t2[i-
1]+spent[1][i], t1[i-1]+reach[0][i-1]+spent[1]
What is the minimum time required to build [i]) should be added to complete the above
the car chassis? code.
a) 40
b) 41 8. What is the time complexity of the above
c) 42 dynamic programming implementation of the
d) 43 assembly line scheduling problem?
a) O(1)
Answer: d b) O(n)
Explanation: The minimum time required is c) O(n2)
43. d) O(n3)
The path is S2,1 -> S1,2 -> S2,3 -> S2,4,
where Si,j : i = line number, j = station Answer: b
number Explanation: The time complexity of the
above dynamic programming implementation
7. Consider the following code: of the assembly line scheduling problem is
#include<stdio.h>
O(n).
int get_min(int a, int b)
{ 9. What is the space complexity of the above
if(a<b) dynamic programming implementation of the
return a; assembly line scheduling problem?
return b; a) O(1)
}
int minimum_time_required(int reach[][3], b) O(n)
int spent[][4], int *entry, int *exit, in c) O(n2)
t n)
{
d) O(n3)
int t1[n], t2[n],i;
t1[0] = entry[0] + spent[0][0]; Answer: b
t2[0] = entry[1] + spent[1][0]; Explanation: The space complexity of the
for(i = 1; i < n; i++) above dynamic programming implementation
{ of the assembly line scheduling problem is
t1[i] = get_min(t1[i-1]+spent[0]
[i], t2[i-1]+reach[1][i-1]+spent[0][i]); O(n).
__________;
} 10. What is the output of the following code?
return get_min(t1[n-1]+exit[0], t2[n
-1]+exit[1]); #include<stdio.h>
} int get_min(int a, int b)

Downloaded From: https://cse-r17.blogspot.com 152


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

{ return a;
if(a<b) return b;
return a; }
return b; int minimum_time_required(int reach[][3],
} int spent[][4], int *entry, int *exit, in
int minimum_time_required(int reach[][3], t n)
int spent[][4], int *entry, int *exit, in {
t n) int t1[n], t2[n],i;
{ t1[0] = entry[0] + spent[0][0];
int t1[n], t2[n], i; t2[0] = entry[1] + spent[1][0];
t1[0] = entry[0] + spent[0][0]; for(i = 1; i < n; i++)
t2[0] = entry[1] + spent[1][0]; {
for(i = 1; i < n; i++) t1[i] = get_min(t1[i-1]+spent[0
{ ][i], t2[i-1]+reach[1][i-1]+spent[0][i]);
t1[i] = get_min(t1[i-1]+spent[0] t2[i] = get_min(t2[i-1]+spent[1
[i], t2[i-1]+reach[1][i-1]+spent[0][i]); ][i], t1[i-1]+reach[0][i-1]+spent[1][i]);
t2[i] = get_min(t2[i-1]+spent[1] }
[i], t1[i-1]+reach[0][i-1]+spent[1][i]); return get_min(t1[n-1]+exit[0], t2[n-
} 1]+exit[1]);
return get_min(t1[n-1]+exit[0], t2[n }
-1]+exit[1]); int main()
} {
int main() int time_to_reach[][3] = {{6, 1, 5},
{ {2, 4, 7}};
int time_to_reach[][3] = {{6, 1, 5}, int time_spent[][4] = {{6, 5, 4, 7},
{2, 4, 7}}; {5, 10, 2, 6}};
int time_spent[][4] = {{6, 5, 4, 7}, int entry_time[2] = {5, 6};
{5, 10, 2, 6}}; int exit_time[2] = {8, 9};
int entry_time[2] = {5, 6}; int num_of_stations = 4;
int exit_time[2] = {8, 9}; int ans = minimum_time_required(time
int num_of_stations = 4; _to_reach, time_spent, entry_time, exit_t
int ans = minimum_time_required(time_ ime, num_of_stations);
to_reach, time_spent, entry_time, exit_ti printf("%d",ans);
me, num_of_stations); return 0;
printf("%d",ans); }
return 0;
} a) 16
b) 18
a) 32 c) 20
b) 33 d) 22
c) 34
d) 35 Answer: c
Explanation: The value stored in t1[2] when
Answer: c the above code is executed is 20.
Explanation: The program prints the optimal
time required to build the car chassis, which 12. What is the value stored in t2[3] when the
is 34. following code is executed?
11. What is the value stored in t1[2] when the #include<stdio.h>
following code is executed? int get_min(int a, int b)
{
#include<stdio.h> if(a<b)
int get_min(int a, int b) return a;
{ return b;
if(a<b) }

Downloaded From: https://cse-r17.blogspot.com 153


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

int minimum_time_required(int reach[][3], int t1[n], t2[n], i;


int spent[][4], int *entry, int *exit, in t1[0] = entry[0] + spent[0][0];
t n) t2[0] = entry[1] + spent[1][0];
{ for(i = 1; i < n; i++)
int t1[n], t2[n],i; {
t1[0] = entry[0] + spent[0][0]; t1[i] = get_min(t1[i-1]+spent[0
t2[0] = entry[1] + spent[1][0]; ][i], t2[i-1]+reach[1][i-1]+spent[0][i]);
for(i = 1; i < n; i++) t2[i] = get_min(t2[i-1]+spent[1
{ ][i], t1[i-1]+reach[0][i-1]+spent[1][i]);
t1[i] = get_min(t1[i-1]+spent[0] }
[i], t2[i-1]+reach[1][i-1]+spent[0][i]); return get_min(t1[n-1]+exit[0], t2[
t2[i] = get_min(t2[i-1]+spent[1] n-1]+exit[1]);
[i], t1[i-1]+reach[0][i-1]+spent[1][i]); }
} int main()
return get_min(t1[n-1]+exit[0], t2[n {
-1]+exit[1]); int time_to_reach[][4] = {{16, 10, 5
} , 12},
int main() {12, 4, 17, 8}
{ };
int time_to_reach[][3] = {{6, 1, 5}, int time_spent[][5] = {{13, 5, 20, 1
{2, 4, 7}}; 9, 9},
int time_spent[][4] = {{6, 5, 4, 7}, {15, 10, 12, 16,
{5, 10, 2, 6}}; 13}};
int entry_time[2] = {5, 6}; int entry_time[2] = {12, 9};
int exit_time[2] = {8, 9}; int exit_time[2] = {10, 13};
int num_of_stations = 4; int num_of_stations = 5;
int ans = minimum_time_required(time_ int ans = minimum_time_required(time
to_reach, time_spent, entry_time, exit_ti _to_reach, time_spent, entry_time, exit_t
me, num_of_stations); ime, num_of_stations);
printf("%d",ans); printf("%d",ans);
return 0; return 0;
} }

a) 19 a) 62
b) 23 b) 69
c) 25 c) 75
d) 27 d) 88

Answer: c Answer: d
Explanation: The value stored in t2[3] when Explanation: The program prints the optimal
the above code is executed is 25. time required to build the car chassis, which
is 88.
13. What is the output of the following code?

#include<stdio.h> 1. Given a string, you have to find the


int get_min(int a, int b)
{
minimum number of characters to be inserted
if(a<b) in the string so that the string becomes a
return a; palindrome. Which of the following methods
return b; can be used to solve the problem?
} a) Greedy algorithm
int minimum_time_required(int reach[][4],
b) Recursion
int spent[][5], int *entry, int *exit, in
t n) c) Dynamic programming
{ d) Both recursion and dynamic programming

Downloaded From: https://cse-r17.blogspot.com 154


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: d Answer: b
Explanation: Dynamic programming and Explanation: The string can be converted to
recursion can be used to solve the problem. “efgfe” by inserting “f” or to “egfge” by
inserting “g”. Thus, only one insertion is
2. In which of the following cases the required.
minimum no of insertions to form palindrome
is maximum? 5. Consider the string “abbccbba”. What is
a) String of length one the minimum number of insertions required to
b) String with all same characters make the string a palindrome?

M
c) Palindromic string a) 0
d) Non palindromic string b) 1

O
c) 2
Answer: d d) 3

C
Explanation: In string of length one, string
with all same characters and a palindromic Answer: a

T.
string the no of insertions is zero since the Explanation: The given string is already a
strings are already palindromes. To convert a palindrome. So, no insertions are required.
non-palindromic string to a palindromic

O
string, the minimum length of string to be 6. Which of the following problems can be
added is 1 which is greater than all the other used to solve the minimum number of
above cases. Hence the minimum no of
insertions to form palindrome is maximum in
non-palindromic strings.
SP
insertions to form a palindrome problem?
a) Minimum number of jumps problem
b) Longest common subsequence problem
G
c) Coin change problem
3. In the worst case, the minimum number of d) Knapsack problems
LO

insertions to be made to convert the string


into a palindrome is equal to the length of the Answer: b
string. Explanation: A variation of longest common
subsequence can be used to solve the
.B

a) True
b) False minimum number of insertions to form a
palindrome problem.
17

Answer: b
Explanation: In the worst case, the minimum 7. Consider the following dynamic
number of insertions to be made to convert programming implementation:
-R

the string into a palindrome is equal to length


of the string minus one. For example, #include<stdio.h>
#include<string.h>
consider the string “abc”. The string can be int max(int a, int b)
SE

converted to “abcba” by inserting “a” and {


“b”. The number of insertions is two, which is if(a > b)
equal to length minus one. return a;
return b;
C

}
4. Consider the string “efge”. What is the
int min_ins(char *s)
minimum number of insertions required to {
make the string a palindrome? int len = strlen(s), i, j;
a) 0 int arr[len + 1][len + 1];
b) 1 char rev[len + 1];
strcpy(rev, s);
c) 2 strrev(rev);
d) 3 for(i = 0;i <= len; i++)

Downloaded From: https://cse-r17.blogspot.com 155


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

arr[i][0] = 0; int arr[len + 1][len + 1];


for(i = 0; i <= len; i++) char rev[len + 1];
arr[0][i] = 0; strcpy(rev, s);
for(i = 1; i <= len; i++) strrev(rev);
{ for(i = 0;i <= len; i++)
for(j = 1; j <= len; j++) arr[i][0] = 0;
{ for(i = 0; i <= len; i++)
if(s[i - 1] == rev[j - 1]) arr[0][i] = 0;
arr[i][j] = arr[i - 1][j for(i = 1; i <= len; i++)
- 1] + 1; {
else for(j = 1; j <= len; j++)
arr[i][j] = max(arr[i - {
1][j], arr[i][j - 1]); if(s[i - 1] == rev[j - 1])
} arr[i][j] = arr[i - 1][j
} - 1] + 1;
return _____________; else
} arr[i][j] = max(arr[i -
int main() 1][j], arr[i][j - 1]);
{ }
char s[] = "abcda"; }
int ans = min_ins(s); return len - arr[len][len];
printf("%d",ans); }
return 0; int main()
} {
char s[] = "abcda";
Which of the following lines should be added int ans = min_ins(s);
to complete the code? printf("%d",ans);
return 0;
a) arr[len][len] }
b) len + arr[len][len]
c) len a) O(1)
d) len – arr[len][len] b) O(n)
c) O(n2)
Answer: d
d) O(mn)
Explanation: arr[len][len] contains the length
of the longest palindromic subsequence. So, Answer: c
len – arr[len][len] gives the minimum number Explanation: The time complexity of the
of insertions required to form a palindrome. above dynamic programming implementation
8. What is the time complexity of the is O(n2).
following dynamic programming
implementation of the minimum number of 9. What is the space complexity of the
insertions to form a palindrome problem? following dynamic programming
implementation of the minimum number of
#include<stdio.h> insertions to form a palindrome problem?
#include<string.h>
int max(int a, int b) #include<stdio.h>
{ #include<string.h>
if(a > b) int max(int a, int b)
return a; {
return b; if(a > b)
} return a;
int min_ins(char *s) return b;
{ }
int len = strlen(s), i, j; int min_ins(char *s)

Downloaded From: https://cse-r17.blogspot.com 156


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

{ int len = strlen(s), i, j;


int len = strlen(s), i, j; int arr[len + 1][len + 1];
int arr[len + 1][len + 1]; char rev[len + 1];
char rev[len + 1]; strcpy(rev, s);
strcpy(rev, s); strrev(rev);
strrev(rev); for(i = 0;i <= len; i++)
for(i = 0;i <= len; i++) arr[i][0] = 0;
arr[i][0] = 0; for(i = 0; i <= len; i++)
for(i = 0; i <= len; i++) arr[0][i] = 0;
arr[0][i] = 0; for(i = 1; i <= len; i++)
for(i = 1; i <= len; i++) {
{ for(j = 1; j <= len; j++)
for(j = 1; j <= len; j++) {
{ if(s[i - 1] == rev[j - 1])
if(s[i - 1] == rev[j - 1]) arr[i][j] = arr[i - 1][j
arr[i][j] = arr[i - 1][j - 1] + 1;
- 1] + 1; else
else arr[i][j] = max(arr[i -
arr[i][j] = max(arr[i - 1][j], arr[i][j - 1]);
1][j], arr[i][j - 1]); }
} }
} return len - arr[len][len];
return len - arr[len][len]; }
} int main()
int main() {
{ char s[] = "abcda";
char s[] = "abcda"; int ans = min_ins(s);
int ans = min_ins(s); printf("%d",ans);
printf("%d",ans); return 0;
return 0; }
}
a) 1
a) O(1) b) 2
b) O(n) c) 3
c) O(n2) d) 4
d) O(mn)
Answer: b
Answer: c Explanation: The length of the longest
Explanation: The space complexity of the palindromic subsequence is 3. So, the output
above dynamic programming implementation will be 5 – 3 = 2.
is O(n2).
11. What is the value stored in arr[2][4] when
10. What is the output of the following code? the following code is executed?

#include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h>
int max(int a, int b) int max(int a, int b)
{ {
if(a > b) if(a > b)
return a; return a;
return b; return b;
} }
int min_ins(char *s) int min_ins(char *s)
{ {
int len = strlen(s), i, j;

Downloaded From: https://cse-r17.blogspot.com 157


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

int arr[len + 1][len + 1]; strrev(rev);


char rev[len + 1]; for(i = 0;i <= len; i++)
strcpy(rev, s); arr[i][0] = 0;
strrev(rev); for(i = 0; i <= len; i++)
for(i = 0;i <= len; i++) arr[0][i] = 0;
arr[i][0] = 0; for(i = 1; i <= len; i++)
for(i = 0; i <= len; i++) {
arr[0][i] = 0; for(j = 1; j <= len; j++)
for(i = 1; i <= len; i++) {
{ if(s[i - 1] == rev[j - 1])
for(j = 1; j <= len; j++) arr[i][j] = arr[i - 1][j
{ - 1] + 1;
if(s[i - 1] == rev[j - 1]) else
arr[i][j] = arr[i - 1][j arr[i][j] = max(arr[i -
- 1] + 1; 1][j], arr[i][j - 1]);
else }
arr[i][j] = max(arr[i - }
1][j], arr[i][j - 1]); return len - arr[len][len];
} }
} int main()
return len - arr[len][len]; {
} char s[] = "efgfe";
int main() int ans = min_ins(s);
{ printf("%d",ans);
char s[] = "abcda"; return 0;
int ans = min_ins(s); }
printf("%d",ans);
return 0; a) 0
} b) 2
c) 4
a) 2
d) 6
b) 3
c) 4 Answer: a
d) 5 Explanation: Since the string “efgfe” is
already a palindrome, the number of
Answer: a
insertions required is 0.
Explanation: The value stored in arr[2][4]
when the above code is executed is 2.
1. Given a 2D matrix, find a submatrix that
12. What is the output of the following code?
has the maximum sum. Which of the
#include<stdio.h> following methods can be used to solve this
#include<string.h> problem?
int max(int a, int b) a) Brute force
{ b) Recursion
if(a > b)
c) Dynamic programming
return a;
return b; d) Brute force, Recursion, Dynamic
} programming
int min_ins(char *s)
{ Answer: d
int len = strlen(s), i, j; Explanation: Brute force, Recursion and
int arr[len + 1][len + 1];
char rev[len + 1];
Dynamic programming can be used to find
strcpy(rev, s); the submatrix that has the maximum sum.

Downloaded From: https://cse-r17.blogspot.com 158


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

2. In which of the following cases, the one negative element). In this case, the sum
maximum sum rectangle is the 2D matrix of the elements of the maximum sum
itself? rectangle cannot be zero.
a) When all the elements are negative a) True
b) When all the elements are positive b) False
c) When some elements are positive and
some negative Answer: a
d) When diagonal elements are positive and Explanation: If a matrix contains all non-
rest are negative zero elements with at least one positive and at
least on negative element, then the sum of
Answer: a elements of the maximum sum rectangle
Explanation: When all the elements of a cannot be zero.
matrix are positive, the maximum sum
rectangle is the 2D matrix itself. 5. Consider the 2×3 matrix {{1,2,3},{1,2,3}}.
What is the sum of elements of the maximum
3. Consider the following statements and sum rectangle?
select which of the following statement are a) 3
true. b) 6
Statement 1: The maximum sum rectangle c) 12
can be 1X1 matrix containing the largest d) 18
element If the matrix size is 1X1
Statement 2: The maximum sum rectangle Answer: c
can be 1X1 matrix containing the largest Explanation: Since all the elements of the
element If all the elements are zero 2×3 matrix are positive, the maximum sum
Statement 3: The maximum sum rectangle rectangle is the matrix itself and the sum of
can be 1X1 matrix containing the largest elements is 12.
element If all the elements are negative
a) Only statement 1 is correct 6. Consider the 2×2 matrix {{-1,-2},{-3,-4}}.
b) Only statement 1 and Statement 2 are What is the sum of elements of the maximum
correct sum rectangle?
c) Only statement 1 and Statement 3 are a) 0
correct b) -1
d) Statement 1, Statement 2 and Statement 3 c) -7
are correct d) -12

Answer: d Answer: b
Explanation: If the matrix size is 1×1 then Explanation: Since all the elements of the
the element itself is the maximum sum of that 2×2 matrix are negative, the maximum sum
1×1 matrix. If all elements are zero, then the rectangle is {-1}, a 1×1 matrix containing the
sum of any submatrix of the given matrix is largest element. The sum of elements of the
zero. If all elements are negative, then the maximum sum rectangle is -1.
maximum element in that matrix is the
highest sum in that matrix which is again 1X1 7. Consider the 3×3 matrix {{2,1,-3},{6,3,4},
submatrix of the given matrix. Hence all three {-2,3,0}}. What is the sum of the elements of
statements are correct. the maximum sum rectangle?
a) 13
4. Consider a matrix in which all the elements b) 16
are non-zero(at least one positive and at least

Downloaded From: https://cse-r17.blogspot.com 159


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

c) 14 tmp[idx] = arr[idx][
d) 19 right];
}
else
Answer: c {
Explanation: The complete matrix represents for(idx = 0; idx < row
the maximum sum rectangle and it’s sum is ; idx++)
14. tmp[idx] += arr[idx
][right];
}
8. What is the time complexity of the brute
val = kadane_algo(tmp,row)
force implementation of the maximum sum ;
rectangle problem? if(val > mx_sm)
a) O(n) ______;
}
b) O(n2) }
c) O(n3) return mx_sm;
}
d) O(n4)
Which of the following lines should be
Answer: d
inserted to complete the above code?
Explanation: The time complexity of the
a) val = mx_sm
brute force implementation of the maximum
b) return val
sum rectangle problem is O(n4). c) mx_sm = val
d) return mx_sm
9. The dynamic programming implementation
of the maximum sum rectangle problem uses Answer: c
which of the following algorithm? Explanation: The line “mx_sm = val” should
a) Hirschberg’s algorithm be inserted to complete the above code.
b) Needleman-Wunsch algorithm
c) Kadane’s algorithm 11. What is the time complexity of the
d) Wagner Fischer algorithm following dynamic programming
implementation of the maximum sum
Answer: c rectangle problem?
Explanation: The dynamic programming
implementation of the maximum sum int max_sum_rectangle(int arr[][3],int ro
rectangle problem uses Kadane’s algorithm. w,int col)
{
10. Consider the following code snippet: int left, right, tmp[row], mx_sm =
INT_MIN, idx, val;
for(left = 0; left < col; left++)
int max_sum_rectangle(int arr[][3],int ro
{
w,int col)
for(right = left; right < col;
{
right++)
int left, right, tmp[row], mx_sm =
{
INT_MIN, idx, val;
if(right == left)
for(left = 0; left < col; left++)
{
{
for(idx = 0; idx < row
for(right = left; right < col;
; idx++)
right++)
tmp[idx] = arr[idx][
{
right];
if(right == left)
}
{
else
for(idx = 0; idx < row
{
; idx++)

Downloaded From: https://cse-r17.blogspot.com 160


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

for(idx = 0; idx < row val = kadane_algo(tmp,row)


; idx++) ;
tmp[idx] += arr[idx if(val > mx_sm)
][right]; mx_sm = val;
} }
val = kadane_algo(tmp,row) }
; return mx_sm;
if(val > mx_sm) }
mx_sm = val;
} a) O(row*col)
} b) O(row)
return mx_sm;
} c) O(col)
d) O(row*col*col)
a) O(row*col)
b) O(row) Answer: b
c) O(col) Explanation: The space complexity of the
d) O(row*col*col) above dynamic programming implementation
of the maximum sum rectangle problem is
Answer: d O(row).
Explanation: The time complexity of the
above dynamic programming implementation 13. What is the output of the following code?
of the maximum sum rectangle is
#include<stdio.h>
O(row*col*col). #include<limits.h>
int max_num(int a, int b)
12. What is the space complexity of the {
following dynamic programming if(a > b)
implementation of the maximum sum return a;
return b;
rectangle problem?
}
int kadane_algo(int *arr, int len)
int max_sum_rectangle(int arr[][3],int ro {
w,int col) int ans, sum, idx;
{ ans =0;
int left, right, tmp[row], mx_sm = sum =0;
INT_MIN, idx, val; for(idx =0; idx < len; idx++)
for(left = 0; left < col; left++) {
{ sum = max_num(0,sum + arr[idx])
for(right = left; right < col; ;
right++) ans = max_num(sum,ans);
{ }
if(right == left) return ans;
{ }
for(idx = 0; idx < row int max_sum_rectangle(int arr[][5],int ro
; idx++) w,int col)
tmp[idx] = arr[idx][ {
right]; int left, right, tmp[row], mx_sm =
} INT_MIN, idx, val;
else for(left = 0; left < col; left++)
{ {
for(idx = 0; idx < row for(right = left; right < col;
; idx++) right++)
tmp[idx] += arr[idx {
][right]; if(right == left)
} {

Downloaded From: https://cse-r17.blogspot.com 161


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

for(idx = 0; idx < ro sum =0;


w; idx++) for(idx =0; idx < len; idx++)
tmp[idx] = arr[idx][ {
right]; sum = max_num(0,sum + arr[idx])
} ;
else ans = max_num(sum,ans);
{ }
for(idx = 0; idx < r return ans;
ow; idx++) }
tmp[idx] += arr[id int max_sum_rectangle(int arr[][5],int ro
x][right]; w,int col)
} {
val = kadane_algo(tmp,row int left, right, tmp[row], mx_sm =
); INT_MIN, idx, val=0;
if(val > mx_sm) for(left = 0; left < col; left++)
mx_sm = val; {
} for(right = left; right < col;
} right++)
return mx_sm; {
} if(right == left)
int main() {
{ for(idx = 0; idx < row
int arr[2][5] ={{1, 2, -1, -4, -20 ; idx++)
}, {-4, -1, 1, 7, -6}}; tmp[idx] = arr[idx]
int row = 2, col = 5; [right];
int ans = max_sum_rectangle(arr,ro }
w,col); else
printf("%d",ans); {
return 0; for(idx = 0; idx < row
} ; idx++)
tmp[idx] += arr[idx
a) 7 ][right];
b) 8 }
val = kadane_algo(tmp,row)
c) 9 ;
d) 10 if(val > mx_sm)
mx_sm = val;
Answer: b }
Explanation: The program prints the sum of }
return mx_sm;
elements of the maximum sum rectangle,
}
which is 8. int main()
{
14. What is the output of the following code? int arr[4][5] ={{ 7, 1, -3, -6, -1
5},
#include<stdio.h> { 10, -6, 3, -4,
#include<limits.h> 11},
int max_num(int a, int b) { -2, -3, -1, 2, -5}
{ ,
if(a > b) { 3, 0, 1, 0, 3}}
return a; ;
return b; int row = 4, col = 5;
} int ans = max_sum_rectangle(arr,row
int kadane_algo(int *arr, int len) ,col);
{ printf("%d",ans);
int ans, sum, idx; return 0;
ans =0; }

Downloaded From: https://cse-r17.blogspot.com 162


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

a) 17 Answer: d
b) 18 Explanation: In the brute force
c) 19 implementation, all the possible subsets will
d) 20 be formed. This takes exponential time.

Answer: b 4. Consider a variation of the balanced


Explanation: The program prints the sum of partition problem in which we find two
elements of the maximum sum rectangle, subsets such that |S1 – S2| is minimum.
which is 18. Consider the array {1, 2, 3, 4, 5}. Which of
the following pairs of subsets is an optimal
solution for the above problem?
1. Given an array, check if the array can be a) {5, 4} & {3, 2, 1}
divided into two subsets such that the sum of b) {5} & {4, 3, 2, 1}
elements of the two subsets is equal. This is c) {4, 2} & {5, 3, 1}
the balanced partition problem. Which of the d) {5, 3} & {4, 2, 1}
following methods can be used to solve the
balanced partition problem? Answer: d
a) Dynamic programming Explanation: For S1 = {5, 3} and S2 = {4, 2,
b) Recursion 1}, sum(S1) – sum(S2) = 1, which is the
c) Brute force optimal solution.
d) Dynamic programming, Recursion, Brute
force 5. Consider the following code:

Answer: d #include<stdio.h>
int balanced_partition(int *arr, int len)
Explanation: All of the mentioned methods
{
can be used to solve the balanced partition int sm = 0, i, j;
problem. for(i = 0;i < len; i++)
sm += arr[i];
2. In which of the following cases, it is not if(sm % 2 != 0)
possible to have two subsets with equal sum? return 0;
int ans[sm/2 + 1][len + 1];
a) When the number of elements is odd for(i = 0; i <= len; i++)
b) When the number of elements is even ans[0][i] = 1;
c) When the sum of elements is odd for(i = 1; i <= sm/2; i++)
d) When the sum of elements is even ans[i][0] = 0;
for(i = 1; i <= sm/2; i++)
Answer: c {
for(j = 1;j <= len; j++)
Explanation: When the sum of all the {
elements is odd, it is not possible to have two ans[i][j] = ans[i][j-1];
subsets with equal sum. if(i >= arr[j - 1])
ans[i][j] = _____________
3. What is the time complexity of the brute __;
}
force algorithm used to solve the balanced }
partition problem? return ans[sm/2][len];
a) O(1) }
b) O(n) int main()
{
c) O(n2) int arr[] = {3, 4, 5, 6, 7, 1}, len
d) O(2n) = 6;
int ans = balanced_partition(arr,len

Downloaded From: https://cse-r17.blogspot.com 163


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

); int ans = balanced_partition(arr,len


if(ans == 0) );
printf("false"); if(ans == 0)
else printf("false");
printf("true"); else
return 0; printf("true");
} return 0;
}
Which of the following lines should be
inserted to complete the above code? a) O(sum)
a) ans[i – arr[j – 1]][j – 1] b) O(n)
b) ans[i][j] c) O(sum * n)
c) ans[i][j] || ans[i – arr[j – 1]][j – 1] d) O(sum + n)
d) ans[i][j] && ans[i – arr[j – 1]][j – 1]
Answer: c
Answer: c Explanation: The time complexity of the
Explanation: The line “ans[i][j] || ans[i – arr[j above dynamic programming implementation
– 1]][j – 1]” completes the above code. of the balanced partition problem is O(sum *
n).
6. What is the time complexity of the
following dynamic programming 7. What is the space complexity of the
implementation of the balanced partition following dynamic programming
problem where “n” is the number of elements implementation of the balanced partition
and “sum” is their sum? problem?

#include<stdio.h> #include<stdio.h>
int balanced_partition(int *arr, int len) int balanced_partition(int *arr, int len)
{ {
int sm = 0, i, j; int sm = 0, i, j;
for(i = 0;i < len; i++) for(i = 0;i < len; i++)
sm += arr[i]; sm += arr[i];
if(sm % 2 != 0) if(sm % 2 != 0)
return 0; return 0;
int ans[sm/2 + 1][len + 1]; int ans[sm/2 + 1][len + 1];
for(i = 0; i <= len; i++) for(i = 0; i <= len; i++)
ans[0][i] = 1; ans[0][i] = 1;
for(i = 1; i <= sm/2; i++) for(i = 1; i <= sm/2; i++)
ans[i][0] = 0; ans[i][0] = 0;
for(i = 1; i <= sm/2; i++) for(i = 1; i <= sm/2; i++)
{ {
for(j = 1;j <= len; j++) for(j = 1;j <= len; j++)
{ {
ans[i][j] = ans[i][j-1]; ans[i][j] = ans[i][j-1];
if(i >= arr[j - 1]) if(i >= arr[j - 1])
ans[i][j] = ans[i][j] || ans[i][j] = ans[i][j] ||
ans[i - arr[j - 1]][j - 1]; ans[i - arr[j - 1]][j - 1];
} }
} }
return ans[sm/2][len]; return ans[sm/2][len];
} }
int main() int main()
{ {
int arr[] = {3, 4, 5, 6, 7, 1}, len int arr[] = {3, 4, 5, 6, 7, 1}, len
= 6; = 6;

Downloaded From: https://cse-r17.blogspot.com 164


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

int ans = balanced_partition(arr,len else


); printf("true");
if(ans == 0) return 0;
printf("false"); }
else
printf("true"); a) True
return 0; b) False
}
Answer: a
a) O(sum)
b) O(n) Explanation: The partitions are S1 = {6, 7}
c) O(sum * n) and S2 = {1, 3, 4, 5} and the sum of each
d) O(sum + n) partition is 13. So, the array can be divided
into balanced partitions.
Answer: c
Explanation: The space complexity of the 9. What is the value stored in ans[3][3] when
above dynamic programming implementation the following code is executed?
of the balanced partition problem is O(sum * #include<stdio.h>
n). int balanced_partition(int *arr, int len)
{
8. What is the output of the following code? int sm = 0, i, j;
for(i = 0;i < len; i++)
#include<stdio.h> sm += arr[i];
int balanced_partition(int *arr, int len) if(sm % 2 != 0)
{ return 0;
int sm = 0, i, j; int ans[sm/2 + 1][len + 1];
for(i = 0;i < len; i++) for(i = 0; i <= len; i++)
sm += arr[i]; ans[0][i] = 1;
if(sm % 2 != 0) for(i = 1; i <= sm/2; i++)
return 0; ans[i][0] = 0;
int ans[sm/2 + 1][len + 1]; for(i = 1; i <= sm/2; i++)
for(i = 0; i <= len; i++) {
ans[0][i] = 1; for(j = 1;j <= len; j++)
for(i = 1; i <= sm/2; i++) {
ans[i][0] = 0; ans[i][j] = ans[i][j-1];
for(i = 1; i <= sm/2; i++) if(i >= arr[j - 1])
{ ans[i][j] = ans[i][j] ||
for(j = 1;j <= len; j++) ans[i - arr[j - 1]][j - 1];
{ }
ans[i][j] = ans[i][j-1]; }
if(i >= arr[j - 1]) return ans[sm/2][len];
ans[i][j] = ans[i][j] || }
ans[i - arr[j - 1]][j - 1]; int main()
} {
} int arr[] = {3, 4, 5, 6, 7, 1}, len
return ans[sm/2][len]; = 6;
} int ans = balanced_partition(arr,len
int main() );
{ if(ans == 0)
int arr[] = {3, 4, 5, 6, 7, 1}, len printf("false");
= 6; else
int ans = balanced_partition(arr,le printf("true");
n); return 0;
if(ans == 0) }
printf("false");

Downloaded From: https://cse-r17.blogspot.com 165


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

a) 0 = 6;
b) 1 int ans = balanced_partition(arr,len
);
c) -1 if(ans == 0)
d) -2 printf("false");
else
Answer: b printf("true");
Explanation: The value stored in ans[3][3] return 0;
indicates if a sum of 3 can be obtained using a }
subset of the first 3 elements. Since the sum
a) True
can be obtained the value stored is 1.
b) False
10. What is the sum of each of the balanced
Answer: a
partitions for the array {5, 6, 7, 10, 3, 1}?
Explanation: The array can be divided into
a) 16
two partitions S1 = {10, 6} and S2 = {5, 7, 3,
b) 32
1} and the sum of all the elements of each
c) 0
partition is 16. So, the answer is true.
d) 64
12. What is the output of the following code?
Answer: a
Explanation: The sum of all the elements of #include<stdio.h>
the array is 32. So, the sum of all the elements int balanced_partition(int *arr, int len)
of each partition should be 16. {
int sm = 0, i, j;
11. What is the output of the following code? for(i = 0;i < len; i++)
sm += arr[i];
if(sm % 2 != 0)
#include<stdio.h>
return 0;
int balanced_partition(int *arr, int len)
int ans[sm/2 + 1][len + 1];
{
for(i = 0; i <= len; i++)
int sm = 0, i, j;
ans[0][i] = 1;
for(i = 0;i < len; i++)
for(i = 1; i <= sm/2; i++)
sm += arr[i];
ans[i][0] = 0;
if(sm % 2 != 0)
for(i = 1; i <= sm/2; i++)
return 0;
{
int ans[sm/2 + 1][len + 1];
for(j = 1;j <= len; j++)
for(i = 0; i <= len; i++)
{
ans[0][i] = 1;
ans[i][j] = ans[i][j-1];
for(i = 1; i <= sm/2; i++)
if(i >= arr[j - 1])
ans[i][0] = 0;
ans[i][j] = ans[i][j] ||
for(i = 1; i <= sm/2; i++)
ans[i - arr[j - 1]][j - 1];
{
}
for(j = 1;j <= len; j++)
}
{
return ans[sm/2][len];
ans[i][j] = ans[i][j-1];
}
if(i >= arr[j - 1])
int main()
ans[i][j] = ans[i][j] ||
{
ans[i - arr[j - 1]][j - 1];
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8,
}
9}, len = 9;
}
int ans = balanced_partition(arr,len
return ans[sm/2][len];
);
}
if(ans == 0)
int main()
printf("false");
{
else
int arr[] = {5, 6, 7, 10, 3, 1}, len

Downloaded From: https://cse-r17.blogspot.com 166


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

printf("true"); c) 216
return 0; d) 81
}
Answer: c
a) True
Explanation: The total number of
b) False
permutations that can be obtained is 6 * 6 * 6
Answer: b = 216.
Explanation: Since the sum of all the
4. You have 2 dice each of them having 6
elements of the array is 45, the array cannot
faces numbered from 1 to 6. What is the
be divided into two partitions of equal sum
number of ways in which a sum of 11 can be
and the answer is false.
achieved?
a) 0
1. You are given n dice each having f faces. b) 1
You have to find the number of ways in c) 2
which a sum of S can be achieved. This is the d) 3
dice throw problem. Which of the following
Answer: c
methods can be used to solve the dice throw
Explanation: The sum of 11 can be achieved
problem?
when the dice show {6, 5} or {5, 6}.
a) Brute force
b) Recursion 5. There are n dice with f faces. The faces are
c) Dynamic programming numbered from 1 to f. What is the minimum
d) Brute force, Recursion and Dynamic possible sum that can be obtained when the n
Programming dice are rolled together?
a) 1
Answer: d
b) f
Explanation: Brute force, Recursion and
c) n
Dynamic Programming can be used to solve
d) n*f
the dice throw problem.
Answer: c
2. You have n dice each having f faces. What
Explanation: The sum will be minimum
is the number of permutations that can be
when all the faces show a value 1. The sum in
obtained when you roll the n dice together?
this case will be n.
a) n*n*n…f times
b) f*f*f…n times 6. There are n dice with f faces. The faces are
c) n*n*n…n times numbered from 1 to f. What is the maximum
d) f*f*f…f times possible sum that can be obtained when the n
dice are rolled together?
Answer: b
a) 1
Explanation: Each die can take f values and
b) f*f
there are n dice. So, the total number of
c) n*n
permutations is f*f*f…n times.
d) n*f
3. You have 3 dice each having 6 faces. What
Answer: d
is the number of permutations that can be
Explanation: The sum will be maximum
obtained when you roll the 3 dice together?
when all the faces show a value f. The sum in
a) 27
this case will be n*f.
b) 36

Downloaded From: https://cse-r17.blogspot.com 167


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

7. There are 10 dice having 5 faces. The faces Which of the following lines should be added
are numbered from 1 to 5. What is the to complete the above code?
number of ways in which a sum of 4 can be a) arr[num_of_dice][S]
achieved? b) arr[dice][sm]
a) 0 c) arr[dice][S]
b) 2 d) arr[S][dice]
c) 4
d) 8 Answer: a
Explanation: The line arr[num_of_dice][S]

M
Answer: a completes the above code.
Explanation: Since there are 10 dice and the

O
minimum value each die can take is 1, the 9. What is time complexity of the following
minimum possible sum is 10. Hence, a sum of dynamic programming implementation of the

C
4 cannot be achieved. dice throw problem where f is the number of
faces, n is the number of dice and s is the sum

T.
8. Consider the following dynamic to be found?
programming implementation of the dice
throw problem: #include<stdio.h>

O
int get_ways(int num_of_dice, int num_of_
#include<stdio.h> faces, int S)
int get_ways(int num_of_dice, int num_of_
faces, int S)
{
SP
{
int arr[num_of_dice + 1][S + 1];
int dice, face, sm;
for(dice = 0; dice <= num_of_dice; d
int arr[num_of_dice + 1][S + 1];
G
int dice, face, sm; ice++)
for(dice = 0; dice <= num_of_dice; d for(sm = 0; sm <= S; sm++)
LO

ice++) arr[dice][sm] = 0;
for(sm = 0; sm <= S; sm++) for(sm = 1; sm <= S; sm++)
arr[dice][sm] = 0; arr[1][sm] = 1;
for(sm = 1; sm <= S; sm++) for(dice = 2; dice <= num_of_dice; d
ice++)
.B

arr[1][sm] = 1;
for(dice = 2; dice <= num_of_dice; d {
ice++) for(sm = 1; sm <= S; sm++)
{
17

{
for(sm = 1; sm <= S; sm++) for(face = 1; face <= num_of
{ _faces && face < sm; face++)
for(face = 1; face <= num_of arr[dice][sm] += arr[dic
e - 1][sm - face];
-R

_faces && face < sm; face++)


arr[dice][sm] += arr[dic }
e - 1][sm - face]; }
} return arr[num_of_dice][S];
SE

} }
return _____________; int main()
} {
int main() int num_of_dice = 3, num_of_faces =
C

{ 4, sum = 6;
int num_of_dice = 3, num_of_faces = int ans = get_ways(num_of_dice, num_
4, sum = 6; of_faces, sum);
int ans = get_ways(num_of_dice, num_ printf("%d",ans);
of_faces, sum); return 0;
printf("%d",ans); }
return 0;
} a) O(n*f)
b) O(f*s)

Downloaded From: https://cse-r17.blogspot.com 168


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

c) O(n*s) Answer: c
d) O(n*f*s) Explanation: The space complexity of the
above dynamic programming implementation
Answer: d is O(n*s).
Explanation: The time complexity of the
above dynamic programming implementation 11. What is the output of the following code?
is O(n*f*s).
#include<stdio.h>
10. What is space complexity of the following int get_ways(int num_of_dice, int num_of_
faces, int S)
dynamic programming implementation of the {
dice throw problem where f is the number of int arr[num_of_dice + 1][S + 1];
faces, n is the number of dice and s is the sum int dice, face, sm;
to be found? for(dice = 0; dice <= num_of_dice; d
ice++)
#include<stdio.h> for(sm = 0; sm <= S; sm++)
int get_ways(int num_of_dice, int num_of_ arr[dice][sm] = 0;
faces, int S) for(sm = 1; sm <= S; sm++)
{ arr[1][sm] = 1;
int arr[num_of_dice + 1][S + 1]; for(dice = 2; dice <= num_of_dice; d
int dice, face, sm; ice++)
for(dice = 0; dice <= num_of_dice; d {
ice++) for(sm = 1; sm <= S; sm++)
for(sm = 0; sm <= S; sm++) {
arr[dice][sm] = 0; for(face = 1; face <= num_of
for(sm = 1; sm <= S; sm++) _faces && face < sm; face++)
arr[1][sm] = 1; arr[dice][sm] += arr[dic
for(dice = 2; dice <= num_of_dice; d e - 1][sm - face];
ice++) }
{ }
for(sm = 1; sm <= S; sm++) return arr[num_of_dice][S];
{ }
for(face = 1; face <= num_of int main()
_faces && face < sm; face++) {
arr[dice][sm] += arr[dic int num_of_dice = 3, num_of_faces =
e - 1][sm - face]; 4, sum = 6;
} int ans = get_ways(num_of_dice, num_
} of_faces, sum);
return arr[num_of_dice][S]; printf("%d",ans);
} return 0;
int main() }
{
int num_of_dice = 3, num_of_faces = a) 10
4, sum = 6; b) 12
int ans = get_ways(num_of_dice, num_ c) 14
of_faces, sum);
printf("%d",ans);
d) 16
return 0;
} Answer: a
Explanation: The output of the above code is
a) O(n*f) 10.
b) O(f*s)
c) O(n*s) 12. What will be the value stored in arr[2][2]
d) O(n*f*s) when the following code is executed?

Downloaded From: https://cse-r17.blogspot.com 169


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

#include<stdio.h> arr[dice][sm] = 0;
int get_ways(int num_of_dice, int num_of_ for(sm = 1; sm <= S; sm++)
faces, int S) arr[1][sm] = 1;
{ for(dice = 2; dice <= num_of_dice; d
int arr[num_of_dice + 1][S + 1]; ice++)
int dice, face, sm; {
for(dice = 0; dice <= num_of_dice; for(sm = 1; sm <= S; sm++)
dice++) {
for(sm = 0; sm <= S; sm++) for(face = 1; face <= num_of
arr[dice][sm] = 0; _faces && face < sm; face++)
for(sm = 1; sm <= S; sm++) arr[dice][sm] += arr[dic
arr[1][sm] = 1; e - 1][sm - face];
for(dice = 2; dice <= num_of_dice; }
dice++) }
{ return arr[num_of_dice][S];
for(sm = 1; sm <= S; sm++) }
{ int main()
for(face = 1; face <= num_o {
f_faces && face < sm; face++) int num_of_dice = 4, num_of_faces =
arr[dice][sm] += arr[di 6, sum = 3;
ce - 1][sm - face]; int ans = get_ways(num_of_dice, num_
} of_faces, sum);
} printf("%d",ans);
return arr[num_of_dice][S]; return 0;
} }
int main()
{ a) 0
int num_of_dice = 3, num_of_faces = b) 1
4, sum = 6;
int ans = get_ways(num_of_dice, num c) 2
_of_faces, sum); d) 3
printf("%d",ans);
return 0; Answer: a
} Explanation: The minimum possible sum is
4. So, the output for sum = 3 is 0.
a) 0
b) 1 14. What is the output of the following code?
c) 2
d) 3 #include<stdio.h>
int get_ways(int num_of_dice, int num_of_
Answer: b faces, int S)
Explanation: The value stored in arr[2][2] is {
int arr[num_of_dice + 1][S + 1];
1. int dice, face, sm;
for(dice = 0; dice <= num_of_dice;
13. What is the output of the following code? dice++)
for(sm = 0; sm <= S; sm++)
#include<stdio.h> arr[dice][sm] = 0;
int get_ways(int num_of_dice, int num_of_ for(sm = 1; sm <= S; sm++)
faces, int S) arr[1][sm] = 1;
{ for(dice = 2; dice <= num_of_dice;
int arr[num_of_dice + 1][S + 1]; dice++)
int dice, face, sm; {
for(dice = 0; dice <= num_of_dice; d for(sm = 1; sm <= S; sm++)
ice++) {
for(sm = 0; sm <= S; sm++) for(face = 1; face <= num_o

Downloaded From: https://cse-r17.blogspot.com 170


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

f_faces && face < sm; face++) a) 0


arr[dice][sm] += arr[dic b) 1
e - 1][sm - face];
}
c) 2
} d) 3
return arr[num_of_dice][S];
} Answer: c
int main() Explanation: The expression can be
{ parenthesized as T & (F | T) and (T & F) | T
int num_of_dice = 2, num_of_faces =
6, sum = 5; so that the output is T.
int ans = get_ways(num_of_dice, num
_of_faces, sum); 3. Consider the expression T & F ∧ T. What is
printf("%d",ans); the number of ways in which the expression
return 0; can be parenthesized so that the output is T
}
(true)?
a) 2 a) 0
b) 3 b) 1
c) 4 c) 2
d) 5 d) 3

Answer: c Answer: c
Explanation: The output of the above code is Explanation: The expression can be
4. parenthesized as (T & F) ∧ T or T & (F ∧ T),
so that the output is T.

1. You are given a boolean expression which 4. Consider the expression T | F ∧ T. In how
consists of operators &, | and ∧ (AND, OR many ways can the expression be
and XOR) and symbols T or F (true or false). parenthesized so that the output is F (false)?
You have to find the number of ways in a) 0
which the symbols can be parenthesized so b) 1
that the expression evaluates to true. This is c) 2
the boolean parenthesization problem. Which d) 3
of the following methods can be used to solve
the problem? Answer: b
a) Dynamic programming Explanation: The expression can be
b) Recursion parenthesized as (T | F) ∧ T, so that the output
c) Brute force is F (false).
d) Dynamic programming, Recursion and
Brute force 5. Which of the following gives the total
number of ways of parenthesizing an
Answer: d expression with n + 1 terms?
Explanation: Dynamic programming, a) n factorial
Recursion and Brute force can be used to b) n square
solve the Boolean parenthesization problem. c) n cube
d) nth catalan number
2. Consider the expression T & F | T. What is
the number of ways in which the expression Answer: d
can be parenthesized so that the output is T Explanation: The nth Catalan number gives
(true)?

Downloaded From: https://cse-r17.blogspot.com 171


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

the total number of ways of parenthesizing an {


expression with n + 1 terms. int pos = row + l;
int t_row_pos = True[ro
w][pos] + False[row][pos];
6. What is the maximum number of ways in int t_pos_col = True[po
which a boolean expression with n + 1 terms s+1][col] + False[pos+1][col];
can be parenthesized, such that the output is if(op[pos] == '|')
true? {
a) nth catalan number _______________;
}
b) n factorial if(op[pos] == '&')
c) n cube {
d) n square _______________;
}
Answer: a if(op[pos] == '^')
{
Explanation: The number of ways will be _______________;
maximum when all the possible }
parenthesizations result in a true value. The }
number of possible parenthesizations is given }
by the nth catalan number. }
return True[0][str_len-1];
}
7. Consider the following dynamic
programming implementation of the boolean Which of the following lines should be added
parenthesization problem: to complete the “if(op[pos] == ‘|’)” part of the
int count_bool_parenthesization(char *sym
code?
, char *op) a) False[row][col] += True[row][pos] *
{ False[pos+1][col];
int str_len = strlen(sym); True[row][col] += t_row_pos * t_pos_col +
int True[str_len][str_len],False[st False[row][pos] * False[pos+1][col];
r_len][str_len];
int row,col,length,l;
b) False[row][col] += False[row][pos] *
for(row = 0, col = 0; row < str_len True[pos+1][col];
; row++,col++) True[row][col] += t_row_pos * t_pos_col –
{ True[row][pos] * True[pos+1][col];
if(sym[row] == 'T') c) False[row][col] += True[row][pos] *
{
True[row][col] = 1;
True[pos+1][col];
False[row][col] = 0; True[row][col] += t_row_pos * t_pos_col +
} True[row][pos] * True[pos+1][col];
else d) False[row][col] += False[row][pos] *
{ False[pos+1][col];
True[row][col] = 0;
False[row][col] = 1;
True[row][col] += t_row_pos * t_pos_col –
} False[row][pos] * False[pos+1][col];
}
for(length = 1; length < str_len; l Answer: d
ength++) Explanation: The following lines should be
{ added:
for(row = 0, col = length; col
< str_len; col++, row++) False[row][col] += False[row][pos] *
{ False[pos+1][col];
True[row][col] = 0; True[row][col] += t_row_pos * t_pos_col +
False[row][col] = 0; False[row][pos] * False[pos+1][col];
for(l = 0; l < length; l++)

Downloaded From: https://cse-r17.blogspot.com 172


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

8. Which of the following lines should be return True[0][str_len-1];


added to complete the “if(op[k] == ‘&’)” part }
of the following code?
a) True[row][col] += False[row][pos] *
int count_bool_parenthesization(char *sym False[pos+1][col];
, char *op) False[row][col] += t_row_pos * t_pos_col –
{ True[row][pos] * True[pos+1][col];
int str_len = strlen(sym); b) True[row][col] += True[row][pos] *
int True[str_len][str_len],False[st
True[pos+1][col];

M
r_len][str_len];
int row,col,length,l; False[row][col] += t_row_pos * t_pos_col –
for(row = 0, col = 0; row < str_len True[row][pos] * True[pos+1][col];

O
; row++,col++) c) True[row][col] += True[row][pos] *
{ False[pos+1][col];
if(sym[row] == 'T')

C
{
False[row][col] += t_row_pos * t_pos_col –
True[row][col] = 1; False[row][pos] * True[pos+1][col];

T.
False[row][col] = 0; d) True[row][col] += False[row][pos] *
} True[pos+1][col];
else False[row][col] += t_row_pos * t_pos_col –

O
{
True[row][col] = 0;
False[row][pos] * True[pos+1][col];

}
}
False[row][col] = 1;

for(length = 1; length < str_len; l


SP
Answer: b
Explanation: The following lines should be
added:
G
ength++) True[row][col] += True[row][pos] *
{
for(row = 0, col = length; col True[pos+1][col];
LO

< str_len; col++, row++) False[row][col] += t_row_pos * t_pos_col –


{ True[row][pos] * True[pos+1][col];
True[row][col] = 0;
False[row][col] = 0; 9. What is the time complexity of the
.B

for(l = 0; l < length; l++)


{
following dynamic programming
int pos = row + l; implementation of the boolean
17

int t_row_pos = True[ro parenthesization problem?


w][pos] + False[row][pos];
int t_pos_col = True[po int count_bool_parenthesization(char *sym
s+1][col] + False[pos+1][col]; , char *op)
-R

if(op[pos] == '|') {
{ int str_len = strlen(sym);
_______________; int True[str_len][str_len],False[st
SE

} r_len][str_len];
if(op[pos] == '&') int row,col,length,l;
{ for(row = 0, col = 0; row < str_len
_______________; ; row++,col++)
} {
C

if(op[pos] == '^') if(sym[row] == 'T')


{ {
_______________; True[row][col] = 1;
} False[row][col] = 0;
} }
} else
} {
True[row][col] = 0;

Downloaded From: https://cse-r17.blogspot.com 173


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

False[row][col] = 1; Answer: d
} Explanation: The time complexity of the
}
for(length = 1; length < str_len; l
above dynamic programming implementation
ength++) is O(n3).
{
for(row = 0, col = length; col 10. What is the space complexity of the
< str_len; col++, row++)
{
following dynamic programming
True[row][col] = 0; implementation of the boolean
False[row][col] = 0; parenthesization problem?
for(l = 0; l < length; l++)
{ int count_bool_parenthesization(char *sym
int pos = row + l; , char *op)
int t_row_pos = True[ro {
w][pos] + False[row][pos]; int str_len = strlen(sym);
int t_pos_col = True[po int True[str_len][str_len],False[st
s+1][col] + False[pos+1][col]; r_len][str_len];
if(op[pos] == '|') int row,col,length,l;
{ for(row = 0, col = 0; row < str_len
False[row][col] += ; row++,col++)
False[row][pos] * False[pos+1][col]; {
True[row][col] += t if(sym[row] == 'T')
_row_pos * t_pos_col - False[row][pos] * {
False[pos+1][col];; True[row][col] = 1;
} False[row][col] = 0;
if(op[pos] == '&') }
{ else
True[row][col] += Tr {
ue[row][pos] * True[pos+1][col]; True[row][col] = 0;
False[row][col] += t False[row][col] = 1;
_row_pos * t_pos_col - True[row][pos] * T }
rue[pos+1][col]; }
} for(length = 1; length < str_len; l
if(op[pos] == '^') ength++)
{ {
True[row][col] += Tr for(row = 0, col = length; col
ue[row][pos] * False[pos+1][col] + False[ < str_len; col++, row++)
row][pos] * True[pos + 1][col]; {
False[row][col] += T True[row][col] = 0;
rue[row][pos] * True[pos+1][col] + False[ False[row][col] = 0;
row][pos] * False[pos+1][col]; for(l = 0; l < length; l++)
} {
} int pos = row + l;
} int t_row_pos = True[ro
} w][pos] + False[row][pos];
return True[0][str_len-1]; int t_pos_col = True[po
} s+1][col] + False[pos+1][col];
if(op[pos] == '|')
a) O(1) {
b) O(n) False[row][col] +=
False[row][pos] * False[pos+1][col];
c) O(n2) True[row][col] += t
d) O(n3) _row_pos * t_pos_col - False[row][pos] *
False[pos+1][col];;
}
if(op[pos] == '&')

Downloaded From: https://cse-r17.blogspot.com 174


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

{ False[row][col] = 1;
True[row][col] += Tr }
ue[row][pos] * True[pos+1][col]; }
False[row][col] += t for(length = 1; length < str_len; le
_row_pos * t_pos_col - True[row][pos] * T ngth++)
rue[pos+1][col]; {
} for(row = 0, col = length; col <
if(op[pos] == '^') str_len; col++, row++)
{ {
True[row][col] += Tr True[row][col] = 0;
ue[row][pos] * False[pos+1][col] + False[ False[row][col] = 0;
row][pos] * True[pos + 1][col]; for(l = 0; l < length; l++)
False[row][col] += T {
rue[row][pos] * True[pos+1][col] + False[ int pos = row + l;
row][pos] * False[pos+1][col]; int t_row_pos = True[row
} ][pos] + False[row][pos];
} int t_pos_col = True[pos
} +1][col] + False[pos+1][col];
} if(op[pos] == '|')
return True[0][str_len-1]; {
} False[row][col] += F
alse[row][pos] * False[pos+1][col];
a) O(1) True[row][col] += t_
b) O(n) row_pos * t_pos_col - False[row][pos] * F
alse[pos+1][col];
c) O(n2) }
d) O(n3) if(op[pos] == '&')
{
True[row][col] += Tr
Answer: c ue[row][pos] * True[pos+1][col];
Explanation: The space complexity of the False[row][col] += t
above dynamic programming implementation _row_pos * t_pos_col - True[row][pos] * T
rue[pos+1][col];
is O(n2). }
if(op[pos] == '^')
11. What is the output of the following code? {
True[row][col] += Tr
#include<stdio.h> ue[row][pos] * False[pos+1][col] + False[
#include<string.h> row][pos] * True[pos + 1][col];
int count_bool_parenthesization(char *sym False[row][col] += T
, char *op) rue[row][pos] * True[pos+1][col] + False[
{ row][pos] * False[pos+1][col];
int str_len = strlen(sym); }
int True[str_len][str_len],False[str }
_len][str_len]; }
int row,col,length,l; }
for(row = 0, col = 0; row < str_len; return True[0][str_len-1];
row++,col++) }
{ int main()
if(sym[row] == 'T') {
{ char sym[] = "TTTT";
True[row][col] = 1; char op[] = "|^^";
False[row][col] = 0; int ans = count_bool_parenthesizatio
} n(sym,op);
else printf("%d",ans);
{ return 0;
True[row][col] = 0; }

Downloaded From: https://cse-r17.blogspot.com 175


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

a) 1 the minimum edge from the vertex in MST to


b) 2 vertex not in MST. From, figure shown below
c) 3 weight of MST = 27.
d) 4

Answer: d
Explanation: The output of the above
program is 4.

1. Which of the following is true? 3. Worst case is the worst case time
a) Prim’s algorithm initialises with a vertex complexity of Prim’s algorithm if adjacency
b) Prim’s algorithm initialises with a edge matrix is used?
c) Prim’s algorithm initialises with a vertex a) O(log V)
which has smallest edge
b) O(V2)
d) Prim’s algorithm initialises with a forest
c) O(E2)
Answer: a d) O(V log E)
Explanation: Steps in Prim’s algorithm: (I)
Select any vertex of given graph and add it to Answer: b
MST (II) Add the edge of minimum weight Explanation: Use of adjacency matrix
from a vertex not in MST to the vertex in provides the simple implementation of the
MST; (III) It MST is complete the stop, Prim’s algorithm. In Prim’s algorithm, we
otherwise go to step (II). need to search for the edge with a minimum
for that vertex. So, worst case time
2. Consider the given graph. complexity will be O(V2), where V is the
number of vertices.

4. Prim’s algorithm is a ______


a) Divide and conquer algorithm
b) Greedy algorithm
c) Dynamic Programming
d) Approximation algorithm

Answer: b
Explanation: Prim’s algorithm uses a greedy
algorithm approach to find the MST of the
What is the weight of the minimum spanning connected weighted graph. In greedy method,
tree using the Prim’s algorithm,starting from we attempt to find an optimal solution in
vertex a? stages.
a) 23
b) 28 5. Prim’s algorithm resembles Dijkstra’s
c) 27 algorithm.
d) 11 a) True
b) False
Answer: c
Explanation: In Prim’s algorithm, we select a Answer: a
vertex and add it to the MST. Then we add Explanation: In Prim’s algorithm, the MST is

Downloaded From: https://cse-r17.blogspot.com 176


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

constructed starting from a single vertex and So, the MST contains edges (4-3)(3-2)(2-1)
adding in new edges to the MST that link the (1-5).
partial tree to a new vertex outside of the
MST. And Dijkstra’s algorithm also rely on 8. Prim’s algorithm is also known as
the similar approach of finding the next __________
closest vertex. So, Prim’s algorithm a) Dijkstra–Scholten algorithm
resembles Dijkstra’s algorithm. b) Borůvka’s algorithm
c) Floyd–Warshall algorithm
6. Kruskal’s algorithm is best suited for the d) DJP Algorithm
sparse graphs than the prim’s algorithm.
a) True Answer: d
b) False Explanation: The Prim’s algorithm was
developed by Vojtěch Jarník and it was latter
Answer: a discovered by the duo Prim and Dijkstra.
Explanation: Prim’s algorithm and Kruskal’s Therefore, Prim’s algorithm is also known as
algorithm perform equally in case of the DJP Algorithm.
sparse graphs. But Kruskal’s algorithm is
simpler and easy to work with. So, it is best 9. Prim’s algorithm can be efficiently
suited for sparse graphs. implemented using _____ for graphs with
greater density.
7. Consider the graph shown below. a) d-ary heap
b) linear search
c) fibonacci heap
d) binary search

Answer: a
Explanation: In Prim’s algorithm, we add the
minimum weight edge for the chosen vertex
which requires searching on the array of
weights. This searching can be efficiently
implemented using binary heap for dense
graphs. And for graphs with greater density,
Which of the following edges form the MST Prim’s algorithm can be made to run in linear
of the given graph using Prim’a algorithm, time using d-ary heap(generalization of
starting from vertex 4. binary heap).
a) (4-3)(5-3)(2-3)(1-2)
b) (4-3)(3-5)(5-1)(1-2) 10. Which of the following is false about
c) (4-3)(3-5)(5-2)(1-5) Prim’s algorithm?
d) (4-3)(3-2)(2-1)(1-5) a) It is a greedy algorithm
b) It constructs MST by selecting edges in
Answer: d increasing order of their weights
Explanation: The MST for the given graph c) It never accepts cycles in the MST
using Prim’s algorithm starting from vertex 4 d) It can be implemented using the Fibonacci
is, heap

Answer: b
Explanation: Prim’s algorithm can be
implemented using Fibonacci heap and it

Downloaded From: https://cse-r17.blogspot.com 177


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

never accepts cycles. And Prim’s algorithm c) 15


follows greedy approach. Prim’s algorithms d) 19
span from one vertex to another.
Answer: d
Explanation: Kruskal’s algorithm constructs
1. Kruskal’s algorithm is used to ______ the minimum spanning tree by constructing
a) find minimum spanning tree by adding the edges to spanning tree one-one
b) find single source shortest path by one. The MST for the given graph is,
c) find all pair shortest path algorithm
d) traverse the graph

Answer: a
Explanation: The Kruskal’s algorithm is used
to find the minimum spanning tree of the
connected graph. It construct the MST by
finding the edge having the least possible
weight that connects two trees in the forest.
So, the weight of the MST is 19.
2. Kruskal’s algorithm is a ______
a) divide and conquer algorithm 4. What is the time complexity of Kruskal’s
b) dynamic programming algorithm algorithm?
c) greedy algorithm a) O(log V)
d) approximation algorithm b) O(E log V)
c) O(E2)
Answer: c d) O(V log E)
Explanation: Kruskal’s algorithm uses a
greedy algorithm approach to find the MST Answer: b
of the connected weighted graph. In the Explanation: Kruskal’s algorithm involves
greedy method, we attempt to find an optimal sorting of the edges, which takes O(E logE)
solution in stages. time, where E is a number of edges in graph
and V is the number of vertices. After sorting,
3. Consider the given graph. all edges are iterated and union-find
algorithm is applied. union-find algorithm
requires O(logV) time. So, overall Kruskal’s
algorithm requires O(E log V) time.

5. Consider the following graph. Using


Kruskal’s algorithm, which edge will be
selected first?

What is the weight of the minimum spanning


tree using the Kruskal’s algorithm?
a) 24
b) 23

Downloaded From: https://cse-r17.blogspot.com 178


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

spanning tree is shown below.

So, the edges in the MST are, (B-E)(G-E)(E-


F)(D-F).

7. Which of the following is true?


a) Prim’s algorithm can also be used for
disconnected graphs
a) GF
b) DE b) Kruskal’s algorithm can also run on the
c) BE disconnected graphs
c) Prim’s algorithm is simpler than Kruskal’s
d) BG
algorithm
Answer: c d) In Kruskal’s sort edges are added to MST
Explanation: In Krsuskal’s algorithm the in decreasing order of their weights
edges are selected and added to the spanning
Answer: b
tree in increasing order of their weights.
Explanation: Prim’s algorithm iterates from
Therefore, the first edge selected will be the
one node to another, so it can not be applied
minimal one. So, correct option is BE.
for disconnected graph. Kruskal’s algorithm
6. Which of the following edges form can be applied to the disconnected graphs to
minimum spanning tree on the graph using construct the minimum cost forest. Kruskal’s
kruskals algorithm? algorithm is comparatively easier and simpler
than prim’s algorithm.

8. Which of the following is false about the


Kruskal’s algorithm?
a) It is a greedy algorithm
b) It constructs MST by selecting edges in
increasing order of their weights
c) It can accept cycles in the MST
d) It uses union-find data structure

Answer: c
Explanation: Kruskal’s algorithm is a greedy
algorithm to construct the MST of the given
a) (B-E)(G-E)(E-F)(D-F) graph. It constructs the MST by selecting
b) (B-E)(G-E)(E-F)(B-G)(D-F) edges in increasing order of their weights and
c) (B-E)(G-E)(E-F)(D-E) rejects an edge if it may form the cycle. So,
d) (B-E)(G-E)(E-F)(D-F)(D-G) using Kruskal’s algorithm is never formed.

Answer: a 9. Kruskal’s algorithm is best suited for the


Explanation: Using Krushkal’s algorithm on dense graphs than the prim’s algorithm.
the given graph, the generated minimum

Downloaded From: https://cse-r17.blogspot.com 179


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

a) True Answer: b
b) False Explanation: Minimum spanning tree is a
spanning tree with the lowest cost among all
Answer: b the spacing trees. Sum of all of the edges in
Explanation: Prim’s algorithm outperforms the spanning tree is the cost of the spanning
the Kruskal’s algorithm in case of the dense tree. There can be many minimum spanning
graphs. It is significantly faster if graph has trees for a given graph.
more edges than the Kruskal’s algorithm.
3. Consider a complete graph G with 4
10. Consider the following statements. vertices. The graph G has ____ spanning
S1. Kruskal’s algorithm might produce a non- trees.
minimal spanning tree. a) 15
S2. Kruskal’s algorithm can efficiently b) 8
implemented using the disjoint-set data c) 16
structure. d) 13
a) S1 is true but S2 is false
b) Both S1 and S2 are false Answer: c
c) Both S1 and S2 are true Explanation: A graph can have many
d) S2 is true but S1 is false spanning trees. And a complete graph with n
vertices has n(n-2) spanning trees. So, the
Answer: d
complete graph with 4 vertices has 4(4-2) = 16
Explanation: In Kruskal’s algorithm, the
spanning trees.
disjoint-set data structure efficiently identifies
the components containing a vertex and adds
4. The travelling salesman problem can be
the new edges. And Kruskal’s algorithm
solved using _________
always finds the MST for the connected
a) A spanning tree
graph.
b) A minimum spanning tree
c) Bellman – Ford algorithm
d) DFS traversal
1. Which of the following is false in the case
of a spanning tree of a graph G? Answer: b
a) It is tree that spans G
Explanation: In the travelling salesman
b) It is a subgraph of the G
problem we have to find the shortest possible
c) It includes every vertex of the G
route that visits every city exactly once and
d) It can be either cyclic or acyclic
returns to the starting point for the given a set
of cities. So, travelling salesman problem can
Answer: d
be solved by contracting the minimum
Explanation: A graph can have many
spanning tree.
spanning trees. Each spanning tree of a graph
G is a subgraph of the graph G, and spanning
5. Consider the graph M with 3 vertices. Its
trees include every vertex of the gram.
adjacency matrix is shown below. Which of
Spanning trees are always acyclic.
the following is true?
2. Every graph has only one minimum
spanning tree.
a) True
b) False

Downloaded From: https://cse-r17.blogspot.com 180


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

a) Graph M has no minimum spanning tree Answer: a


b) Graph M has a unique minimum spanning Explanation: A subgraph is a graph formed
trees of cost 2 from a subset of the vertices and edges of the
c) Graph M has 3 distinct minimum spanning original graph. And the subset of vertices
trees, each of cost 2 includes all endpoints of the subset of the
d) Graph M has 3 spanning trees of different edges. So, we can say MST of a graph is a
costs subgraph when all weights in the original
graph are positive.
Answer: c
Explanation: Here all non-diagonal elements 8. Consider the graph shown below. Which of
in the adjacency matrix are 1. So, every the following are the edges in the MST of the
vertex is connected every other vertex of the given graph?
graph. And, so graph M has 3 distinct
minimum spanning trees.

6. Consider a undirected graph G with


vertices { A, B, C, D, E}. In graph G, every
edge has distinct weight. Edge CD is edge a) (a-c)(c-d)(d-b)(d-b)
with minimum weight and edge AB is edge b) (c-a)(a-d)(d-b)(d-e)
with maximum weight. Then, which of the c) (a-d)(d-c)(d-b)(d-e)
following is false? d) (c-a)(a-d)(d-c)(d-b)(d-e)
a) Every minimum spanning tree of G must
contain CD Answer: c
b) If AB is in a minimum spanning tree, then Explanation: The minimum spanning tree of
its removal must disconnect G the given graph is shown below. It has cost
c) No minimum spanning tree contains AB 56.
d) G has a unique minimum spanning tree

Answer: c
Explanation: Every MST will contain CD as
it is smallest edge. So, Every minimum
spanning tree of G must contain CD is true.
And G has a unique minimum spanning tree
is also true because the graph has edges with
distinct weights. So, no minimum spanning
tree contains AB is false.
9. Which of the following is not the algorithm
7. If all the weights of the graph are positive, to find the minimum spanning tree of the
then the minimum spanning tree of the graph given graph?
is a minimum cost subgraph. a) Boruvka’s algorithm
a) True b) Prim’s algorithm
b) False c) Kruskal’s algorithm
d) Bellman–Ford algorithm

Downloaded From: https://cse-r17.blogspot.com 181


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: d c) Greedy algorithm


Explanation: The Boruvka’s algorithm, d) Backtracking
Prim’s algorithm and Kruskal’s algorithm are
the algorithms that can be used to find the Answer: c
minimum spanning tree of the given graph. Explanation: Greedy algorithm is used to
The Bellman-Ford algorithm is used to find solve this problem. We first sort items
the shortest path from the single source to all according to their value/weight ratio and then
other vertices. add item with highest ratio until we cannot
add the next item as a whole. At the end, we
10. Which of the following is false? add the next item as much as we can.
a) The spanning trees do not have any cycles
b) MST have n – 1 edges if the graph has n 3. What is the objective of the knapsack
edges problem?
c) Edge e belonging to a cut of the graph if a) To get maximum total value in the
has the weight smaller than any other edge in knapsack
the same cut, then the edge e is present in all b) To get minimum total value in the
the MSTs of the graph knapsack
d) Removing one edge from the spanning tree c) To get maximum weight in the knapsack
will not make the graph disconnected d) To get minimum weight in the knapsack

Answer: d Answer: a
Explanation: Every spanning tree has n – 1 Explanation: The objective is to fill the
edges if the graph has n edges and has no knapsack of some given volume with
cycles. The MST follows the cut property, different materials such that the value of
Edge e belonging to a cut of the graph if has selected items is maximized.
the weight smaller than any other edge in the
same cut, then the edge e is present in all the 4. Which of the following statement about 0/1
MSTs of the graph. knapsack and fractional knapsack problem is
correct?
a) In 0/1 knapsack problem items are
1. Fractional knapsack problem is also known divisible and in fractional knapsack items are
as __________ indivisible
a) 0/1 knapsack problem b) Both are the same
b) Continuous knapsack problem c) 0/1 knapsack is solved using a greedy
c) Divisible knapsack problem algorithm and fractional knapsack is solved
d) Non continuous knapsack problem using dynamic programming
d) In 0/1 knapsack problem items are
Answer: b indivisible and in fractional knapsack items
Explanation: Fractional knapsack problem is are divisible
also called continuous knapsack problem.
Fractional knapsack is solved using dynamic Answer: d
programming. Explanation: In fractional knapsack problem
we can partially include an item into the
2. Fractional knapsack problem is solved knapsack whereas in 0/1 knapsack we have to
most efficiently by which of the following either include or exclude the item wholly.
algorithm?
a) Divide and conquer 5. Time complexity of fractional knapsack
b) Dynamic programming problem is ____________

Downloaded From: https://cse-r17.blogspot.com 182


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

a) O(n log n) we get better results with a fractional


b) O(n) knapsack.
c) O(n2)
d) O(nW) 9. The main time taking step in fractional
knapsack problem is ___________
Answer: a a) Breaking items into fraction
Explanation: As the main time taking a step b) Adding items into knapsack
is of sorting so it defines the time complexity c) Sorting
of our code. So the time complexity will be d) Looping through sorted items
O(n log n) if we use quick sort for sorting.
Answer: c
6. Fractional knapsack problem can be solved Explanation: The main time taking step is to
in time O(n). sort the items according to their value/weight
a) True ratio. It defines the time complexity of the
b) False code.

Answer: a 10. Given items as {value,weight} pairs


Explanation: It is possible to solve the {{60,20},{50,25},{20,5}}. The capacity of
problem in O(n) time by adapting the knapsack=40. Find the maximum value
algorithm for finding weighted medians. output assuming items to be divisible and
nondivisible respectively.
7. Given items as {value,weight} pairs a) 100, 80
{{40,20},{30,10},{20,5}}. The capacity of b) 110, 70
knapsack=20. Find the maximum value c) 130, 110
output assuming items to be divisible. d) 110, 80
a) 60
b) 80 Answer: d
c) 100 Explanation: Assuming items to be divisible-
d) 40 The value/weight ratio are {3, 2, 4}.So we
include third and first items wholly. So, now
Answer: a only 15 units of volume are left for second
Explanation: The value/weight ratio are- item. So we include it partially.
{2,3,4}. So we include the second and third Final volume =
items wholly into the knapsack. This leaves 20+60+50x(15/25)=80+30=110
only 5 units of volume for the first item. So Assuming items to be indivisible- In this case
we include the first item partially. we will have to leave one item due to
Final value = 20+30+(40/4)=60. insufficient capacity.
Final volume = 60 + 20 = 80.
8. The result of the fractional knapsack is
greater than or equal to 0/1 knapsack. Sanfoundry Global Education & Learning
a) True Series – Data Structures & Algorithms.
b) False

Answer: a
Explanation: As fractional knapsack gives
extra liberty to include the object partially
which is not possible with 0/1 knapsack, thus
UNIT IV ITERATIVE
IMPROVEMENT

Downloaded From: https://cse-r17.blogspot.com 183


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

1. Given G is a bipartite graph and the among the following is correct?


bipartitions of this graphs are U and V a) A
respectively. What is the relation between b) B
them? c) C
a) Number of vertices in U = Number of d) D
vertices in V
b) Sum of degrees of vertices in U = Sum of Answer: c
degrees of vertices in V Explanation: We can prove it in this
c) Number of vertices in U > Number of following way. Let ‘1’ be a vertex in bipartite
vertices in V set X and let ‘2’ be a vertex in the bipartite
d) Nothing can be said set Y. Therefore the bipartite set X contains
all odd numbers and the bipartite set Y
Answer: b contains all even numbers. Now let us
Explanation: We can prove this by induction. consider a graph of odd cycle (a triangle).
By adding one edge, the degree of vertices in There exists an edge from ‘1’ to ‘2’, ‘2’ to ‘3’
U is equal to 1 as well as in V. Let us assume and ‘3’ to ‘1’. The latter case (‘3’ to ‘1’)
that this is true for n-1 edges and add one makes an edge to exist in a bipartite set X
more edge. Since the given edge adds exactly itself. Therefore telling us that graphs with
once to both U and V we can tell that this odd cycles are not bipartite.
statement is true for all n vertices.
4. A complete bipartite graph is a one in
2. A k-regular bipartite graph is the one in which each vertex in set X has an edge with
which degree of each vertices is k for all the set Y. Let n be the total number of vertices.
vertices in the graph. Given that the For maximum number of edges, the total
bipartitions of this graph are U and V number of vertices hat should be present on
respectively. What is the relation between set X is?
them? a) n
a) Number of vertices in U=Number of b) n/2
vertices in V c) n/4
b) Number of vertices in U not equal to d) data insufficient
number of vertices in V
c) Number of vertices in U always greater Answer: b
than the number of vertices in V Explanation: We can prove this by calculus.
d) Nothing can be said Let x be the total number of vertices on set X.
Therefore set Y will have n-x. We have to
Answer: a maximize x*(n-x). This is true when x=n/2.
Explanation: We know that in a bipartite
graph sum of degrees of vertices in U=sum of 5. When is a graph said to be bipartite?
degrees of vertices in V. Given that the graph a) If it can be divided into two independent
is a k-regular bipartite graph, we have k* sets A and B such that each edge connects a
(number of vertices in U)=k*(number of vertex from to A to B
vertices in V). b) If the graph is connected and it has odd
number of vertices
3. There are four students in a class namely c) If the graph is disconnected
A, B, C and D. A tells that a triangle is a d) If the graph has at least n/2 vertices whose
bipartite graph. B tells pentagon is a bipartite degree is greater than n/2
graph. C tells square is a bipartite graph. D
tells heptagon is a bipartite graph. Who

Downloaded From: https://cse-r17.blogspot.com 184


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: a Answer: a
Explanation: A graph is said to be bipartite if Explanation: If a graph is such that there
it can be divided into two independent sets A exists a path which visits every edge atleast
and B such that each edge connects a vertex once, then it is said to be Eulerian. Taking an
from A to B. example of a square, the given question
evaluates to yes.
6. Are trees bipartite?
a) Yes 10. A graph is found to be 2 colorable. What
b) No can be said about that graph?

M
c) Yes if it has even number of vertices a) The given graph is eulerian
d) No if it has odd number of vertices b) The given graph is bipartite

O
c) The given graph is hamiltonian
Answer: a d) The given graph is planar

C
Explanation: Condition needed is that there
should not be an odd cycle. But in a tree there Answer: b

T.
are no cycles at all. Hence it is bipartite. Explanation: A graph is said to be colorable
if two vertices connected by an edge are
7. A graph has 20 vertices. The maximum never of the same color. 2 colorable mean that

O
number of edges it can have is? (Given it is this can be achieved with just 2 colors.
bipartite)
a) 100
b) 140
c) 80
SP
1. Which type of graph has no odd cycle in it?
a) Bipartite
G
d) 20 b) Histogram
c) Cartesian
LO

Answer: a d) Pie
Explanation: Let the given bipartition X have
x vertices, then Y will have 20-x vertices. We Answer: a
need to maximize x*(20-x). This will be Explanation: The graph is known as Bipartite
.B

maxed when x=10. if the graph does not contain any odd length
cycle in it. Odd length cycle means a cycle
17

8. Given that a graph contains no odd cycle. with the odd number of vertices in it.
Is it enough to tell that it is bipartite?
a) Yes 2. What type of graph has chromatic number
b) No less than or equal to 2?
-R

a) Histogram
Answer: a b) Bipartite
SE

Explanation: It is required that the graph is c) Cartesian


connected also. If it is not then it cannot be d) Tree
called a bipartite graph.
Answer: b
C

9. Can there exist a graph which is both Explanation: A graph is known as bipartite
eulerian and is bipartite? graph if and only if it has the total chromatic
a) Yes number less than or equal to 2. The smallest
b) No number of graphs needed to color the graph is
c) Yes if it has even number of edges chromatic number.
d) Nothing can be said

Downloaded From: https://cse-r17.blogspot.com 185


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

3. Which of the following is the correct type c) Heap


of spectrum of the bipartite graph? d) Bipartite
a) Symmetric
b) Anti – Symmetric Answer: d
c) Circular Explanation: The Konig’s theorem given the
d) Exponential equivalence relation between the minimum
vertex cover and the maximum matching in
Answer: a graph theory. Bipartite graph has a size of
Explanation: The spectrum of the bipartite minimum vertex cover equal to maximum
graph is symmetric in nature. The spectrum is matching.
the property of graph that are related to
polynomial, Eigen values, Eigen vectors of 7. Which theorem gives the relation between
the matrix related to graph. the minimum vertex cover and maximum
matching?
4. Which of the following is not a property of a) Konig’s Theorem
the bipartite graph? b) Kirchhoff’s Theorem
a) No Odd Cycle c) Kuratowski’s Theorem
b) Symmetric spectrum d) Kelmans Theorem
c) Chromatic Number Is Less Than or Equal
to 2 Answer: a
d) Asymmetric spectrum Explanation: The Konig’s theorem given the
equivalence relation between the minimum
Answer: d vertex cover and the maximum matching in
Explanation: A graph is known to be graph theory. Bipartite graph has a size of
bipartite if it has odd length cycle number. It minimum vertex cover equal to maximum
also has symmetric spectrum and the bipartite matching.
graph contains the total chromatic number
less than or equal to 2. 8. Which of the following is not a property of
perfect graph?
5. Which one of the following is the a) Compliment of Line Graph of Bipartite
chromatic number of bipartite graph? Graph
a) 1 b) Compliment of Bipartite Graph
b) 4 c) Line Graph of Bipartite Graph
c) 3 d) Line Graph
d) 5
Answer: d
Answer: a Explanation: TThe Compliment of Line
Explanation: A graph is known as bipartite Graph of Bipartite Graph, Compliment of
graph if and only if it has the total chromatic Bipartite Graph, Line Graph of Bipartite
number less than or equal to 2. The smallest Graph and every Bipartite Graph is known as
number of graphs needed to color the graph is a perfect graph in graph theory. Normal line
the chromatic number. graph is not a perfect graph whereas line
perfect graph is a graph whose line graph is a
6. Which graph has a size of minimum vertex perfect graph.
cover equal to maximum matching?
a) Cartesian 9. Which of the following graphs don’t have
b) Tree chromatin number less than or equal to 2?
a) Compliment of Line Graph of Bipartite

Downloaded From: https://cse-r17.blogspot.com 186


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Graph b) 1
b) Compliment of Bipartite Graph c) 2
c) Line Graph of Bipartite Graph d) 3
d) Wheel graph
Answer: c
Answer: d Explanation: The perfect bipartite graph has
Explanation: The perfect bipartite graph has clique size 2. So the clique size of
chromatic number 2. Also, the Compliment of Compliment of Line Graph of Bipartite
Line Graph of Bipartite Graph, Compliment Graph, Compliment of Bipartite Graph, Line
of Bipartite Graph, Line Graph of Bipartite Graph of Bipartite Graph and every Bipartite
Graph and every Bipartite Graph is known as Graph is 2.
perfect graph in graph theory. Wheel graph
Wn has chromatin number 3 if n is odd and 4 13. It is possible to have a negative chromatic
if n is even. number of bipartite graph.
a) True
10. Which of the following has maximum b) False
clique size 2?
a) Perfect graph Answer: b
b) Tree Explanation: A graph is known as bipartite
c) Histogram graph if and only if it has the total chromatic
d) Cartesian number less than or equal to 2. The smallest
number of graphs needed to color the graph is
Answer: a the chromatic number. But the chromatic
Explanation: The perfect bipartite graph has number cannot be negative.
clique size 2. Also, the clique size of
Compliment of Line Graph of Bipartite 14. Every Perfect graph has forbidden graph
Graph, Compliment of Bipartite Graph, Line characterization.
Graph of Bipartite Graph and every Bipartite a) True
Graph is 2. b) False

11. What is the chromatic number of Answer: a


compliment of line graph of bipartite graph? Explanation: Berge theorem proves the
a) 0 forbidden graph characterization of every
b) 1 perfect graphs. Because of that reason every
c) 2 bipartite graph is perfect graph.
d) 3
15. Which structure can be modelled by using
Answer: c Bipartite graph?
Explanation: The perfect bipartite graph has a) Hypergraph
chromatic number 2. So the Compliment of b) Perfect Graph
Line Graph of Bipartite Graph, Compliment c) Hetero Graph
of Bipartite Graph, Line Graph of Bipartite d) Directed Graph
Graph and every Bipartite Graph has
chromatic number 2. Answer: a
Explanation: A combinatorial structure such
12. What is the clique size of the line graph of as Hypergraph can be made using the
bipartite graph? bipartite graphs. A hypergraph in graph
a) 0

Downloaded From: https://cse-r17.blogspot.com 187


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

theory is a type of graph in which edge can b) n2 + 2


join any number of vertices.
c) n2 / 4
d) n3
1. Which type of graph has all the vertex of
the first set connected to all the vertex of the Answer: c
second set? Explanation: A n vertex triangle free graph
a) Bipartite contains a total of n2 / 4 number of edges.
b) Complete Bipartite This is stated by Mantel’s Theorem which is a
c) Cartesian special case in Turan’s theorem for r=2.
d) Pie
5. Which graph is used to define the claw free
Answer: b graph?
Explanation: The graph is known as Bipartite a) Bipartite Graph
if the graph does not contain any odd length b) Claw Graph
cycle in it. The complete bipartite graph has c) Star Graph
all the vertex of first set connected to all the d) Cartesian Graph
vertex of second set.
Answer: b
2. Which graph is also known as biclique? Explanation: Star is a complete bipartite
a) Histogram graph with one internal node and k leaves.
b) Complete Bipartite Star with three edges is called a claw. Hence
c) Cartesian this graph is used to define claw free graph.
d) Tree
6. What is testing of a complete bipartite
Answer: b subgraph in a bipartite graph problem called?
Explanation: A graph is known as complete a) P Problem
bipartite graph if and only if it has all the b) P-Complete Problem
vertex of first set connected to all the vertex c) NP Problem
of second set. Complete Bipartite graph is d) NP-Complete Problem
also known as Biclique.
Answer: d
3. Which term defines all the complete Explanation: NP stands for nondeterministic
bipartite graph that are trees? polynomial time. In a bipartite graph, the
a) Symmetric testing of a complete bipartite subgraph in a
b) Anti – Symmetric bipartite graph is an NP-Complete Problem.
c) Circular
d) Stars 7. Which graph cannot contain K3, 3 as a
minor of graph?
Answer: d a) Planar Graph
Explanation: Star is a complete bipartite b) Outer Planar Graph
graph with one internal node and k leaves. c) Non Planar Graph
Therefore, all complete bipartite graph which d) Inner Planar Graph
is trees are known as stars in graph theory.
Answer: a
4. How many edges does a n vertex triangle Explanation: Minor graph is formed by
free graph contains? deleting certain number of edges from a
a) n2 graph or by deleting certain number off

Downloaded From: https://cse-r17.blogspot.com 188


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

vertices from a graph. Hence Planar graph c) 0


cannot contain K3, 3 as a minor graph. d) 2

8. Which of the following is not an Eigen Answer: b


value of the adjacency matrix of the complete Explanation: The adjacency matrix is a
bipartite graph? square matrix that is used to represent a finite
a) (nm)1/2 graph. The multiplicity of the adjacency
b) (-nm)1/2 matrix off complete bipartite graph with
c) 0 Eigen Value 0 is n + m – 2.
d) nm
12. Which of the following is not an Eigen
Answer: d value of the Laplacian matrix of the complete
Explanation: The adjacency matrix is a bipartite graph?
square matrix that is used to represent a finite a) n + m
graph. Therefore, the Eigen values for the b) n
c) 0
complete bipartite graph is found to be
d) n*m
(nm)1/2, (-nm)1/2, 0.
Answer: d
9. Which complete graph is not present in Explanation: The laplacian matrix is used to
minor of Outer Planar Graph? represent a finite graph in the mathematical
a) K3, 3 field of Graph Theory. Therefore, the Eigen
b) K3, 1 values for the complete bipartite graph is
c) K3, 2 found to be n + m, n, m, 0.
d) K1, 1
13. What is the multiplicity for the laplacian
Answer: c matrix of the complete bipartite graph for n
Explanation: Minor graph is formed by Eigen value?
deleting certain number of edges from a a) 1
graph or by deleting certain number off b) m-1
vertices from a graph. Hence Outer Planar c) n-1
graph cannot contain K3, 2 as a minor graph. d) 0
10. Is every complete bipartite graph a Moore Answer: b
Graph. Explanation: The laplacian matrix is used to
a) True represent a finite graph in the mathematical
b) False field of Graph Theory. The multiplicity of the
laplacian matrix of complete bipartite graph
Answer: a
with Eigen Value n is m-1.
Explanation: In graph theory, Moore graph is
defined as a regular graph that has a degree d 14. Is it true that every complete bipartite
and diameter k. therefore, every complete graph is a modular graph.
bipartite graph is a Moore Graph. a) True
b) False
11. What is the multiplicity for the adjacency
matrix of complete bipartite graph for 0 Eigen Answer: a
value? Explanation: Yes, the modular graph in
a) 1 graph theory is defined as an undirected
b) n + m – 2

Downloaded From: https://cse-r17.blogspot.com 189


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

graph in which all three vertices have at least 3. What is the source?
one median vertex. So all complete bipartite a) Vertex with no incoming edges
graph is called modular graph. b) Vertex with no leaving edges
c) Centre vertex
15. How many spanning trees does a d) Vertex with the least weight
complete bipartite graph contain?
a) nm Answer: a
b) mn-1 * nn-1 Explanation: Vertex with no incoming edges
c) 1 is called as a source. Vertex with no leaving
d) 0 edges is called as a sink.

Answer: b 4. Which algorithm is used to solve a


Explanation: Spanning tree of a given graph maximum flow problem?
is defined as the subgraph or the tree with all a) Prim’s algorithm
the given vertices but having minimum b) Kruskal’s algorithm
c) Dijkstra’s algorithm
number of edges. So, there are a total of mn-1 d) Ford-Fulkerson algorithm
* nn-1 spanning trees for a complete bipartite
graph. Answer: d
Explanation: Ford-fulkerson algorithm is
used to compute the maximum feasible flow
1. What does Maximum flow problem between a source and a sink in a network.
involve?
a) finding a flow between source and sink that 5. Does Ford- Fulkerson algorithm use the
is maximum idea of?
b) finding a flow between source and sink a) Naïve greedy algorithm approach
that is minimum b) Residual graphs
c) finding the shortest path between source c) Minimum cut
and sink d) Minimum spanning tree
d) computing a minimum spanning tree
Answer: b
Answer: a Explanation: Ford-Fulkerson algorithm uses
Explanation: The maximum flow problem the idea of residual graphs which is an
involves finding a feasible flow between a extension of naïve greedy approach allowing
source and a sink in a network that is undo operations.
maximum and not minimum.
6. The first step in the naïve greedy algorithm
2. A network can have only one source and is?
one sink. a) analysing the zero flow
a) False b) calculating the maximum flow using trial
b) True and error
c) adding flows with higher values
Answer: b d) reversing flow if required
Explanation: A network can have only one
source and one sink inorder to find the Answer: a
feasible flow in a weighted connected graph. Explanation: The first step in the naïve
greedy algorithm is to start with the zero flow
followed by adding edges with higher values.

Downloaded From: https://cse-r17.blogspot.com 190


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

7. Under what condition can a vertex combine 10. In what time can an augmented path be
and distribute flow in any manner? found?
a) It may violate edge capacities a) O(|E| log |V|)
b) It should maintain flow conservation b) O(|E|)
c) The vertex should be a source vertex c) O(|E|2)
d) The vertex should be a sink vertex d) O(|E|2 log |V|)
Answer: b Answer: b
Explanation: A vertex can combine and Explanation: An augmenting path can be
distribute flow in any manner but it should found in O(|E|) mathematically by an
not violate edge capacities and it should unweighted shortest path algorithm.
maintain flow conservation.
11. Dinic’s algorithm runs faster than the
8. Find the maximum flow from the following Ford-Fulkerson algorithm.
graph. a) true
b) false

Answer: a
Explanation: Dinic’s algorithm includes
construction of level graphs and resLidual
graphs and finding of augmenting paths along
with blocking flow and is faster than the
Ford-Fulkerson algorithm.

12. What is the running time of an


a) 22 unweighted shortest path algorithm whose
b) 17 augmenting path is the path with the least
c) 15 number of edges?
d) 20 a) O(|E|)
b) O(|E||V|)
Answer: c c) O(|E|2|V|)
Explanation: Initially, zero flow is computed. d) O(|E| log |V|)
Then, computing flow= 7+1+5+2=15. Hence,
maximum flow=15. Answer: c
Explanation: Each augmenting step takes
9. A simple acyclic path between source and O(|E|) using an unweighted shortest path
sink which pass through only positive algorithm yielding a O(|E|2|V|) bound on the
weighted edges is called? running time.
a) augmenting path
b) critical path 13. Who is the formulator of Maximum flow
c) residual path problem?
d) maximum path a) Lester R. Ford and Delbert R. Fulkerson
b) T.E. Harris and F.S. Ross
Answer: a c) Y.A. Dinitz
Explanation: Augmenting path between d) Kruskal
source and sink is a simple path without
cycles. Path consisting of zero slack edges is Answer: b
called critical path. Explanation: The first ever people to

Downloaded From: https://cse-r17.blogspot.com 191


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

formulate Maximum flow problem were T.E. c) Ford-Fulkerson algorithm


Harris and F.S. Ross. Lester R. Ford and d) Prim’s algorithm
Delbert R. Fulkerson formulated Ford-
Fulkerson algorithm. Answer: a
Explanation: Stable marriage problem uses
14. What is the running time of Dinic’s Gale-Shapley algorithm. Maximum flow
blocking flow algorithm? problem uses Ford-Fulkerson algorithm.
a) O(V2E) Prim’s algorithm involves minimum spanning
b) O(VE2) tree.
c) O(V3) 3. An optimal solution satisfying men’s
d) O(E max |f|) preferences is said to be?
a) Man optimal
Answer: a b) Woman optimal
Explanation: The running time of Dinic’s c) Pair optimal
blocking flow algorithm is O(V2E). The d) Best optimal
running of Ford-Fulkerson algorithm is O(E
max |f|). Answer: a
Explanation: An optimal solution satisfying
15. How many constraints does flow have? men’s preferences are said to be man optimal.
a) one An optimal solution satisfying woman’s
b) three preferences are said to be woman optimal.
c) two
d) four 4. When a free man proposes to an available
woman, which of the following happens?
Answer: c a) She will think and decide
Explanation: A flow is a mapping which b) She will reject
follows two constraints- conservation of c) She will replace her current mate
flows and capacity constraints. d) She will accept

Answer: d
1. Stable marriage problem is an example of? Explanation: When a man proposes to an
a) Branch and bound algorithm available woman, she will accept his proposal
b) Backtracking algorithm irrespective of his position on his preference
c) Greedy algorithm list.
d) Divide and conquer algorithm
5. If there are n couples who would prefer
Answer: b each other to their actual marriage partners,
Explanation: Stable marriage problem is an then the assignment is said to be unstable.
example for recursive algorithm because it a) True
recursively uses backtracking algorithm to b) False
find an optimal solution.
Answer: a
2. Which of the following algorithms does Explanation: If there are n couples such that
Stable marriage problem uses? a man and a woman are not married, and if
a) Gale-Shapley algorithm they prefer each other to their actual partners,
b) Dijkstra’s algorithm the assignment is unstable.

Downloaded From: https://cse-r17.blogspot.com 192


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

6. How many 2*2 matrices are used in this 9. Consider the following ranking matrix.
problem?
a) 1
b) 2
c) 3
d) 4

Answer: b
Explanation: Two 2*2 matrices are used.
One for men representing corresponding
woman and ranking and the other for women.

7. What happens when a free man approaches Assume that M1 and W2 are married. Now,
a married woman? M2 approaches W2. Which of the following
a) She simply rejects him happens?
b) She simply replaces her mate with him a) W2 replaces M1 with M2
c) She goes through her preference list and b) W2 rejects M2
accordingly, she replaces her current mate c) W2 accepts both M1 and M2
with him d) W2 rejects both M1 and M2
d) She accepts his proposal
Answer: a
Answer: c Explanation: W2 is married to M1. But the
Explanation: If the preference of the man is preference of W2 has M2 before M1. Hence,
greater, she replaces her current mate with W2 replaces M1 with M2.
him, leaving her current mate free.
10. Consider the following ranking matrix.
8. In case of stability, how many symmetric
possibilities of trouble can occur?
a) 1
b) 2
c) 4
d) 3

Answer: b
Explanation: Possibilities- There might be a
woman pw, preferred to w by m, who herself
prefers m to be her husband and the same
applies to man as well. Assume that M1 and W1 are married and M2
and W3 are married. Now, whom will M3
approach first?
a) W1
b) W2
c) W3
d) All three

Answer: c
Explanation: M3 will approach W3 first.
Since W3 is married and since her preference

Downloaded From: https://cse-r17.blogspot.com 193


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

list has her current mate before M3, she Answer: a


rejects his proposal. Explanation: Choice of school by students is
the most related example in the given set of
11. Who formulated a straight forward options since both school and students will
backtracking scheme for stable marriage have a preference list.
problem?
a) McVitie and Wilson 15. What is the efficiency of Gale-Shapley
b) Gale algorithm used in stable marriage problem?
c) Ford and Fulkerson a) O(N)
d) Dinitz b) O(N log N)
c) O(N2)
Answer: a d) O(log N)
Explanation: McVitie and Wilson formulated
a much faster straight forward backtracking Answer: c
scheme for stable marriage problem. Ford and Explanation: The time efficiency of Gale-
Fulkerson formulated Maximum flow Shapley algorithm is mathematically found to
problem.
be O(N2) where N denotes stable marriage
12. Can stable marriage cannot be solved problem.
using branch and bound algorithm.
a) True
1. _____________ is a matching with the
b) False
largest number of edges.
a) Maximum bipartite matching
Answer: b
b) Non-bipartite matching
Explanation: Stable marriage problem can be
c) Stable marriage
solved using branch and bound approach
d) Simplex
because branch and bound follows
backtracking scheme with a limitation factor. Answer: a
Explanation: Maximum bipartite matching
13. What is the prime task of the stable
matches two elements with a property that no
marriage problem?
two edges share a vertex.
a) To provide man optimal solution
b) To provide woman optimal solution
2. Maximum matching is also called as
c) To determine stability of marriage
maximum cardinality matching.
d) To use backtracking approach
a) True
b) False
Answer: c
Explanation: The prime task of stable Answer: a
marriage problem is to determine stability of Explanation: Maximum matching is also
marriage (i.e) finding a man and a woman
called as maximum cardinality matching (i.e.)
who prefer each other to others.
matching with the largest number of edges.
14. Which of the following problems is 3. How many colours are used in a bipartite
related to stable marriage problem? graph?
a) Choice of school by students a) 1
b) N-queen problem b) 2
c) Arranging data in a database c) 3
d) Knapsack problem d) 4

Downloaded From: https://cse-r17.blogspot.com 194


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: b Answer: c
Explanation: A bipartite graph is said to be Explanation: A simple path from a free
two-colourable so that every edge has its vertex in V to a free vertex in U whose edges
vertices coloured in different colours. alternate between edges not in M and edges in
M is called a augmenting path.
4. What is the simplest method to prove that a
graph is bipartite? 8. A matching M is maximal if and only if
a) It has a cycle of an odd length there exists no augmenting path with respect
b) It does not have cycles to M.
c) It does not have a cycle of an odd length a) True
d) Both odd and even cycles are formed b) False

Answer: c Answer: a
Explanation: It is not difficult to prove that a Explanation: According to the theorem
graph is bipartite if and only if it does not discovered by the French mathematician
have a cycle of an odd length. Claude Berge, it means that the current
matching is maximal if there is no
5. A matching that matches all the vertices of augmenting path.
a graph is called?
a) Perfect matching 9. Which one of the following is an
b) Cardinality matching application for matching?
c) Good matching a) Proposal of marriage
d) Simplex matching b) Pairing boys and girls for a dance
c) Arranging elements in a set
Answer: a d) Finding the shortest traversal path
Explanation: A matching that matches all the
vertices of a graph is called perfect matching. Answer: b
Explanation: Pairing boys and girls for a
6. What is the length of an augmenting path? dance is a traditional example for matching.
a) Even Proposal of marriage is an application of
b) Odd stable marriage problem.
c) Depends on graph
d) 1 10. Which is the correct technique for finding
a maximum matching in a graph?
Answer: b a) DFS traversal
Explanation: The length of an augmenting b) BFS traversal
path in a bipartite graph is always said to be c) Shortest path traversal
always odd. d) Heap order traversal

7. In a bipartite graph G=(V,U,E), the Answer: b


matching of a free vertex in V to a free vertex Explanation: The correct technique for
in U is called? finding a maximum matching in a bipartite
a) Bipartite matching graph is by using a Breadth First
b) Cardinality matching Search(BFS).
c) Augmenting
d) Weight matching 11. The problem of maximizing the sum of
weights on edges connecting matched pairs of
vertices is?

Downloaded From: https://cse-r17.blogspot.com 195


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

a) Maximum- mass matching 15. From the given graph, how many vertices
b) Maximum bipartite matching can be matched using maximum matching in
c) Maximum weight matching bipartite graph algorithm?
d) Maximum node matching

Answer: c
Explanation: The problem is called as
maximum weight matching which is similar
to a bipartite matching. It is also called as
assignment problem. a) 5
b) 4
12. What is the total number of iterations c) 3
used in a maximum- matching algorithm? d) 2
a) [n/2]
b) [n/3] Answer: a
c) [n/2]+n Explanation: One of the solutions of the
d) [n/2]+1 matching problem is given by a-w,b-v,c-x,d-
y,e-z. Hence the answer is 5.
Answer: d
Explanation: The total number of iterations
cannot exceed [n/2]+1 where n=|V|+|U|
denoting the number of vertices in the graph.

13. What is the efficiency of algorithm UNIT V COPING WITH


designed by Hopcroft and Karp?
a) O(n+m)
THE LIMITATIONS OF
b) O(n(n+m) ALGORITHM POWER
c) O(√n(n+m))
d) O(n+2) 1. The worst-case efficiency of solving a
problem in polynomial time is?
Answer: c a) O(p(n))
Explanation: The efficiency of algorithm b) O(p( n log n))
designed by Hopcroft and Karp is
c) O(p(n2))
mathematically found to be O(√n(n+m)). d) O(p(m log n))
14. Who was the first person to solve the Answer: a
maximum matching problem?
Explanation: The worst-case efficiency of
a) Jack Edmonds
solving an problem in polynomial time is
b) Hopcroft
O(p(n)) where p(n) is the polynomial time of
c) Karp input size.
d) Claude Berge
2. Problems that can be solved in polynomial
Answer: a
time are known as?
Explanation: Jack Edmonds was the first
a) intractable
person to solve the maximum matching b) tractable
problem in 1965. c) decision
d) complete

Downloaded From: https://cse-r17.blogspot.com 196


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: b b) O( N log N)
Explanation: Problems that can be solved in c) O(log N)
polynomial time are known as tractable. d) O(N2)
Problems that cannot be solved in polynomial
time are intractable. Answer: d
Explanation: Mathematically, the run time of
3. The sum and composition of two Euler’s circuit problem is determined to be
polynomials are always polynomials. O(N2).
a) true
b) false 7. To which class does the Euler’s circuit
problem belong?
Answer: a a) P class
Explanation: One of the properties of b) NP class
polynomial functions states that the sum and
c) Partition class
composition of two polynomials are always
d) Complete class
polynomials.
Answer: a
4. _________ is the class of decision
Explanation: Euler’s circuit problem can be
problems that can be solved by non- solved in polynomial time. It can be solved in
deterministic polynomial algorithms?
a) NP O(N2).
b) P
8. Halting problem is an example for?
c) Hard
a) decidable problem
d) Complete
b) undecidable problem
Answer: a c) complete problem
Explanation: NP problems are called as non- d) trackable problem
deterministic polynomial problems. They are
Answer: b
a class of decision problems that can be
Explanation: Halting problem by Alan
solved using NP algorithms.
Turing cannot be solved by any algorithm.
5. Problems that cannot be solved by any Hence, it is undecidable.
algorithm are called?
9. How many stages of procedure does a non-
a) tractable problems
deterministic algorithm consist of?
b) intractable problems
a) 1
c) undecidable problems
b) 2
d) decidable problems
c) 3
Answer: c d) 4
Explanation: Problems cannot be solved by
Answer: b
any algorithm are called undecidable
Explanation: A non-deterministic algorithm
problems. Problems that can be solved in
is a two-stage procedure- guessing stage and
polynomial time are called Tractable
verification stage.
problems.
10. A non-deterministic algorithm is said to
6. The Euler’s circuit problem can be solved
be non-deterministic polynomial if the time-
in?
efficiency of its verification stage is
a) O(N)
polynomial.

Downloaded From: https://cse-r17.blogspot.com 197


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

a) true 14. Which of the following problems is not


b) false NP complete?
a) Hamiltonian circuit
Answer: a b) Bin packing
Explanation: One of the properties of NP c) Partition problem
class problems states that A non-deterministic d) Halting problem
algorithm is said to be non-deterministic
polynomial if the time-efficiency of its Answer: d
verification stage is polynomial. Explanation: Hamiltonian circuit, bin
packing, partition problems are NP complete
11. How many conditions have to be met if an problems. Halting problem is an undecidable
NP- complete problem is polynomially problem.
reducible?
a) 1 15. The choice of polynomial class has led to
b) 2 the development of an extensive theory called
c) 3 ________
d) 4 a) computational complexity
b) time complexity
Answer: b c) problem complexity
Explanation: A function t that maps all yes d) decision complexity
instances of decision problems D1 and D2
and t should be computed in polynomial time Answer: a
are the two conditions. Explanation: An extensive theory called
computational complexity seeks to classify
12. To which of the following class does a problems according to their inherent
CNF-satisfiability problem belong? difficulty.
a) NP class
b) P class
c) NP complete 1. Which of the following algorithm can be
d) NP hard used to solve the Hamiltonian path problem
efficiently?
Answer: c a) branch and bound
Explanation: The CNF satisfiability problem b) iterative improvement
belongs to NP complete class. It deals with c) divide and conquer
Boolean expressions. d) greedy algorithm

13. How many steps are required to prove Answer: a


that a decision problem is NP complete? Explanation: The Hamiltonian path problem
a) 1 can be solved efficiently using branch and
b) 2 bound approach. It can also be solved using a
c) 3 backtracking approach.
d) 4
2. The problem of finding a path in a graph
Answer: b that visits every vertex exactly once is called?
Explanation: First, the problem should be a) Hamiltonian path problem
NP. Next, it should be proved that every b) Hamiltonian cycle problem
problem in NP is reducible to the problem in c) Subset sum problem
question in polynomial time. d) Turnpike reconstruction problem

Downloaded From: https://cse-r17.blogspot.com 198


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

Answer: a c) Leonard
Explanation: Hamiltonian path problem is a d) Bellman
problem of finding a path in a graph that
visits every node exactly once whereas Answer: a
Hamiltonian cycle problem is finding a cycle Explanation: The first ever problem to solve
in a graph. the Hamiltonian path was the enumerative
algorithm formulated by Martello.
3. Hamiltonian path problem is _________
a) NP problem 7. In what time can the Hamiltonian path
b) N class problem problem can be solved using dynamic
c) P class problem programming?
d) NP complete problem a) O(N)
b) O(N log N)
Answer: d c) O(N2)
Explanation: Hamiltonian path problem is
d) O(N2 2N)
found to be NP complete. Hamiltonian cycle
problem is also an NP- complete problem. Answer: d
Explanation: Using dynamic programming,
4. There is no existing relationship between a
the time taken to solve the Hamiltonian path
Hamiltonian path problem and Hamiltonian
circuit problem. problem is mathematically found to be O(N2
a) true 2N).
b) false
8. In graphs, in which all vertices have an odd
Answer: b degree, the number of Hamiltonian cycles
Explanation: There is a relationship between through any fixed edge is always even.
Hamiltonian path problem and Hamiltonian a) true
circuit problem. The Hamiltonian path in b) false
graph G is equal to Hamiltonian cycle in
graph H under certain conditions. Answer: a
Explanation: According to a handshaking
5. Which of the following problems is similar lemma, in graphs, in which all vertices have
to that of a Hamiltonian path problem? an odd degree, the number of Hamiltonian
a) knapsack problem cycles through any fixed edge is always even.
b) closest pair problem
c) travelling salesman problem 9. Who invented the inclusion-exclusion
d) assignment problem principle to solve the Hamiltonian path
problem?
Answer: c a) Karp
Explanation: Hamiltonian path problem is b) Leonard Adleman
similar to that of a travelling salesman c) Andreas Bjorklund
problem since both the problem traverses all d) Martello
the nodes in a graph exactly once.
Answer: c
6. Who formulated the first ever algorithm for Explanation: Andreas Bjorklund came up
solving the Hamiltonian path problem? with the inclusion-exclusion principle to
a) Martello reduce the counting of number of
b) Monte Carlo Hamiltonian cycles.

Downloaded From: https://cse-r17.blogspot.com 199


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

10. For a graph of degree three, in what time


can a Hamiltonian path be found?
a) O(0.251n)
b) O(0.401n)
c) O(0.167n)
d) O(0.151n)

Answer: a a) 1
Explanation: For a graph of maximum b) 2
degree three, a Hamiltonian path can be found c) 0
in time O(0.251n). d) 3
11. What is the time complexity for finding a Answer: c
Hamiltonian path for a graph having N Explanation: The above graph has no
vertices (using permutation)? Hamiltonian paths. That is, we cannot
a) O(N!) traverse the graph with meeting vertices
b) O(N! * N) exactly once.
c) O(log N)
d) O(N)
1. Under what condition any set A will be a
Answer: b subset of B?
Explanation: For a graph having N vertices a) if all elements of set B are also present in
traverse the permutations in N! iterations and set A
it traverses the permutations to see if adjacent b) if all elements of set A are also present in
vertices are connected or not takes N set B
iterations (i.e.) O(N! * N). c) if A contains more elements than B
d) if B contains more elements than A
12. How many Hamiltonian paths does the
following graph have? Answer: b
Explanation: Any set A will be called a
subset of set B if all elements of set A are
also present in set B. So in such a case set A
will be a part of set B.

2. What is a subset sum problem?


a) 1 a) finding a subset of a set that has sum of
b) 2 elements equal to a given number
c) 3 b) checking for the presence of a subset that
d) 4 has sum of elements equal to a given number
and printing true or false based on the result
Answer: a
c) finding the sum of elements present in a set
Explanation: The above graph has only one
d) finding the sum of all the subsets of a set
Hamiltonian path that is from a-b-c-d-e.
Answer: b
13. How many Hamiltonian paths does the
Explanation: In subset sum problem check
following graph have?
for the presence of a subset that has sum of
elements equal to a given number. If such a

Downloaded From: https://cse-r17.blogspot.com 200


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

subset is present then we print true otherwise a) true


false. b) false

3. Which of the following is true about the Answer: b


time complexity of the recursive solution of Explanation: The recursive solution to subset
the subset sum problem? sum problem takes exponential time
a) It has an exponential time complexity complexity whereas the dynamic
b) It has a linear time complexity programming solution takes polynomial time
c) It has a logarithmic time complexity complexity. So dynamic programming
d) it has a time complexity of O(n2) solution is faster in terms of time complexity.

Answer: a 7. Which of the following is not true about


Explanation: Subset sum problem has both subset sum problem?
recursive as well as dynamic programming a) the recursive solution has a time
solution. The recursive solution has an complexity of O(2n)
exponential time complexity as it will require b) there is no known solution that takes
to check for all subsets in worst case. polynomial time
c) the recursive solution is slower than
4. What is the worst case time complexity of dynamic programming solution
dynamic programming solution of the subset d) the dynamic programming solution has a
sum problem(sum=given subset sum)? time complexity of O(n log n)
a) O(n)
b) O(sum) Answer: d
c) O(n2) Explanation: Recursive solution of subset
d) O(sum*n) sum problem is slower than dynamic problem
solution in terms of time complexity.
Answer: d Dynamic programming solution has a time
Explanation Subset sum problem has both complexity of O(n*sum).
recursive as well as dynamic programming
solution. The dynamic programming solution 8. Which of the following should be the base
has a time complexity of O(n*sum) as it as a case for the recursive solution of subset sum
nested loop with limits from 1 to n and 1 to problem?
sum respectively. a)

5. Subset sum problem is an example of NP- if(sum==0)


complete problem. return true;
a) true
b) false b)
Answer: a if(sum==0)
Explanation: Subset sum problem takes
exponential time when we implement a return true;
recursive solution. Subset sum problem is if (n ==0 && sum!= 0)
known to be a part of NP complete problems.
return false;
6. Recursive solution of subset sum problem
is faster than dynamic problem solution in c)
terms of time complexity.

Downloaded From: https://cse-r17.blogspot.com 201


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

if (n ==0 && sum!= 0) c) True


d) False
return false;
Answer: c
d)
Explanation: The given code represents the
if(sum<0) recursive approach of solving the subset sum
problem. The output for the code will be true
return true; if any subset is found to have sum equal to
the desired sum, otherwise false will be

M
if (n ==0 && sum!= 0)
printed.
return false;

O
10. What will be the output for the following
Answer: b code?

C
Explanation: The base case condition defines
the point at which the program should stop #include <stdio.h>

T.
bool func(int arr[], int n, int sum)
recursion. In this case we need to make sure {
that, the sum does not become 0 and there bool subarr[n+1][sum+1];

O
should be elements left in our array for for (int i = 0; i <= n; i++)
recursion to happen. subarr[i][0] = true;
for (int i = 1; i <= sum; i++)

9. What will be the output for the following


SP subarr[0][i] = false;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= sum; j++
G
code? )
{
LO

#include <stdio.h> if(j<arr[i-1])


bool func(int arr[], int n, int sum) subarr[i][j] = subarr[i-1
{ ][j];
if (sum == 0) if (j >= arr[i-1])
.B

return true; subarr[i][j] = subarr[i-1


if (n == 0 && sum != 0) ][j] ||
return false; subarr[i - 1][j-arr[i-1]]
17

if (arr[n-1] > sum) ;


return func(arr, n-1, sum); }
}
return func(arr, n-1, sum) || func(ar return subarr[n][sum];
-R

r, n-1, sum-arr[n-1]); }
}
int main() int main()
{ {
SE

int arr[] = {4,6, 12, 2}; int arr[] = {3, 3, 4, 4, 7};


int sum = 12; int sum = 5;
int n = sizeof(arr)/sizeof(arr[0]); int n = sizeof(arr)/sizeof(arr[0]);
if (func(arr, n, sum) == true) if (func(arr, n, sum) == true)
C

printf("true"); printf("true");
else else
printf("false"); printf("false");
return 0; return 0;
} }

a) 12 a) true
b) 4 6 2 b) false

Downloaded From: https://cse-r17.blogspot.com 202


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

c) 0 1. What is meant by the power set of a set?


d) error in code a) subset of all sets
b) set of all subsets
Answer: b c) set of particular subsets
Explanation: The given code represents the d) an empty set
dynamic programming approach of solving
the subset sum problem. The output for the Answer: b
code will be true if any subset is found to Explanation: Power set of a set is defined as
have sum equal to the desired sum, otherwise the set of all subsets. Ex- if there is a set S=
false will be printed. {1,3} then power set of set S will be P={{},
{1},{3}{1,3}}.
11. What will be the worst case time
complexity for the following code? 2. What is the set partition problem?
a) finding a subset of a set that has sum of
#include <stdio.h> elements equal to a given number
bool func(int arr[], int n, int sum)
b) checking for the presence of a subset that
{
if (sum == 0) has sum of elements equal to a given number
return true; c) checking whether the set can be divided
if (n == 0 && sum != 0) into two subsets of with equal sum of
return false; elements and printing true or false based on
if (arr[n-1] > sum)
the result
return func(arr, n-1, sum);
return func(arr, n-1, sum) || func(ar d) finding subsets with equal sum of elements
r, n-1, sum-arr[n-1]);
} Answer: c
int main() Explanation: In set partition problem we
{ check whether a set can be divided into 2
int arr[] = {4,6, 12, 2};
int sum = 12;
subsets such that the sum of elements in each
int n = sizeof(arr)/sizeof(arr[0]); subset is equal. If such subsets are present
if (func(arr, n, sum) == true) then we print true otherwise false.
printf("true");
else 3. Which of the following is true about the
printf("false"); time complexity of the recursive solution of
return 0;
} set partition problem?
a) It has an exponential time complexity
a) O(n log n) b) It has a linear time complexity
b) O(n2) c) It has a logarithmic time complexity
d) it has a time complexity of O(n2)
c) O(2n)
d) O(n2 log n) Answer: a
Explanation: Set partition problem has both
Answer: c recursive as well as dynamic programming
Explanation: The given code represents the solution. The recursive solution has an
recursive approach solution of the subset sum exponential time complexity as it will require
problem. It has an exponential time to check for all subsets in the worst case.
complexity as it will require to check for all
subsets in the worst case. It is equal to O(2n). 4. What is the worst case time complexity of
dynamic programming solution of set
partition problem(sum=sum of set elements)?

Downloaded From: https://cse-r17.blogspot.com 203


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

a) O(n) Answer: d
b) O(sum) Explanation: Recursive solution of set
c) O(n2) partition problem is slower than dynamic
d) O(sum*n) problem solution in terms of time complexity.
Dynamic programming solution has a time
Answer: d complexity of O(n*sum).
Explanation: Set partition problem has both
recursive as well as dynamic programming 8. Which of the following should be the base
solution. The dynamic programming solution case for the recursive solution of a set
has a time complexity of O(n*sum) as it as a partition problem?
nested loop with limits from 1 to n and 1 to a)
sum respectively.
If(sum%2!=0)
5. Set partition problem is an example of NP return false;
complete problem.
a) true if(sum==0)
b) false
return true;
Answer: a
Explanation: Set partition problem takes b)
exponential time when we implement a If(sum%2!=0)
recursive solution. Set partition problem is
known to be a part of NP complete problems. return false;

6. Recursive solution of Set partition problem if(sum==0)


is faster than dynamic problem solution in
return true;
terms of time complexity.
a) true if (n ==0 && sum!= 0)
b) false
return false;
Answer: b
Explanation: The recursive solution to set c)
partition problem takes exponential time
if (n ==0 && sum!= 0)
complexity whereas the dynamic
programming solution takes polynomial time return false;
complexity. So dynamic programming
solution is faster in terms of time complexity. d)

7. Which of the following is not true about set if(sum<0)


partition problem?
return true;
a) the recursive solution has a time
complexity of O(2n) if (n ==0 && sum!= 0)
b) there is no known solution that takes
polynomial time return false;
c) the recursive solution is slower than
dynamic programming solution Answer: b
d) the dynamic programming solution has a Explanation: In this case, we need to make
time complexity of O(n log n) sure that, the sum does not become 0 and

Downloaded From: https://cse-r17.blogspot.com 204


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

there should be elements left in our array for be divided into 2 subsets such that the sum of
recursion to happen. Also if the sum of elements in each subset is equal. If such a
elements of the set is an odd number then that partition is possible then we print true
set cannot be partitioned into two subsets otherwise false. In this case true should be
with an equal sum so under such a condition printed.
false should be returned.
10. What will be the output for the given
code?

9. What will be the output for the given code? #include <stdio.h>
bool func (int arr[], int n)
#include <stdio.h> {
#include <stdbool.h> int sum = 0;
bool func1(int arr[], int n, int sum) int i, j;
{ for (i = 0; i < n; i++)
if (sum == 0) sum += arr[i];
return true; if (sum%2 != 0)
if (n == 0 && sum != 0) return false;
return false; bool partition[sum/2+1][n+1];
if (arr[n-1] > sum) for (i = 0; i <= n; i++)
return func1(arr, n-1, sum); partition[0][i] = true;
return func1(arr, n-1, sum) || func1( for (i = 1; i <= sum/2; i++)
arr, n-1, sum-arr[n-1]); partition[i][0] = false;
} for (i = 1; i <= sum/2; i++)
bool func (int arr[], int n) {
{ for (j = 1; j <= n; j++)
int sum = 0; {
for (int i = 0; i < n; i++) partition[i][j] = partiti
sum += arr[i]; on[i][j-1];
if (sum%2 != 0) if (i >= arr[j-1])
return false; partition[i][j] = partiti
return func1 (arr, n, sum/2); on[i][j] || partition[i - arr[j-1]][j-1];
} }
int main() }
{ return partition[sum/2][n];
int arr[] = {4,6, 12, 2}; }
int n = sizeof(arr)/sizeof(arr[0]); int main()
if (func(arr, n) == true) {
printf("true"); int arr[] = {3, 3, 4, 4, 7};
else int n = sizeof(arr)/sizeof(arr[0]);
printf("false"); if (func(arr, n) == true)
return 0; printf("true");
} else
printf("false");
return 0;
a) true }
b) false
c) 4 6 2 a) true
d) 12 b) false
c) 0
Answer: a d) error
Explanation: The given code represents the
recursive approach of solving the set partition Answer: b
problem. The code checks whether a set can Explanation: The given code represents the

Downloaded From: https://cse-r17.blogspot.com 205


CS8451 DESIGN AND ANALYSIS OF ALGORITHMS Regulations 2017

dynamic programming approach of solving b) O(n2)


set partition problem. The code checks c) O(2n)
whether a set can be divided into 2 subsets d) O(sum*n)
such that the sum of elements in each subset
is equal. If such a partition is possible then we Answer: d
print true otherwise false. In this case, false Explanation: The auxiliary space complexity
should be printed. of set partition problem is required in order to
store the partition table. It takes up a space of
11. What will be the auxiliary space n*sum, so its auxiliary space requirement
complexity of dynamic programming solution becomes O(n*sum).
of set partition problem(sum=sum of set
elements)?
a) O(n log n)

Downloaded From: https://cse-r17.blogspot.com 206

You might also like