CS8451 Design and Analysis of Algorithms MCQ
CS8451 Design and Analysis of Algorithms MCQ
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)
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?
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
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);
}
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 – }
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
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;
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;
Answer: d
Explanation: As A * B = GCD (A, B) *
LCM (A, B). So B = (144 * 8)/72 = 16.
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.
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
a) Multiplication of A U B terms
d) 6
b) Multiplication of A ꓵ B terms
c) Multiplication of A*B terms Answer: a
SE
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).
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;
#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);
}
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?
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
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
6. Which of the following lines should be 7. What is the output of the following code?
inserted to complete the following recursive
#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
} #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.
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
#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);
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
}
} 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)
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)
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.
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;
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.
} 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)
{
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
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. }
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()
{
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
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).
#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
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. }
} 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
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);
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)
{ = 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] !
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)
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
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
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.
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).
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).
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.
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
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)
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
Answer: c
Explanation: A graph can have many
SE
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
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.
Answer: d a) GF
Explanation: Kruskal’s algorithm constructs b) DE
the minimum spanning tree by constructing
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.
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.
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
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
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)
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.
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
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
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
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.
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).
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.
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
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
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
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:
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
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}.
#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;
}
} 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);
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()
{-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
return 0; return 0;
} }
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
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}
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)
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
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
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
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
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++)
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
{
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 _____;
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++)
#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
#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” ?
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?
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.
Answer: a a) O(n)
Explanation: To find the longest palindromic b) O(1)
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()
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
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(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
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)
#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);
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];
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
#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";
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
#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];
range.(It will be a logical error and the 4. Consider the following assembly line
compiler wont show it). problem:
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)
{ 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) }
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?
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
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
}
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++)
#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;
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
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++)
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: 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
#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;
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
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
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
} }
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)
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?
#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
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)?
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;
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
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] == '&')
{ 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; }
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.
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
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
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.
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.
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
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: 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 ____________
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
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
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
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
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.
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.
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.
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
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
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.
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.
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.
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.
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++)
r, n-1, sum-arr[n-1]); }
}
int main() int main()
{ {
SE
printf("true"); printf("true");
else else
printf("false"); printf("false");
return 0; return 0;
} }
a) 12 a) true
b) 4 6 2 b) false
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;
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