Data Structures & Algorithms II MCQs
Searching Multiple Choice Questions (MCQ)
This set of Data Structure Multiple Choice Questions &
Answers (MCQs) focuses on “Searching”.
1. Which of the following searching algorithm is fastest?
a) binary search
b) linear search
c) jump search
d) all are equally fast
View Answer
Answer: a
Explanation: Binary search has the least time complexity
(equal to log n) out of the given searching algorithms. This
makes binary search preferable in most cases.
2. Where is linear searching used?
a) Used all the time
b) When the list has only a few elements
c) When performing a single search in an unordered list
d) When the list has only a few elements and When
performing a single search in an unordered list
View Answer
Page 1 of 295
Answer: d
Explanation: It is practical to implement linear search in the
situations mentioned in When the list has only a few
elements and When performing a single search in an
unordered list, but for larger elements the complexity
becomes larger and it makes sense to sort the list and
employ binary search or hashing.
3. How can Jump Search be improved?
a) Step size should be other than sqrt(n)
b) Cannot be improved
c) Begin from the kth item, where k is the step size
d) Start searching from the end
View Answer
Answer: c
Explanation: This gives a very slight improvement as you are
skipping the first k elements.
advertisement
4. Which of the following searching algorithm is used with
exponential sort after finding the appropriate range?
a) Jump search
b) Fibonacci Search
c) Linear search
Page 2 of 295
d) Binary search
View Answer
Answer: d
Explanation: In exponential search, we first find a range
where the required elements should be present in the array.
Then we apply binary search in this range.
5. Which of the following searching algorithm is fastest
when the input array is not sorted but has uniformly
distributed values?
a) linear search
b) jump search
c) interpolation search
d) binary search
View Answer
Answer: a
Explanation: Out of the given options linear search is the
only searching algorithm which can be applied to arrays
which are not sorted. It has a time complexity of O(n) in the
worst case.
6. What is the time complexity of Z algorithm for pattern
searching (m = length of text, n = length of pattern)?
a) O(n)
Page 3 of 295
b) O(m)
c) O(n + m)
d) O(m * n)
View Answer
Answer: c
Explanation: Z algorithm is an efficient pattern searching
algorithm as it searches the pattern in linear time. It has a
time complexity of O(m + n) where m is the length of text
and n is the length of the pattern.
7. In which of the cases uniform binary search fails
compared to binary search?
a) Complexity of code
b) Many searches will be performed on several arrays of the
same length
c) Many searches will be performed on the same array
d) A table lookup is generally faster than an addition and a
shift
View Answer
Answer: a
Explanation: Uniform binary search code is more complex to
implement than binary search as it involves mid points to be
computed in hand before search.
Page 4 of 295
8. Interpolation search is a variation of?
a) Exponential search
b) Linear search
c) Binary search
d) Jump search
View Answer
Answer: c
Explanation: Interpolation search is a variation of binary
search which gives the best result when the array has
uniformly distributed values. Interpolation search goes to
different positions depending on the value being searched
whereas binary search always goes to the middle element.
9. Which of the following is not an application of binary
search?
a) To search in unordered list
b) Debugging
c) Union of intervals
d) To find the lower/upper bound in an ordered sequence
View Answer
Answer: a
Explanation: In Binary search, the elements in the list should
be sorted. It is applicable only for ordered list. Hence Binary
search in unordered list is not an application.
Page 5 of 295
10. Which of the following step is taken after finding an
element having value greater than the element being
searched?
a) binary search takes place in the forward direction
b) binary search takes place in a backward direction
c) linear search takes place in the forward direction
d) linear search takes place in the backward direction
View Answer
Answer: d
Explanation: First an element having value greater than the
element being searched is found. After this linear search is
performed in a backward direction.
11. Which of the following is not an advantage of Fibonacci
Search?
a) When the element being searched for has a non uniform
access storage
b) It can be applied efficiently on unsorted arrays
c) Can be used for large arrays which do not fit in the CPU
cache or in the RAM
d) Can be used in magnetic tapes
View Answer
Answer: b
Explanation: When the speed of access depends on the
Page 6 of 295
location previously accessed, Fibonacci search is better
compared to binary search as it performs well on those
locations which have lower dispersion. Fibonacci search
won’t work on unsorted arrays. The input should be a
sorted array or array should be sorted before Fibonacci
search.
12. In which of the following case jump search will be
preferred over exponential search?
a) when the given array is very small in size
b) when the given array is very large in size
c) jumping backwards takes significantly more time than
jumping forward
d) jumping forward takes significantly more time than
jumping backwards
View Answer
Answer: d
Explanation: Jump search only needs to jump backwards
once, while an exponential search can jump backwards up
to log n times. Thus jump search will be preferred if jumping
backwards is expensive.
Data Structure Multiple Choice Questions – Linear Search
Page 7 of 295
This set of Data Structure Multiple Choice Questions &
Answers (MCQs) focuses on “Linear Search”.
1. Where is linear searching used?
a) When the list has only a few elements
b) When performing a single search in an unordered list
c) Used all the time
d) When the list has only a few elements and When
performing a single search in an unordered list
View Answer
Answer: d
Explanation: It is practical to implement linear search in the
situations mentioned in When the list has only a few
elements and When performing a single search in an
unordered list, but for larger elements the complexity
becomes larger and it makes sense to sort the list and
employ binary search or hashing.
2. Select the code snippet which performs unordered linear
search iteratively?
a)
int unorderedLinearSearch(int arr[], int size, int data)
{
int index;
Page 8 of 295
for(int i = 0; i < size; i++)
{
if(arr[i] == data)
{
index = i;
break;
}
}
return index;
}
b)
advertisement
int unorderedLinearSearch(int arr[], int size, int data)
{
int index;
for(int i = 0; i < size; i++)
{
if(arr[i] == data)
{
Page 9 of 295
break;
}
}
return index;
}
c)
Note: Join free Sanfoundry classes at Telegram or Youtube
int unorderedLinearSearch(int arr[], int size, int data)
{
int index;
for(int i = 0; i <= size; i++)
{
if(arr[i] == data)
{
index = i;
break;
}
}
return index;
Page 10 of 295
}
d)
int unorderedLinearSearch(int arr[], int size, int data)
{
int index;
for(int i = 0; i < size-1; i++)
{
if(arr[i] == data)
{
index = i;
break;
}
}
return index;
}
View Answer
Answer: a
Explanation: Unordered term refers to the given array, that
is, the elements need not be ordered. To search for an
Page 11 of 295
element in such an array, we need to loop through the
elements until the desired element is found.
3. What is the best case for linear search?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(1)
View Answer
Answer: d
Explanation: The element is at the head of the array, hence
O(1).
4. What is the worst case for linear search?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(1)
View Answer
Answer: c
Explanation: Worst case is when the desired element is at
the tail of the array or not present at all, in this case you
Page 12 of 295
have to traverse till the end of the array, hence the
complexity is O(n).
5. Select the code snippet which performs ordered linear
search iteratively?
a)
public int linearSearch(int arr[],int key,int size)
{
int index = -1;
int i = 0;
while(size > 0)
{
if(data[i] == key)
{
index = i;
}
if(data[i] > key))
{
index = i;
break;
Page 13 of 295
}
i++;
}
return index;
}
b)
public int linearSearch(int arr[],int key,int size)
{
int index = -1;
int i = 0;
while(size > 0)
{
if(data[i] == key)
{
index = i;
}
if(data[i] > key))
{
break;
Page 14 of 295
}
i++;
}
return index;
}
c)
public int linearSearch(int arr[],int key,int size)
{
int index = -1;
int i = 0;
while(size > 0)
{
if(data[i] == key)
{
break;
}
if(data[i] > key))
{
index = i;
Page 15 of 295
}
i++;
}
return index;
}
d)
public int linearSearch(int arr[],int key,int size)
{
int index = -1;
int i = 0;
while(size > 0)
{
if(data[i] == key)
{
break;
}
if(data[i] > key))
{
break;
Page 16 of 295
index=i;
}
i++;
}
return index;
}
View Answer
Answer: b
Explanation: The term ordered refers to the items in the
array being sorted(here we assume ascending order). So
traverse through the array until the element, if at any time
the value at i exceeds key value, it means the element is not
present in the array. This provides a slightly better efficiency
than unordered linear search.
6. What is the best case and worst case complexity of
ordered linear search?
a) O(nlogn), O(logn)
b) O(logn), O(nlogn)
c) O(n), O(1)
Page 17 of 295
d) O(1), O(n)
View Answer
Answer: d
Explanation: Although ordered linear search is better than
unordered when the element is not present in the array, the
best and worst cases still remain the same, with the key
element being found at first position or at last position.
7. Choose the code snippet which uses recursion for linear
search.
a)
public void linSearch(int[] arr, int first, int last, int key)
{
if(first == last)
{
[Link]("-1");
}
else
{
if(arr[first] == key)
{
Page 18 of 295
[Link](first);
}
else
{
linSearch(arr, first+1, last, key);
}
}
}
b)
public void linSearch(int[] arr, int first, int last, int key)
{
if(first == last)
{
[Link]("-1");
}
else
{
if(arr[first] == key)
{
Page 19 of 295
[Link](first);
}
else
{
linSearch(arr, first+1, last-1, key);
}
}
}
c)
public void linSearch(int[] arr, int first, int last, int key)
{
if(first == last)
{
[Link]("-1");
}
else
{
if(arr[first] == key)
{
Page 20 of 295
[Link](last);
}
else
{
linSearch(arr, first+1, last, key);
}
}
}
d)
public void linSearch(int[] arr, int first, int last, int key)
{
if(first == last)
{
[Link]("-1");
}
else
{
if(arr[first] == key)
{
Page 21 of 295
[Link](first);
}
else
{
linSearch(arr, first+1, last+1, key);
}
}
}
View Answer
Answer: a
Explanation: Every time check the key with the array value
at first index, if it is not equal then call the function again
with an incremented first index.
8. What does the following piece of code do?
for (int i = 0; i < [Link]-1; i++)
{
for (int j = i+1; j < [Link]; j++)
Page 22 of 295
{
if( (arr[i].equals(arr[j])) && (i != j) )
{
[Link](arr[i]);
}
}
}
a) Print the duplicate elements in the array
b) Print the element with maximum frequency
c) Print the unique elements in the array
d) Prints the element with minimum frequnecy
View Answer
Answer: a
Explanation: The print statement is executed only when the
items are equal and their indices are not.
9. Select the code snippet which prints the element with
maximum frequency.
a)
public int findPopular(int[] a)
{
Page 23 of 295
if (a == null || [Link] == 0)
return 0;
[Link](a);
int previous = a[0];
int popular = a[0];
int count = 1;
int maxCount = 1;
for (int i = 1; i < [Link]; i++)
{
if (a[i] == previous)
count++;
else
{
if (count > maxCount)
{
popular = a[i-1];
maxCount = count;
}
previous = a[i];
Page 24 of 295
count = 1;
}
}
return count > maxCount ? a[[Link]-1] : popular;
}
b)
public int findPopular(int[] a)
{
if (a == null || [Link] == 0)
return 0;
[Link](a);
int previous = a[0];
int popular = a[0];
int count = 1;
int maxCount = 1;
for (int i = 1; i < [Link]; i++)
{
if (a[i] == previous)
count++;
Page 25 of 295
else
{
if (count > maxCount)
{
popular = a[i];
maxCount = count;
}
previous = a[i];
count = 1;
}
}
return count > maxCount ? a[[Link]-1] : popular;
}
c)
public int findPopular(int[] a)
{
if (a == null || [Link] == 0)
return 0;
[Link](a);
Page 26 of 295
int previous = a[0];
int popular = a[0];
int count = 1;
int maxCount = 1;
for (int i = 1; i < [Link]; i++)
{
if (a[i+1] == previous)
count++;
else
{
if (count > maxCount)
{
popular = a[i-1];
maxCount = count;
}
previous = a[i];
count = 1;
}
}
Page 27 of 295
return count > maxCount ? a[[Link]-1] : popular;
}
d)
public int findPopular(int[] a)
{
if (a == null || [Link] == 0)
return 0;
[Link](a);
int previous = a[0];
int popular = a[0];
int count = 1;
int maxCount = 1;
for (int i = 1; i < [Link]; i++)
{
if (a[i+2] == previous)
count++;
else
{
if (count > maxCount)
Page 28 of 295
{
popular = a[i-1];
maxCount = count;
}
previous = a[i];
count = 1;
}
}
return count > maxCount ? a[[Link]-1] : popular;
}
View Answer
Answer: a
Explanation: Traverse through the array and see if it is equal
to the previous element, since the array is sorted this
method works with a time complexity of O(nlogn), without
sorting a Brute force technique must be applied for which
the time complexity will be O(n2).
10. Which of the following is a disadvantage of linear
search?
a) Requires more space
Page 29 of 295
b) Greater time complexities compared to other searching
algorithms
c) Not easy to understand
d) Not easy to implement
View Answer
Answer: b
Explanation: The complexity of linear search as the name
suggests is O(n) which is much greater than other searching
techniques like binary search(O(logn)). Linear search is easy
to implement and understand than other searching
techniques.
Linear Search Recursive Multiple Choice Questions and
Answers (MCQs)
This set of Data Structures & Algorithms Multiple Choice
Questions & Answers (MCQs) focuses on “Linear Search
Recursive”.
1. Is there any difference in the speed of execution between
linear serach(recursive) vs linear search(lterative)?
a) Both execute at same speed
b) Linear search(recursive) is faster
c) Linear search(Iterative) is faster
Page 30 of 295
d) Cant be said
View Answer
Answer: c
Explanation: The Iterative algorithm is faster than the latter
as recursive algorithm has overheads like calling function
and registering stacks repeatedly.
2. Is the space consumed by the linear search(recursive) and
linear search(iterative) same?
a) No, recursive algorithm consumes more space
b) No, recursive algorithm consumes less space
c) Yes
d) Nothing can be said
View Answer
Answer: a
Explanation: The recursive algorithm consumes more space
as it involves the usage the stack space(calls the function
numerous times).
3. What is the worst case runtime of linear search(recursive)
algorithm?
a) O(n)
b) O(logn)
c) O(n2)
Page 31 of 295
d) O(nx)
View Answer
Answer: a
Explanation: In the worst case scenario, there might be a
need of calling the stack n times. Therfore O(n).
advertisement
4. Linear search(recursive) algorithm used in
_____________
a) When the size of the dataset is low
b) When the size of the dataset is large
c) When the dataset is unordered
d) Never used
View Answer
Answer: a
Explanation: It is used when the size of the dataset is low as
its runtime is O(n) which is more when compared to the
binary search O(logn).
5. The array is as follows: 1,2,3,6,8,10. At what time the
element 6 is found? (By using linear search(recursive)
algorithm)
a) 4th call
b) 3rd call
Page 32 of 295
c) 6th call
d) 5th call
View Answer
Answer: a
Explanation: Provided that the search starts from the first
element, the function calls itself till the element is found. In
this case, the element is found in 4th call.
Sanfoundry Certification Contest of the Month is Live. 100+
Subjects. Participate Now!
6. The array is as follows: 1,2,3,6,8,10. Given that the
number 17 is to be searched. At which call it tells that
there’s no such element? (By using linear search(recursive)
algorithm)
a) 7th call
b) 9th call
c) 17th call
d) The function calls itself infinite number of times
View Answer
Answer: a
Explanation: The function calls itself till the element is
found. But at the 7th call it terminates as goes outside the
array.
Page 33 of 295
7. What is the best case runtime of linear search(recursive)
algorithm on an ordered set of elements?
a) O(1)
b) O(n)
c) O(logn)
d) O(nx)
View Answer
Answer: a
Explanation: The best case occurs when the given element
to be found is at the first position. Therefore O(1) is the
correct answer.
8. Which of the following code snippet performs linear
search recursively?
a)
for(i=0;i<n;i++)
{
if(a[i]==key)
printf("element found");
}
b)
LinearSearch(int[] a, n,key)
Page 34 of 295
{
if(n<1)
return False
if(a[n]==key)
return True
else
LinearSearch(a,n-1,key)
}
c)
LinearSearch(int[] a, n,key)
{
if(n<1)
return True
if(a[n]==key)
return False
else
LinearSearch(a,n-1,key)
}
d)
Page 35 of 295
LinearSearch(int[] a, n,key)
{
if(n<1)
return False
if(a[n]==key)
return True
else
LinearSearch(a,n+1,key)
}
View Answer
Answer: b
Explanation: Compare n with first element in arr[]. If
element is found at first position, return it. Else recur for
remaining array and n.
9. Can linear search recursive algorithm and binary search
recursive algorithm be performed on an unordered list?
a) Binary search can’t be used
b) Linear search can’t be used
Page 36 of 295
c) Both cannot be used
d) Both can be used
View Answer
Answer: a
Explanation: As binary search requires comparison, it is
required that the list be ordered. Whereas this doesn’t
matter for linear search.
10. What is the recurrence relation for the linear search
recursive algorithm?
a) T(n-2)+c
b) 2T(n-1)+c
c) T(n-1)+c
d) T(n+1)+c
View Answer
Answer: c
Explanation: After each call in the recursive algorithm, the
size of n is reduced by 1. Therefore the optimal solution is
T(n-1)+c.
Data Structure Multiple Choice Questions – Binary Search
This set of Data Structure Multiple Choice Questions &
Answers (MCQs) focuses on “Binary Search”.
Page 37 of 295
1. What is the advantage of recursive approach than an
iterative approach?
a) Consumes less memory
b) Less code and easy to implement
c) Consumes more memory
d) More code has to be written
View Answer
Answer: b
Explanation: A recursive approach is easier to understand
and contains fewer lines of code.
2. Choose the appropriate code that does binary search
using recursion.
a)
public static int recursive(int arr[], int low, int high, int key)
{
int mid = low + (high - low)/2;
if(arr[mid] == key)
{
return mid;
}
else if(arr[mid] < key)
Page 38 of 295
{
return recursive(arr,mid+1,high,key);
}
else
{
return recursive(arr,low,mid-1,key);
}
}
b)
advertisement
public static int recursive(int arr[], int low, int high, int key)
{
int mid = low + (high + low)/2;
if(arr[mid] == key)
{
return mid;
}
else if(arr[mid] < key)
{
Page 39 of 295
return recursive(arr,mid-1,high,key);
}
else
{
return recursive(arr,low,mid+1,key);
}
}
c)
Sanfoundry Certification Contest of the Month is Live. 100+
Subjects. Participate Now!
public static int recursive(int arr[], int low, int high, int key)
{
int mid = low + (high - low)/2;
if(arr[mid] == key)
{
return mid;
}
else if(arr[mid] < key)
{
Page 40 of 295
return recursive(arr,mid,high,key);
}
else
{
return recursive(arr,low,mid-1,key);
}
}
d)
public static int recursive(int arr[], int low, int high, int key)
{
int mid = low + ((high - low)/2)+1;
if(arr[mid] == key)
{
return mid;
}
else if(arr[mid] < key)
{
return recursive(arr,mid,high,key);
}
Page 41 of 295
else
{
return recursive(arr,low,mid-1,key);
}
}
View Answer
Answer: a
Explanation: Calculate the ‘mid’ value, and check if that is
the key, if not, call the function again with 2 sub arrays, one
with till mid-1 and the other starting from mid+1.
3. Given an input arr = {2,5,7,99,899}; key = 899; What is the
level of recursion?
a) 5
b) 2
c) 3
d) 4
View Answer
Answer: c
Explanation: level 1: mid = 7
Page 42 of 295
level 2: mid = 99
level 3: mid = 899(this is the key).
4. Given an array arr = {45,77,89,90,94,99,100} and key = 99;
what are the mid values(corresponding array elements) in
the first and second levels of recursion?
a) 90 and 99
b) 90 and 94
c) 89 and 99
d) 89 and 94
View Answer
Answer: a
Explanation: At first level key = 90
At second level key= 99
Here 90 and 99 are mid values.
5. What is the worst case complexity of binary search using
recursion?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)
View Answer
Page 43 of 295
Answer: b
Explanation: Using the divide and conquer master theorem.
6. What is the average case time complexity of binary search
using recursion?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)
View Answer
Answer: b
Explanation: T(n) = T(n/2) + 1, Using the divide and conquer
master theorem.
7. Which of the following is not an application of binary
search?
a) To find the lower/upper bound in an ordered sequence
b) Union of intervals
c) Debugging
d) To search in unordered list
View Answer
Answer: d
Explanation: In Binary search, the elements in the list should
Page 44 of 295
be sorted. It is applicable only for ordered list. Hence Binary
search in unordered list is not an application.
8. Choose among the following code for an iterative binary
search.
a)
public static int iterative(int arr[], int key)
{
int low = 0;
int mid = 0;
int high = [Link]-1;
while(low <= high)
{
mid = low + (high + low)/2;
if(arr[mid] == key)
{
return mid;
}
else if(arr[mid] < key)
{
Page 45 of 295
low = mid - 1;
}
else
{
high = mid + 1;
}
}
return -1;
}
b)
public static int iterative(int arr[], int key)
{
int low = 0;
int mid = 0;
int high = [Link]-1;
while(low <= high)
{
mid = low + (high - low)/2;
if(arr[mid] == key)
Page 46 of 295
{
return mid;
}
else if(arr[mid] < key)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return -1;
}
c)
public static int iterative(int arr[], int key)
{
int low = 0;
int mid = 0;
Page 47 of 295
int high = [Link]-1;
while(low <= high)
{
mid = low + (high + low)/2;
if(arr[mid] == key)
{
return mid;
}
else if(arr[mid] < key)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return -1;
}
Page 48 of 295
d)
public static int iterative(int arr[], int key)
{
int low = 0;
int mid = 0;
int high = [Link]-1;
while(low <= high)
{
mid = low + (high - low)/2;
if(arr[mid] == key)
{
return mid;
}
else if(arr[mid] < key)
{
low = mid - 1;
}
else
{
Page 49 of 295
high = mid + 1;
}
}
return -1;
}
View Answer
Answer: b
Explanation: Find the ‘mid’, check if it equals the key, if not,
continue the iterations until low <= high.
9. Binary Search can be categorized into which of the
following?
a) Brute Force technique
b) Divide and conquer
c) Greedy algorithm
d) Dynamic programming
View Answer
Answer: b
Explanation: Since ‘mid’ is calculated for every iteration or
Page 50 of 295
recursion, we are diving the array into half and then try to
solve the problem.
10. Given an array arr = {5,6,77,88,99} and key = 88; How
many iterations are done until the element is found?
a) 1
b) 3
c) 4
d) 2
View Answer
Answer: d
Explanation: Iteration1 : mid = 77; Iteration2 : mid = 88;
11. Given an array arr = {45,77,89,90,94,99,100} and key =
100; What are the mid values(corresponding array
elements) generated in the first and second iterations?
a) 90 and 99
b) 90 and 100
c) 89 and 94
d) 94 and 99
View Answer
Answer: a
Explanation: Trace the input with the binary search iterative
code.
Page 51 of 295
12. What is the time complexity of binary search with
iteration?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)
View Answer
Answer: b
Explanation: T(n) = T(n/2) + theta(1)
Using the divide and conquer master theorem, we get the
time complexity as O(logn).
Data Structure Questions and Answers – Uniform Binary
Search
This set of Data Structure Multiple Choice Questions &
Answers (MCQs) focuses on “Uniform Binary Search”.
1. In which of the cases uniform binary search fails
compared to binary search?
a) A table lookup is generally faster than an addition and a
shift
b) Many searches will be performed on the same array
c) Many searches will be performed on several arrays of the
same length
Page 52 of 295
d) Complexity of code
View Answer
Answer: d
Explanation: Uniform binary search code is more complex to
implement than binary search as it involves mid points to be
computed in hand before search.
2. Which of the following is a suitable lookup table that can
be used in the uniform binary search?(N is the number of
elements in the array and the delta array is global)
a)
public static void make_delta(int N)
{
int power = 1;
int i = 0;
do
{
int half = power;
power <<= 1;
delta[i] = (N + half) / power;
}
Page 53 of 295
while (delta[i++] != 0);
}
b)
advertisement
public static void make_delta(int N)
{
int power = 0;
int i = 0;
do
{
int half = power;
power <<= 1;
delta[i] = (N + half) / power;
}
while (delta[i++] != 0);
}
c)
Note: Join free Sanfoundry classes at Telegram or Youtube
public static void make_delta(int N)
Page 54 of 295
{
int power = 1;
int i = 0;
do
{
int half = power;
power >>= 1;
delta[i] = (N + half) / power;
}
while (delta[i++] != 0);
}
d)
public static void make_delta(int N)
{
int power = 1;
int i = 0;
do
{
int half = power;
Page 55 of 295
power <<= 1;
delta[i] = (N - half) / power;
}
while (delta[i++] != 0);
}
View Answer
Answer: a
Explanation: This provides a single lookup index and the
values are dependent on the the number of elements(N) in
the array.
3. Given delta[4] is a global array and number of elements in
the sorted array is 10, what are the values in the delta
array?
a) 4, 3, 1, 0
b) 5, 3, 1, 0
c) 4, 2, 1, 1
d) 5, 2, 1, 1
View Answer
Answer: b
Explanation: Trace with respect to the make_delta function,
always note that the last element is always 0.
Page 56 of 295
4. Choose the appropriate code snippet that performs
uniform binary search.
a)
public static int unisearch(int key)
{
int i = delta[0] - 1;
int j = 0;
while (true)
{
if (key == arr[i])
return i;
else if (delta[j] == 0)
return -1;
else
{
if (key < arr[i])
i += delta[++j];
else
i -= delta[++j];
Page 57 of 295
}
}
}
b)
public static int unisearch(int key)
{
int i = delta[1] - 1;
int j = 0;
while (true)
{
if (key == arr[i])
return i;
else if (delta[j] == 0)
return -1;
else
{
if (key < arr[i])
i -= delta[++j];
else
Page 58 of 295
i += delta[++j];
}
}
}
c)
public static int unisearch(int key)
{
int i = delta[0] - 1;
int j = 0;
while (true)
{
if (key == arr[i])
return i;
else if (delta[j] == 0)
return -1;
else
{
if (key < arr[i])
i -= delta[++j];
Page 59 of 295
else
i += delta[++j];
}
}
}
d)
public static int unisearch(int key)
{
int i = delta[0] - 1;
int j = 0;
while (true)
{
if (key == arr[i])
return i;
else if (delta[j] == 0)
return -1;
else
{
if (key < arr[i])
Page 60 of 295
i += delta[++j];
else
i += delta[++j];
}
}
}
View Answer
Answer: c
Explanation: Unlike the usual binary search which a low,
high and a mid variable and every time comparing the key
with the mid value, the comparing index is obtained from
the lookup delta table, choosing the left or right side of the
array is same as with the normal binary search.
5. What is the time complexity of uniform binary search?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)
View Answer
Page 61 of 295
Answer: b
Explanation: With every iteration we are dividing the array
into two parts(though not equal halves), the complexity
remains same as the normal binary search.
6. Given, arr = {1,3,5,6,7,9,14,15,17,19} key = 17 and delta =
{5,3,1,0}
How many key comparisons are made?(exclude the
comparison used to decide the left or right sub array)
a) 4
b) 3
c) 5
d) 6
View Answer
Answer: b
Explanation: Tracing with the above code, comparison #1:
i=4, comparison #2: i=7, comparison #3: i=8
7. How can Jump Search be improved?
a) Start searching from the end
b) Begin from the kth item, where k is the step size
c) Cannot be improved
d) Step size should be other than sqrt(n)
View Answer
Page 62 of 295
Answer: b
Explanation: This gives a very slight improvement as you are
skipping the first k elements.
8. Which of the following false about Jump Search?
a) Jump Search is better than Linear Search
b) Useful when jumping back is more costly than jumping
forward
c) Jump Search is worse than Binary Search
d) Jump search starts from the index 0 even though
specified index is k
View Answer
Answer: d
Explanation: Linear search has O(n) complexity and Binary
search has O(logn) complexity, in Jump search you have to
jump backwards only once, hence it is preferable if jumping
backwards is costly. Jump search starts from index k
(specified index) and searches for the element. It won’t start
searching from index 0.
Sorting Multiple Choice Questions (MCQ)
This set of Data Structure Multiple Choice Questions &
Answers (MCQs) focuses on “Sorting”.
Page 63 of 295
1. Which of the following sorting algorithms is the fastest for
sorting small arrays?
a) Quick sort
b) Shell sort
c) Insertion sort
d) Heap sort
View Answer
Answer: c
Explanation: For sorting small arrays, insertion sort runs
even faster than quick sort. But, it is impractical to sort large
arrays.
2. What is the advantage of selection sort over other sorting
techniques?
a) It is faster than any other sorting technique
b) It is scalable
c) It works best for inputs which are already sorted
d) It requires no additional storage space
View Answer
Answer: d
Explanation: Since selection sort is an in-place sorting
algorithm, it does not require additional storage.
Page 64 of 295
3. Which of the following method is used for sorting in
merge sort?
a) partitioning
b) merging
c) exchanging
d) selection
View Answer
Answer: b
Explanation: Merge sort algorithm divides the array into two
halves and applies merge sort algorithm to each half
individually after which the two sorted halves are merged
together. Thus its method of sorting is called merging.
advertisement
4. Which of the following sorting algorithm does not use
recursion?
a) bottom up merge sort
b) merge sort
c) heap sort
d) quick sort
View Answer
Answer: a
Explanation: Bottom up merge sort uses the iterative
Page 65 of 295
method in order to implement sorting. It begins by merging
a pair of adjacent array of size 1 each and then merge arrays
of size 2 each in the next step and so on.
5. Merge sort uses which of the following method to
implement sorting?
a) selection
b) exchanging
c) merging
d) partitioning
View Answer
Answer: c
Explanation: Merge sort implements sorting by merging the
sorted versions of smaller parts of the array. Thus its
method of sorting is called merging.
6. Which of the following sorting algorithms is the fastest?
a) Merge sort
b) Shell sort
c) Insertion sort
d) Quick sort
View Answer
Page 66 of 295
Answer: d
Explanation: Quick sort is the fastest known sorting
algorithm because of its highly optimized inner loop.
7. Shell sort algorithm is an example of?
a) Bottom-up sorting
b) In-place sorting
c) Internal sorting
d) External sorting
View Answer
Answer: c
Explanation: Shell sort is an example of internal sorting
because sorting of elements is done internally using an
array.
8. Quick sort uses which of the following method to
implement sorting?
a) partitioning
b) selection
c) exchanging
d) merging
View Answer
Answer: a
Explanation: Quick sort makes partitions of the input array
Page 67 of 295
about the pivot in order to implement sorting. Thus its
method of sorting is called partitioning.
9. In heap sort, after deleting the last minimum element,
the array will contain elements in?
a) increasing sorting order
b) tree preorder
c) tree inorder
d) decreasing sorting order
View Answer
Answer: d
Explanation: By logic, after deleting minimum element, the
heap will contain elements in decreasing sorting order. We
can change this by altering the ordering property.
10. Which of the following sorting algorithm is used by C++
internally?
a) quicksort
b) merge sort
c) introsort
d) heap sort
View Answer
Answer: c
Explanation: Introsort is the in built sorting algorithm used
Page 68 of 295
by C++. It is an example of a hybrid sorting algorithm which
means it uses more than one sorting algorithm as a routine.
11. Which of the following sorting algorithm is stable?
a) Introsort
b) Tim sort
c) Heap sort
d) Quick sort
View Answer
Answer: b
Explanation: Out of the given options Tim sort is the only
algorithm which is stable. As both constituents of Tim sort
(I.e insertion sort and merge sort) are stable so Tim sort also
becomes stable.
12. Which of the following sorting algorithm uses the
method of insertion?
a) selection sort
b) quick sort
c) bubble sort
d) cycle sort
View Answer
Answer: d
Explanation: Cycle sort is the only algorithm from the given
Page 69 of 295
ones that uses the method of insertion. Other than this,
insertion sort also uses the method of insertion for sorting.
13. Which of the following pair of sorting algorithms are
stable?
a) gnome sort and merge sort
b) heap sort and merge sort
c) gnome sort and quick sort
d) merge sort and selection sort
View Answer
Answer: a
Explanation: Gnome sort and merge sort are stable sorting
algorithms as the elements with identical values appear in
the same order in the output array as they were in the input
array when any of these sorting algorithms are
implemented.
Insertion Sort Multiple Choice Questions and Answers
This set of Data Structures & Algorithms Multiple Choice
Questions & Answers (MCQs) focuses on “Insertion Sort”.
1. How many passes does an insertion sort algorithm consist
of?
a) N
b) N-1
Page 70 of 295
c) N+1
d) N2
View Answer
Answer: b
Explanation: An insertion algorithm consists of N-1 passes
when an array of N elements is given.
2. Which of the following algorithm implementations is
similar to that of an insertion sort?
a) Binary heap
b) Quick sort
c) Merge sort
d) Radix sort
View Answer
Answer: a
Explanation: Insertion sort is similar to that of a binary heap
algorithm because of the use of temporary variable to swap.
3. What is the average case running time of an insertion sort
algorithm?
a) O(N)
b) O(N log N)
c) O(log N)
Page 71 of 295
d) O(N2)
View Answer
Answer: d
Explanation: The average case analysis of a tight bound
algorithm is mathematically achieved to be O(N2).
advertisement
4. Any algorithm that sorts by exchanging adjacent elements
require O(N2) on average.
a) True
b) False
View Answer
Answer: a
Explanation: Each swap removes only one inversion, so
O(N2) swaps are required.
5. What is the average number of inversions in an array of N
distinct numbers?
a) N(N-1)/4
b) N(N+1)/2
c) N(N-1)/2
d) N(N-1)/3
View Answer
Page 72 of 295
Answer: a
Explanation: The total number of pairs in a list L is N(N-1)/2.
Thus, an average list has half this amount, or N(N-1)/4
inversions.
Note: Join free Sanfoundry classes at Telegram or Youtube
6. What is the running time of an insertion sort algorithm if
the input is pre-sorted?
a) O(N2)
b) O(N log N)
c) O(N)
d) O(M log N)
View Answer
Answer: c
Explanation: If the input is pre-sorted, the running time is
O(N), because the test in the inner for loop always fails
immediately and the algorithm will run quickly.
7. What will be the number of passes to sort the elements
using insertion sort?
14, 12,16, 6, 3, 10
a) 6
b) 5
c) 7
Page 73 of 295
d) 1
View Answer
Answer: b
Explanation: The number of passes is given by N-1. Here,
N=6. Therefore,
6-1=5 passes.
8. For the following question, how will the array elements
look like after second pass?
34, 8, 64, 51, 32, 21
a) 8, 21, 32, 34, 51, 64
b) 8, 32, 34, 51, 64, 21
c) 8, 34, 51, 64, 32, 21
d) 8, 34, 64, 51, 32, 21
View Answer
Answer: d
Explanation: After swapping elements in the second pass,
the array will look like, 8, 34, 64, 51, 32, 21.
9. Which of the following real time examples is based on
insertion sort?
a) arranging a pack of playing cards
b) database scenarios and distributes scenarios
c) arranging books on a library shelf
Page 74 of 295
d) real-time systems
View Answer
Answer: a
Explanation: Arranging a pack of cards mimics an insertion
sort. Database scenario is an example for merge sort,
arranging books is a stack and real-time systems uses quick
sort.
10. In C, what are the basic loops required to perform an
insertion sort?
a) do- while
b) if else
c) for and while
d) for and if
View Answer
Answer: c
Explanation: To perform an insertion sort, we use two basic
loops- an outer for loop and an inner while loop.
11. Binary search can be used in an insertion sort algorithm
to reduce the number of comparisons.
a) True
b) False
View Answer
Page 75 of 295
Answer: a
Explanation: Binary search can be used in an insertion sort
algorithm to reduce the number of comparisons. This is
called a Binary insertion sort.
12. Which of the following options contain the correct
feature of an insertion sort algorithm?
a) anti-adaptive
b) dependable
c) stable, not in-place
d) stable, adaptive
View Answer
Answer: d
Explanation: An insertion sort is stable, adaptive, in-place
and incremental in nature.
13. Which of the following sorting algorithms is the fastest
for sorting small arrays?
a) Quick sort
b) Insertion sort
c) Shell sort
d) Heap sort
View Answer
Page 76 of 295
Answer: b
Explanation: For sorting small arrays, insertion sort runs
even faster than quick sort. But, it is impractical to sort large
arrays.
14. For the best case input, the running time of an insertion
sort algorithm is?
a) Linear
b) Binary
c) Quadratic
d) Depends on the input
View Answer
Answer: a
Explanation: The best case input for an insertion sort
algorithm runs in linear time and is given by O(N).
15. Which of the following examples represent the worst
case input for an insertion sort?
a) array in sorted order
b) array sorted in reverse order
c) normal unsorted array
d) large array
View Answer
Page 77 of 295
Answer: b
Explanation: The worst case input for an insertion sort
algorithm will be an array sorted in reverse order and its
running time is quadratic.
Insertion Sort Multiple Choice Questions and Answers
(MCQs) – 2
This set of Data Structures & Algorithms Multiple Choice
Questions & Answers (MCQs) focuses on “Insertion Sort –
2”.
1. Which of the following is correct with regard to insertion
sort?
a) insertion sort is stable and it sorts In-place
b) insertion sort is unstable and it sorts In-place
c) insertion sort is stable and it does not sort In-place
d) insertion sort is unstable and it does not sort In-place
View Answer
Answer: a
Explanation: During insertion sort, the relative order of
elements is not changed. Therefore, it is a stable sorting
algorithm. And insertion sort requires only O(1) of
additional memory space. Therefore, it sorts In-place.
Page 78 of 295
2. Which of the following sorting algorithm is best suited if
the elements are already sorted?
a) Heap Sort
b) Quick Sort
c) Insertion Sort
d) Merge Sort
View Answer
Answer: c
Explanation: The best case running time of the insertion sort
is O(n). The best case occurs when the input array is already
sorted. As the elements are already sorted, only one
comparison is made on each pass, so that the time required
is O(n).
3. The worst case time complexity of insertion sort is O(n2).
What will be the worst case time complexity of insertion
sort if the correct position for inserting element is calculated
using binary search?
a) O(nlogn)
b) O(n2)
c) O(n)
d) O(logn)
View Answer
Page 79 of 295
Answer: b
Explanation: The use of binary search reduces the time of
finding the correct position from O(n) to O(logn). But the
worst case of insertion sort remains O(n2) because of the
series of swapping operations required for each insertion.
advertisement
4. Insertion sort is an example of an incremental algorithm.
a) True
b) False
View Answer
Answer: a
Explanation: In the incremental algorithms, the complicated
structure on n items is built by first building it on n − 1
items. And then we make the necessary changes to fix
things in adding the last item. Insertion sort builds the
sorted sequence one element at a time. Therefore, it is an
example of an incremental algorithm.
5. Consider the code given below, which runs insertion sort:
Note: Join free Sanfoundry classes at Telegram or Youtube
void insertionSort(int arr[], int array_size)
{
Page 80 of 295
int i, j, value;
for (i = 1; i < array_size; i++)
{
value = arr[i];
j = i;
while (________ )
{
arr[j] = arr[j − 1];
j = j − 1;
}
arr[j] = value;
}
}
Which condition will correctly implement the while loop?
a) (j > 0) || (arr[j − 1] > value)
b) (j > 0) && (arr[j − 1] > value)
c) (j > 0) && (arr[j + 1] > value)
d) (j > 0) && (arr[j + 1] < value)
View Answer
Page 81 of 295
Answer: b
Explanation: In insertion sort, the element is A[j] is inserted
into the correct position in the sorted sequence A[1… j – 1].
So, condition given in (j > 0) && (arr[j − 1] > value) will
implement while loop correctly.
6. Which of the following is good for sorting arrays having
less than 100 elements?
a) Quick Sort
b) Selection Sort
c) Merge Sort
d) Insertion Sort
View Answer
Answer: d
Explanation: The insertion sort is good for sorting small
arrays. It sorts smaller arrays faster than any other sorting
algorithm.
7. Consider an array of length 5, arr[5] = {9,7,4,2,1}. What
are the steps of insertions done while running insertion sort
on the array?
a) 7 9 4 2 1 4 7 9 2 1 2 4 7 9 1 1 2 4 7 9
b) 9 7 4 1 2 9 7 1 2 4 9 1 2 4 7 1 2 4 7 9
c) 7 4 2 1 9 4 2 1 9 7 2 1 9 7 4 1 9 7 4 2
Page 82 of 295
d) 7 9 4 2 1 2 4 7 9 1 4 7 9 2 1 1 2 4 7 9
View Answer
Answer: a
Explanation: The steps performed while running insertion
sort on given array are:
Initial : 9 7 4 2 1 key = 7
7 9 4 2 1 key = 4
4 7 9 2 1 key = 2
2 4 7 9 1 key = 1
12479
In each step, the key is the element that is compared with
the elements present at the left side to it.
8. Statement 1: In insertion sort, after m passes through the
array, the first m elements are in sorted order.
Statement 2: And these elements are the m smallest
elements in the array.
a) Both the statements are true
b) Statement 1 is true but statement 2 is false
c) Statement 1 is false but statement 2 is true
d) Both the statements are false
View Answer
Page 83 of 295
Answer: b
Explanation: In insertion sort, after m passes through the
array, the first m elements are in sorted order but they are
whatever the first m elements were in the unsorted array.
9. In insertion sort, the average number of comparisons
required to place the 7th element into its correct position is
____
a) 9
b) 4
c) 7
d) 14
View Answer
Answer: b
Explanation: On average (k + 1) / 2 comparisons are
required to place the kth element into its correct position.
Therefore, average number of comparisons required for 7th
element = (7 + 1)/2 = 4.
10. Which of the following is not an exchange sort?
a) Bubble Sort
b) Quick Sort
c) Partition-exchange Sort
d) Insertion Sort
View Answer
Page 84 of 295
Answer: d
Explanation: In Exchange sorts, we compare each element
of an array and swap those elements that are not in their
proper position. Bubble Sort and Quick Sort are exchange
sorts. Quick Sort is also called as Partition-exchange Sort.
Insertion sort is not an exchange sort.
Data Structure Questions and Answers – Selection Sort
This set of Data Structure Multiple Choice Questions &
Answers (MCQs) focuses on “Selection Sort”.
1. What is an in-place sorting algorithm?
a) It needs O(1) or O(logn) memory to create auxiliary
locations
b) The input is already sorted and in-place
c) It requires additional storage
d) It requires additional space
View Answer
Answer: a
Explanation: Auxiliary memory is required for storing the
data temporarily.
2. In the following scenarios, when will you use selection
sort?
Page 85 of 295
a) The input is already sorted
b) A large file has to be sorted
c) Large values need to be sorted with small keys
d) Small values need to be sorted with large keys
View Answer
Answer: c
Explanation: Selection is based on keys, hence a file with
large values and small keys can be efficiently sorted with
selection sort.
3. What is the worst case complexity of selection sort?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)
View Answer
Answer: d
Explanation: Selection sort creates a sub-list, LHS of the
‘min’ element is already sorted and RHS is yet to be sorted.
Starting with the first element the ‘min’ element moves
towards the final element.
advertisement
Page 86 of 295
4. Select the appropriate code that performs selection sort.
a)
int min;
for(int j=0; j<[Link]-1; j++)
{
min = j;
for(int k=j+1; k<=[Link]-1; k++)
{
if(arr[k] < arr[min])
min = k;
}
int temp = arr[min];
arr[min] = arr[j];
arr[j] = temp;
}
b)
Subscribe Now: Design and Analysis of Algorithms
Newsletter | Important Subjects Newsletters
int min;
Page 87 of 295
for(int j=0; j<[Link]-1; j++)
{
min = j;
for(int k=j+1; k<=[Link]; k++)
{
if(arr[k] < arr[min])
min = k;
}
int temp = arr[min];
arr[min] = arr[j];
arr[j] = temp;
}
c)
int min;
for(int j=0; j<[Link]-1; j++)
{
min = j;
for(int k=j+1; k<=[Link]-1; k++)
{
Page 88 of 295
if(arr[k] > arr[min])
min = k;
}
int temp = arr[min];
arr[min] = arr[j];
arr[j] = temp;
}
d)
int min;
for(int j=0; j<[Link]-1; j++)
{
min = j;
for(int k=j+1; k<=[Link]; k++)
{
if(arr[k] > arr[min])
min = k;
}
int temp = arr[min];
arr[min] = arr[j];
Page 89 of 295
arr[j] = temp;
}
View Answer
Answer: a
Explanation: Starting with the first element as ‘min’
element, selection sort loops through the list to select the
least element which is then swapped with the ‘min’
element.
5. What is the advantage of selection sort over other sorting
techniques?
a) It requires no additional storage space
b) It is scalable
c) It works best for inputs which are already sorted
d) It is faster than any other sorting technique
View Answer
Answer: a
Explanation: Since selection sort is an in-place sorting
algorithm, it does not require additional storage.
6. What is the average case complexity of selection sort?
a) O(nlogn)
Page 90 of 295
b) O(logn)
c) O(n)
d) O(n2)
View Answer
Answer: d
Explanation: In the average case, even if the input is partially
sorted, selection sort behaves as if the entire array is not
sorted. Selection sort is insensitive to input.
7. What is the disadvantage of selection sort?
a) It requires auxiliary memory
b) It is not scalable
c) It can be used for small keys
d) It takes linear time to sort the elements
View Answer
Answer: b
Explanation: As the input size increases, the performance of
selection sort decreases.
8. The given array is arr = {3,4,5,2,1}. The number of
iterations in bubble sort and selection sort respectively are
__________
a) 5 and 4
b) 4 and 5
Page 91 of 295
c) 2 and 4
d) 2 and 5
View Answer
Answer: a
Explanation: Since the input array is not sorted, bubble sort
takes 5 iterations and selection sort takes 4(n-1) iterations.
9. The given array is arr = {1,2,3,4,5}. (bubble sort is
implemented with a flag variable)The number of iterations
in selection sort and bubble sort respectively are
__________
a) 5 and 4
b) 1 and 4
c) 0 and 4
d) 4 and 1
View Answer
Answer: d
Explanation: Selection sort is insensitive to input, hence 4(n-
1) iterations. Whereas bubble sort iterates only once to set
the flag to 0 as the input is already sorted.
10. What is the best case complexity of selection sort?
a) O(nlogn)
b) O(logn)
Page 92 of 295
c) O(n)
d) O(n2)
View Answer
Answer: d
Explanation: The best, average and worst case complexities
of selection sort is O(n2).
(n-1) + (n-2) + (n-3) + …. + 1 = (n(n-1))/2 ~ (n2)/2.
Data Structure Questions and Answers – Bubble Sort
This set of Data Structure Multiple Choice Questions &
Answers (MCQs) focuses on “Bubble Sort”.
1. What is an external sorting algorithm?
a) Algorithm that uses tape or disk during the sort
b) Algorithm that uses main memory during the sort
c) Algorithm that involves swapping
d) Algorithm that are considered ‘in place’
View Answer
Answer: a
Explanation: As the name suggests, external sorting
algorithm uses external memory like tape or disk.
2. What is an internal sorting algorithm?
a) Algorithm that uses tape or disk during the sort
b) Algorithm that uses main memory during the sort
Page 93 of 295
c) Algorithm that involves swapping
d) Algorithm that are considered ‘in place’
View Answer
Answer: b
Explanation: As the name suggests, internal sorting
algorithm uses internal main memory.
3. What is the worst case complexity of bubble sort?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)
View Answer
Answer: d
Explanation: Bubble sort works by starting from the first
element and swapping the elements if required in each
iteration.
advertisement
4. Select the appropriate code that performs bubble sort.
a)
for(int j=[Link]-1; j>=0; j--)
{
Page 94 of 295
for(int k=0; k<j; k++)
{
if(arr[k] > arr[k+1])
{
int temp = arr[k];
arr[k] = arr[k+1];
arr[k+1] = temp;
}
}
}
b)
Sanfoundry Certification Contest of the Month is Live. 100+
Subjects. Participate Now!
for(int j=[Link]-1; j>=0; j--)
{
for(int k=0; k<j; k++)
{
if(arr[k] < arr[k+1])
{
Page 95 of 295
int temp = arr[k];
arr[k] = arr[k+1];
arr[k+1] = temp;
}
}
}
c)
for(int j=[Link]; j>=0; j--)
{
for(int k=0; k<j; k++)
{
if(arr[k] > arr[k+1])
{
int temp = arr[k];
arr[k] = arr[k+1];
arr[k+1] = temp;
}
}
}
Page 96 of 295
d)
for(int j=[Link]; j>=0; j--)
{
for(int k=0; k<j; k++)
{
if(arr[k] > arr[k+2])
{
int temp = arr[k];
arr[k] = arr[k+1];
arr[k+1] = temp;
}
}
}
View Answer
Answer: a
Explanation: The outer loop keeps count of number of
iterations, and the inner loop checks to see if swapping is
necessary.
Page 97 of 295
5. What is the average case complexity of bubble sort?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)
View Answer
Answer: d
Explanation: Bubble sort works by starting from the first
element and swapping the elements if required in each
iteration even in the average case.
6. Which of the following is not an advantage of optimised
bubble sort over other sorting techniques in case of sorted
elements?
a) It is faster
b) Consumes less memory
c) Detects whether the input is already sorted
d) Consumes less time
View Answer
Answer: c
Explanation: Optimised Bubble sort is one of the simplest
Page 98 of 295
sorting techniques and perhaps the only advantage it has
over other techniques is that it can detect whether the
input is already sorted. It is faster than other in case of
sorted array and consumes less time to describe whether
the input array is sorted or not. It consumes same memory
than other sorting techniques. Hence it is not an advantage.
7. The given array is arr = {1, 2, 4, 3}. Bubble sort is used to
sort the array elements. How many iterations will be done
to sort the array?
a) 4
b) 2
c) 1
d) 0
View Answer
Answer: a
Explanation: Even though the first two elements are already
sorted, bubble sort needs 4 iterations to sort the given
array.
8. How can you improve the best case efficiency in bubble
sort? (The input is already sorted)
a)
boolean swapped = false;
Page 99 of 295
for(int j=[Link]-1; j>=0 && swapped; j--)
{
swapped = true;
for(int k=0; k<j; k++)
{
if(arr[k] > arr[k+1])
{
int temp = arr[k];
arr[k] = arr[k+1];
arr[k+1] = temp;
swapped = false;
}
}
}
b)
boolean swapped = true;
for(int j=[Link]-1; j>=0 && swapped; j--)
{
swapped = false;
Page 100 of 295
for(int k=0; k<j; k++)
{
if(arr[k] > arr[k+1])
{
int temp = arr[k];
arr[k] = arr[k+1];
arr[k+1] = temp;
}
}
}
c)
boolean swapped = true;
for(int j=[Link]-1; j>=0 && swapped; j--)
{
swapped = false;
for(int k=0; k<j; k++)
{
if(arr[k] > arr[k+1])
{
Page 101 of 295
int temp = arr[k];
arr[k] = arr[k+1];
arr[k+1] = temp;
swapped = true;
}
}
}
d)
boolean swapped = true;
for(int j=[Link]-1; j>=0 && swapped; j--)
{
for(int k=0; k<j; k++)
{
if(arr[k] > arr[k+1])
{
int temp = arr[k];
arr[k] = arr[k+1];
arr[k+1] = temp;
swapped = true;
Page 102 of 295
}
}
}
View Answer
Answer: c
Explanation: A boolean variable ‘swapped’ determines
whether any swapping has happened in a particular
iteration, if no swapping has occurred, then the given array
is sorted and no more iterations are required.
9. What is the best case efficiency of bubble sort in the
improvised version?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)
View Answer
Answer: c
Explanation: Some iterations can be skipped if the list is
sorted, hence efficiency improves to O(n).
Page 103 of 295
10. The given array is arr = {1,2,4,3}. Bubble sort is used to
sort the array elements. How many iterations will be done
to sort the array with improvised version?
a) 4
b) 2
c) 1
d) 0
View Answer
Answer: b
Explanation: Only 2 elements in the given array are not
sorted, hence only 2 iterations are required to sort them.
Merge Sort Multiple Choice Questions and Answers
This set of Data Structures & Algorithms Multiple Choice
Questions & Answers (MCQs) focuses on “Merge Sort”.
1. Merge sort uses which of the following technique to
implement sorting?
a) backtracking
b) greedy algorithm
c) divide and conquer
d) dynamic programming
View Answer
Page 104 of 295
Answer: c
Explanation: Merge sort uses divide and conquer in order to
sort a given array. This is because it divides the array into
two halves and applies merge sort algorithm to each half
individually after which the two sorted halves are merged
together.
2. What is the average case time complexity of merge sort?
a) O(n log n)
b) O(n2)
c) O(n2 log n)
d) O(n log n2)
View Answer
Answer: a
Explanation: The recurrence relation for merge sort is given
by T(n) = 2T(n/2) + n. It is found to be equal to O(n log n)
using the master theorem.
3. What is the auxiliary space complexity of merge sort?
a) O(1)
b) O(log n)
c) O(n)
d) O(n log n)
View Answer
Page 105 of 295
Answer: c
Explanation: An additional space of O(n) is required in order
to merge two sorted arrays. Thus merge sort is not an in
place sorting algorithm.
advertisement
4. Merge sort can be implemented using O(1) auxiliary
space.
a) true
b) false
View Answer
Answer: a
Explanation: Standard merge sort requires O(n) space to
merge two sorted arrays. We can optimize this merging
process so that it takes only constant space. This version is
known as in place merge sort.
5. What is the worst case time complexity of merge sort?
a) O(n log n)
b) O(n2)
c) O(n2 log n)
d) O(n log n2)
View Answer
Page 106 of 295
Answer: a
Explanation: The time complexity of merge sort is not
affected by worst case as its algorithm has to implement the
same number of steps in any case. So its time complexity
remains to be O(n log n).
Sanfoundry Certification Contest of the Month is Live. 100+
Subjects. Participate Now!
6. Which of the following method is used for sorting in
merge sort?
a) merging
b) partitioning
c) selection
d) exchanging
View Answer
Answer: a
Explanation: Merge sort algorithm divides the array into two
halves and applies merge sort algorithm to each half
individually after which the two sorted halves are merged
together. Thus its method of sorting is called merging.
7. What will be the best case time complexity of merge sort?
a) O(n log n)
b) O(n2)
Page 107 of 295
c) O(n2 log n)
d) O(n log n2)
View Answer
Answer: a
Explanation: The time complexity of merge sort is not
affected in any case as its algorithm has to implement the
same number of steps. So its time complexity remains to be
O(n log n) even in the best case.
8. Which of the following is not a variant of merge sort?
a) in-place merge sort
b) bottom up merge sort
c) top down merge sort
d) linear merge sort
View Answer
Answer: d
Explanation: In-place, top down and bottom up merge sort
are different variants of merge sort. Whereas linear merge
sort is not a possible variant as it is a comparison based sort
and the minimum time complexity of any comparison based
sort is O(n log n).
9. Choose the incorrect statement about merge sort from
the following?
Page 108 of 295
a) it is a comparison based sort
b) it is an adaptive algorithm
c) it is not an in place algorithm
d) it is stable algorithm
View Answer
Answer: b
Explanation: Merge sort is not an adaptive sorting
algorithm. This is because it takes O(n log n) time complexity
irrespective of any case.
10. Which of the following is not in place sorting algorithm
by default?
a) merge sort
b) quick sort
c) heap sort
d) insertion sort
View Answer
Answer: a
Explanation: Quick sort, heap sort, and insertion sort are in-
place sorting algorithms, whereas an additional space of
O(n) is required in order to merge two sorted arrays. Even
though we have a variation of merge sort (to do in-place
sorting), it is not the default option. So, among the given
choices, merge sort is the most appropriate answer.
Page 109 of 295
11. Which of the following is not a stable sorting algorithm?
a) Quick sort
b) Cocktail sort
c) Bubble sort
d) Merge sort
View Answer
Answer: a
Explanation: Out of the given options quick sort is the only
algorithm which is not stable. Merge sort is a stable sorting
algorithm.
12. Which of the following stable sorting algorithm takes the
least time when applied to an almost sorted array?
a) Quick sort
b) Insertion sort
c) Selection sort
d) Merge sort
View Answer
Answer: d
Explanation: Insertion sort takes linear time to sort a
partially sorted array. Though merge and quick sort takes
O(n*logn) complexity to sort, merge sort is stable. Hence,
Merge sort takes less time to sort partially sorted array.
Page 110 of 295
13. Merge sort is preferred for arrays over linked lists.
a) true
b) false
View Answer
Answer: b
Explanation: Merge sort is preferred for linked list over
arrays. It is because in a linked list the insert operation takes
only O(1) time and space which implies that we can
implement merge operation in constant time.
14. Which of the following sorting algorithm makes use of
merge sort?
a) tim sort
b) intro sort
c) bogo sort
d) quick sort
View Answer
Answer: a
Explanation: Tim sort is a hybrid sorting algorithm as it uses
more than one sorting algorithm internally. It makes use of
merge sort and insertion sort.
15. Choose the correct code for merge sort.
a)
Page 111 of 295
void merge_sort(int arr[], int left, int right)
{
if (left > right)
{
int mid = (right-left)/2;
merge_sort(arr, left, mid);
merge_sort(arr, mid+1, right);
merge(arr, left, mid, right); //function to merge sorted
arrays
}
}
b)
void merge_sort(int arr[], int left, int right)
{
if (left < right)
{
Page 112 of 295
int mid = left+(right-left)/2;
merge_sort(arr, left, mid);
merge_sort(arr, mid+1, right);
merge(arr, left, mid, right); //function to merge sorted
arrays
}
}
c)
void merge_sort(int arr[], int left, int right)
{
if (left < right)
{
int mid = left+(right-left)/2;
merge(arr, left, mid, right); //function to merge sorted
arrays
merge_sort(arr, left, mid);
merge_sort(arr, mid+1, right);
Page 113 of 295
}
}
d)
void merge_sort(int arr[], int left, int right)
{
if (left < right)
{
int mid = (right-left)/2;
merge(arr, left, mid, right); //function to merge sorted
arrays
merge_sort(arr, left, mid);
merge_sort(arr, mid+1, right);
}
}
Page 114 of 295
View Answer
Answer: b
Explanation: Merge sort first sorts the two halves of the
array individually. Then it merges the two sorted halves in
order to obtain sorted array.
16. Which of the following sorting algorithm does not use
recursion?
a) quick sort
b) merge sort
c) heap sort
d) bottom up merge sort
View Answer
Answer: d
Explanation: Bottom up merge sort uses the iterative
method in order to implement sorting. It begins by merging
a pair of adjacent array of size 1 each and then merge arrays
of size 2 each in the next step and so on.
Heap Sort Multiple Choice Questions and Answers
This set of Data Structures & Algorithms Multiple Choice
Questions & Answers (MCQs) focuses on “Heap Sort”.
Page 115 of 295
1. On which algorithm is heap sort based on?
a) Fibonacci heap
b) Binary tree
c) Priority queue
d) FIFO
View Answer
Answer: c
Explanation: Heap sort is based on the algorithm of priority
queue and it gives the best sorting time.
2. In what time can a binary heap be built?
a) O(N)
b) O(N log N)
c) O(log N)
d) O(N2)
View Answer
Answer: a
Explanation: The basic strategy is to build a binary heap of N
elements which takes O(N) time.
3. Heap sort is faster than Shell sort.
a) true
b) false
View Answer
Page 116 of 295
Answer: b
Explanation: Heap sort is slower than Shell sort because
Shell sort uses Sedgewick’s increment sequence.
advertisement
4. Consider the following heap after buildheap phase. What
will be its corresponding array?
a) 26,53,41,97,58,59,31
b) 26,31,41,53,58,59,97
c) 26,41,53,97,31,58,59
d) 97,53,59,26,41,58,31
View Answer
Answer: d
Explanation: Constructing a max heap using the elements
97,53,59,26,41,58,31 will cause the heap to look like that.
5. In what position does the array for heap sort contains
data?
a) 0
Page 117 of 295
b) 1
c) -1
d) anywhere in the array
View Answer
Answer: a
Explanation: The array for heap sort contains data at
position 0 whereas for a binary heap, array begins at 1. This
is the reason for its complexity.
Subscribe Now: Design and Analysis of Algorithms
Newsletter | Important Subjects Newsletters
6. In heap sort, after deleting the last minimum element,
the array will contain elements in?
a) increasing sorting order
b) decreasing sorting order
c) tree inorder
d) tree preorder
View Answer
Answer: b
Explanation: By logic, after deleting minimum element, the
heap will contain elements in decreasing sorting order. We
can change this by altering the ordering property.
Page 118 of 295
7. What is the typical running time of a heap sort algorithm?
a) O(N)
b) O(N log N)
c) O(log N)
d) O(N2)
View Answer
Answer: b
Explanation: The total running time of a heap sort algorithm
is mathematically found to be O(N log N).
8. How many arrays are required to perform deletion
operation in a heap?
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: b
Explanation: To perform deletion operation in a heap, we
require 2 arrays and that occupies extra memory space and
hence increase in running time.
9. What is the time taken to perform a delete min
operation?
Page 119 of 295
a) O(N)
b) O(N log N)
c) O(log N)
d) O(N2)
View Answer
Answer: c
Explanation: The time taken to perform a deletion of a
minimum element is mathematically found to be O( log N).
10. Heap sort is an extremely stable algorithm.
a) true
b) false
View Answer
Answer: a
Explanation: Heap sort uses fewer comparisons than other
sorting algorithms and hence it is an extremely stable
algorithm.
11. What is the average number of comparisons used in a
heap sort algorithm?
a) N log N-O(N)
b) O(N log N)-O(N)
c) O(N log N)-1
Page 120 of 295
d) 2N log N + O(N)
View Answer
Answer: d
Explanation: The average number of comparisons in a
heapsort algorithm is mathematically found to be 2N log N +
O(N).
12. What is the time taken to copy elements to and from
two arrays created for deletion?
a) O(N)
b) O(N log N)
c) O(log N)
d) O(N2)
View Answer
Answer: a
Explanation: The time taken to copy elements to and from
the main array and extra array is found to be O(N).
13. What is the average number of comparisons used to
heap sort a random permutation of N distinct items?
a) 2N log N-O(N)
b) 2N log N-O(N log N)
c) 2N log N-O(N log log N)
Page 121 of 295
d) 2N log N-O(log N)
View Answer
Answer: c
Explanation: According to a theorem, the average number of
comparisons used to heap sort a random permutation of N
distinct items is found to be 2N log N-O(N log log N).
Heap Sort Multiple Choice Questions and Answers – 2
This set of Data Structures & Algorithms Multiple Choice
Questions & Answers (MCQs) focuses on “Heap Sort – 2”.
1. Heap sort is an implementation of ____________ using a
descending priority queue.
a) insertion sort
b) selection sort
c) bubble sort
d) merge sort
View Answer
Answer: b
Explanation: Heap sort is an implementation of selection
sort using the input array as a heap representing a
descending priority queue. Heap sort algorithm is divided
into two phase. In first phase the max-heap is created and
Page 122 of 295
the second phase (selection phase) deletes the elements
from the priority queue using siftdown operation.
2. Which one of the following is false?
a) Heap sort is an in-place algorithm
b) Heap sort has O(nlogn) average case time complexity
c) Heap sort is stable sort
d) Heap sort is a comparison-based sorting algorithm
View Answer
Answer: c
Explanation: Heap sort is a comparison based sorting
algorithm and has time complexity O(nlogn) in the average
case. Heap sort is an in-place algorithm as it needs O(1) of
auxiliary space. Heap sort uses heap and operations on heap
can change the relative order of items with the same key
values. Therefore, Heap sort is not a stable sort.
3. The essential part of Heap sort is construction of max-
heap. Consider the tree shown below, the node 24 violates
the max-heap property. Once heapify procedure is applied
to it, which position will it be in?
Page 123 of 295
a) 4
b) 5
c) 8
d) 9
View Answer
Answer: d
Explanation: In max-heap element at each node is smaller
than or equal to the element at its parent node. On applying
the heapify procedure on item at position 2, it will be in
position 9 as shown below.
Page 124 of 295
advertisement
4. The descending heap property is ___________
a) A[Parent(i)] = A[i]
b) A[Parent(i)] <= A[i]
c) A[Parent(i)] >= A[i]
d) A[Parent(i)] > 2 * A[i]
View Answer
Answer: c
Explanation: The max-heap is also known as descending
heap. Max-heap of size n is an almost complete binary tree
of n nodes such that the element at each node is less than
or equal to the element at its parent node.
5. What is its wort case time complexity of Heap sort?
a) O(nlogn)
b) O(n2logn)
c) O(n2)
d) O(n3)
View Answer
Answer: a
Explanation: In Heap sort, the call to procedure build_Max-
heap takes O(n) time and each of O(n) calls to the function
Page 125 of 295
max_Heapify takes O(logn) time. So the worst case
complexity of Heap sort is O(nlogn).
Note: Join free Sanfoundry classes at Telegram or Youtube
6. In average case Heap sort is as efficient as the Quick sort.
a) True
b) False
View Answer
Answer: b
Explanation: Quick sort is more efficient than Heap sort
because experiments indicate that Heap sort requires twice
as much time as Quick sort for randomly sorted input.
7. Choose the correct option to fill? X so that the code given
below implements the Heap sort.
#include <stdio.h>
void heapify(int arr[], int n, int i)
{
int largest = i; // Initialize largest as root
int l = 2*i + 1; // left = 2*i + 1
int r = 2*i + 2; // right = 2*i + 2
if (l < n && arr[l] > arr[largest])
Page 126 of 295
largest = l;
if (r < n && arr[r] > arr[largest])
largest = r;
if (largest != i)
{
swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}
void heapSort(int arr[], int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
for (int i=n-1; i>=0; i--)
{
X;
heapify(arr, i, 0);
}
}
Page 127 of 295
void printArray(int arr[], int n)
{
for (int i=0; i<n; ++i)
printf(“%d”,arr[i]);
printf(“\n”);
}
int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr)/sizeof(arr[0]);
heapSort(arr, n);
printf(“Sorted array is \n");
printArray(arr, n);
}
a) swap(arr[0], arr[n])
b) swap(arr[i], arr[n])
c) swap(arr[0], arr[i])
d) swap(arr[i], arr[2*i])
View Answer
Page 128 of 295
Answer: c
Explanation: Steps in heap sort are : (i) Build the max-heap,
(ii) Swap the root element with the last element of the
heap, (iii) Reduce the size of heap by 1 and heapify the root
element, (iv) Repeat the steps form step number (v) until all
the elements are sorted. Therefore the correct option is
swap(arr[0], arr[i]).
8. Which one of the following is a variation of Heap sort?
a) Comb sort
b) Smooth sort
c) Binary tree sort
d) Shell sort
View Answer
Answer: b
Explanation: Smooth sort is a variation of Heap sort. Smooth
sort has O(nlogn) worst case time complexity like Heap sort.
But Smooth sort takes O(n) time to sort the nearly sorted
input array.
9. Introsort algorithm is combination of _____________
a) Quick sort and Heap sort
b) Quick sort and Shell sort
c) Heap sort and Merge sort
Page 129 of 295
d) Heap sort and insertion sort
View Answer
Answer: a
Explanation: Introsort is a hybrid sorting algorithm that
combines Quick sort and Heap sort to retain advantages of
both. It has worst case speed of Heap sort and average case
speed of Quick sort.
10. How many elements can be sorted in O(logn) time using
Heap sort?
a) O(1)
b) O(n/2)
c) O(logn/log(logn))
d) O(logn)
View Answer
Answer: c
Explanation: The time complexity of Heap sort is O(klogk)
for k input elements,
for k = logn/log(logn),
O(klogk) = O(logn/log(logn) * log(logn/log(logn)))
∴ O(klogk) = O(logn/log(logn) * (log(logn) – log(log(logn))))
= O(logn)
Hence the correct option is O(logn/log(logn)).
Page 130 of 295
Binary Tree Sort Multiple Choice Questions and Answers
(MCQs)
This set of Data Structures & Algorithms Multiple Choice
Questions & Answers (MCQs) focuses on “Binary Tree Sort”.
1. Consider the original array 17 8 12 4 26. How many
comparisons are needed to construct the BST on the original
array?
a) 5
b) 4
c) 7
d) 10
View Answer
Answer: d
Explanation: Original array is 17 8 12 4 26. The BST built on
this array is shown in the figure below.
Page 131 of 295
To built the BST, we travel down the tree until a leaf is
reached. Therefore, for every element we compare the
element with the internal nodes until we the leaves and
then once again compare the element with its parent to
decide whether it is right child or left child. So, for given
array we need to perform 10 comparisons to build the BST.
2. In binary tree sort, we first construct the BST and then we
perform _______ traversal to get the sorted order.
a) inorder
b) postorder
c) preorder
d) level order
View Answer
Answer: a
Explanation: In binary tree sort is a sort algorithm where a
binary search tree is built from the elements to be sorted,
and then we perform inorder traversal on the BST to get the
elements in sorted order.
3. What is the worst case time complexity of the binary tree
sort?
a) O(n)
b) O(nlogn)
c) O(n2)
Page 132 of 295
d) O(logn)
View Answer
Answer: c
Explanation: For the binary tree sort the worst case when
the BST constructed is unbalanced. BST gets unbalanced
when the elements are already sorted. So, in the worst case,
O(n2) time is required to built the BST and O(n) time to
traverse the tree. Therefore, the worst case time complexity
is O(n2) + O(n) = O(n2).
advertisement
4. The insert() procedure, given below, builds the BST on the
input elements, which is the first step of the binary tree
sort. Choose the correct to fill the condition.
void insert(Tree* node, int newElement)
{
if(node== NULL)
{
node = createNewNode();
node-> value = newElement;
node -> left = NULL;
Page 133 of 295
node -> right = NULL;
return;
}
else if(__________________)
{
insert(node->left, newElement);
}
else
{
insert(node->right, newElement);
}
}
a) newElement > node->value
b) newElement < node->value
c) newElement == root->value
d) newElement != root->value
View Answer
Answer: b
Explanation: In binary tree sort, the BST is built on the input
elements and the tree is traversed in in-order to get the
Page 134 of 295
sorted order. While building the BST, we travel down the
tree until a leaf is reached. While traveling dawn the tree,
we travel on left subtree if the new element is less than the
node or to the right if the element is greater or equal to the
node. So, correct option is newElement < node->value.
Note: Join free Sanfoundry classes at Telegram or Youtube
5. What is the best case time complexity of the binary tree
sort?
a) O(n)
b) O(nlogn)
c) O(n2)
d) O(logn)
View Answer
Answer: b
Explanation: The best case occurs when the BST is balanced.
So, when tree is balanced we require O(nlogn) time to build
the tree and O(n) time to traverse the tree. So, the best case
time complexity of the binary tree sort is O(nlogn).
6. Binary tree sort is an in-place sorting algorithm.
a) True
b) False
View Answer
Page 135 of 295
Answer: b
Explanation: In binary tree sort it is required to reserve one
tree node for each array element. Its implementation
requires two pointer variables for each node. So, it requires
extra memory. The worst case space complexity of binary
tree sort is Θ(n). Therefore, binary tree sort is not an in-
place sorting algorithm.
7. Which of the following is false?
a) Binary tree sort and quick sort have same running time
b) Binary tree sort used BST as work area
c) As the number of elements to sort gets larger, binary tree
sort gets more and more efficient
d) Both quick sort and binary tree are in place sorting
algorithms
View Answer
Answer: d
Explanation: Binary tree sort and quick sort have same
running time i.e O(nlogn)
in average case and O(n2) in worst case. Binary tree is not in-
place sorting algorithm.
8. Which of the following sorting algorithms can be
considered as improvement to the binary tree sort?
a) Heap sort
Page 136 of 295
b) Quick sort
c) Selection sort
d) Insertion sort
View Answer
Answer: a
Explanation: Heap sort is basically improvement to the
binary tree sort. Heap sort builds a heap on the input
element by adjusting the position of the elements within
the original array, rather than creating nodes as in binary
tree sort.
9. Consider the following statements related to the binary
tree sort.
I. Element can be added gradually as they become available
II. It needs extra memory space
a) Statement I is true but Statement II is false
b) Both Statement I and Statement II are false
c) Both Statement I and Statement II are true
d) Statement II is true but Statement I is false
View Answer
Answer: c
Explanation: Binary tree sort is dynamic sorting, that is it
gets more efficient as more the elements are added. So, we
can add elements gradually as they become available.
Page 137 of 295
Binary tree sort requires extra memory space, its worst case
space complexity is Θ(n).
Depth First Search (DFS) Multiple Choice Questions and
Answers
This set of Data Structure Multiple Choice Questions &
Answers (MCQs) focuses on “Depth First Search (DFS)”.
1. Depth First Search is equivalent to which of the traversal
in the Binary Trees?
a) Pre-order Traversal
b) Post-order Traversal
c) Level-order Traversal
d) In-order Traversal
View Answer
Answer: a
Explanation: In Depth First Search, we explore all the nodes
aggressively to one path and then backtrack to the node.
Hence, it is equivalent to the pre-order traversal of a Binary
Tree.
2. Time Complexity of DFS is? (V – number of vertices, E –
number of edges)
a) O(V + E)
b) O(V)
Page 138 of 295
c) O(E)
d) O(V*E)
View Answer
Answer: a
Explanation: The Depth First Search explores every node
once and every edge once (in worst case), so it’s time
complexity is O(V + E).
3. The Data structure used in standard implementation of
Breadth First Search is?
a) Stack
b) Queue
c) Linked List
d) Tree
View Answer
Answer: a
Explanation: The Depth First Search is implemented using
recursion. So, stack can be used as data structure to
implement depth first search.
advertisement
4. The Depth First Search traversal of a graph will result
into?
a) Linked List
Page 139 of 295
b) Tree
c) Graph with back edges
d) Array
View Answer
Answer: b
Explanation: The Depth First Search will make a graph which
don’t have back edges (a tree) which is known as Depth First
Tree.
5. A person wants to visit some places. He starts from a
vertex and then wants to visit every vertex till it finishes
from one vertex, backtracks and then explore other vertex
from same vertex. What algorithm he should use?
a) Depth First Search
b) Breadth First Search
c) Trim’s algorithm
d) Kruskal’s Algorithm
View Answer
Answer: a
Explanation: This is the definition of the Depth First Search.
Exploring a node, then aggressively finding nodes till it is not
able to find any node.
Note: Join free Sanfoundry classes at Telegram or Youtube
Page 140 of 295
6. Which of the following is not an application of Depth First
Search?
a) For generating topological sort of a graph
b) For generating Strongly Connected Components of a
directed graph
c) Detecting cycles in the graph
d) Peer to Peer Networks
View Answer
Answer: d
Explanation: Depth First Search is used in the Generation of
topological sorting, Strongly Connected Components of a
directed graph and to detect cycles in the graph. Breadth
First Search is used in peer to peer networks to find all
neighbourhood nodes.
7. When the Depth First Search of a graph is unique?
a) When the graph is a Binary Tree
b) When the graph is a Linked List
c) When the graph is a n-ary Tree
d) When the graph is a ternary Tree
View Answer
Answer: b
Explanation: When Every node will have one successor then
the Depth First Search is unique. In all other cases, when it
Page 141 of 295
will have more than one successor, it can choose any of
them in arbitrary order.
8. Regarding implementation of Depth First Search using
stacks, what is the maximum distance between two nodes
present in the stack? (considering each edge length 1)
a) Can be anything
b) 0
c) At most 1
d) Insufficient Information
View Answer
Answer: a
Explanation: In the stack, at a time, there can be nodes
which can differ in many levels. So, it can be the maximum
distance between two nodes in the graph.
9. In Depth First Search, how many times a node is visited?
a) Once
b) Twice
c) Equivalent to number of indegree of the node
d) Thrice
View Answer
Answer: c
Explanation: In Depth First Search, we have to see whether
Page 142 of 295
the node is visited or not by it’s ancestor. If it is visited, we
won’t let it enter it in the stack.
Data Structure Questions and Answers – Non-recursive
Depth First Search
This set of Data Structures & Algorithms Multiple Choice
Questions & Answers (MCQs) focuses on “Non-recursive
Depth First Search”.
1. Which of the following data structure is used to
implement DFS?
a) linked list
b) tree
c) stack
d) queue
View Answer
Answer: c
Explanation: Stack is used in the standard implementation
of depth first search. It is used to store the elements which
are to be explored.
2. Which of the following traversal in a binary tree is similar
to depth first traversal?
a) level order
b) post order
Page 143 of 295
c) pre order
d) in order
View Answer
Answer: c
Explanation: In DFS we keep on exploring as far as possible
along each branch before backtracking. It terminates when
all nodes are visited. So it is similar to pre order traversal in
binary tree.
3. What will be the result of depth first traversal in the
following tree?
a) 4 2 5 1 3
b) 1 2 4 5 3
c) 4 5 2 3 1
d) 1 2 3 4 5
View Answer
Answer: b
Explanation: Depth first search is similar to pre order
traversal in a tree. So here we will get the same result as for
the pre order traversal (root,left right).
advertisement
Page 144 of 295
4. Which of the following is a possible result of depth first
traversal of the given graph(consider 1 to be source
element)?
a) 1 2 3 4 5
b) 1 2 3 1 4 5
c) 1 4 5 3 2
d) 1 4 5 1 2 3
View Answer
Answer: a
Explanation: As 1 is the source element so it will be
considered first. Then we start exploring the vertices which
are connected to 1. So there will be two possible results-1 2
3 4 5 and 1 4 5 2 3.
5. Which of the following represent the correct pseudo code
for non recursive DFS algorithm?
a)
Subscribe Now: Design and Analysis of Algorithms
Newsletter | Important Subjects Newsletters
procedure DFS-non_recursive(G,v):
//let St be a stack
Page 145 of 295
[Link](v)
while St is not empty
v = [Link]()
if v is not discovered:
label v as discovered
for all adjacent vertices of v do
[Link](a) //a being the adjacent vertex
b)
procedure DFS-non_recursive(G,v):
//let St be a stack
[Link]()
while St is not empty
v = [Link](v)
if v is not discovered:
label v as discovered
for all adjacent vertices of v do
[Link](a) //a being the adjacent vertex
c)
procedure DFS-non_recursive(G,v):
Page 146 of 295
//let St be a stack
[Link](v)
while St is not empty
v = [Link]()
if v is not discovered:
label v as discovered
for all adjacent vertices of v do
[Link](v)
d)
procedure DFS-non_recursive(G,v):
//let St be a stack
[Link](v)
while St is not empty
v = [Link]()
if v is not discovered:
label v as discovered
for all adjacent vertices of v do
[Link](a) //a being the adjacent vertex
View Answer
Page 147 of 295
Answer: a
Explanation: In the iterative approach we first push the
source node into the stack. If the node has not been visited
then it is printed and marked as visited. Then the unvisited
adjacent nodes are added to the stack. Then the same
procedure is repeated for each node of the stack.
6. What will be the time complexity of the iterative depth
first traversal code(V=no. of vertices E=[Link] edges)?
a) O(V+E)
b) O(V)
c) O(E)
d) O(V*E)
View Answer
Answer: a
Explanation: As the time required to traverse a full graph is
V+E so its worst case time complexity becomes O(V+E). The
time complexity of iterative and recursive DFS are same.
7. Which of the following functions correctly represent
iterative DFS?
a)
Page 148 of 295
void DFS(int s)
{
vector<bool> discovered(V, true);
stack<int> st;
[Link](s);
while (![Link]())
{
s = [Link]();
[Link]();
if (!discovered[s])
{
cout << s << " ";
discovered[s] = true;
}
for (auto i = adjacent[s].begin(); i != adjacent[s].end();
++i)
if (!discovered[*i])
[Link](*i);
}
Page 149 of 295
}
b)
void DFS(int s)
{
vector<bool> discovered(V, false);
stack<int> st;
[Link](s);
while (![Link]())
{
s = [Link]();
[Link]();
if (!discovered[s])
{
cout << s << " ";
discovered[s] = true;
}
for (auto i = adjacent[s].begin(); i != adjacent[s].end();
++i)
if (!discovered[*i])
Page 150 of 295
[Link](*i);
}
}
c)
void DFS(int s)
{
vector<bool> discovered(V, false);
stack<int> st;
[Link](s);
while (![Link]())
{
[Link]();
s = [Link]();
if (!discovered[s])
{
cout << s << " ";
discovered[s] = true;
}
Page 151 of 295
for (auto i = adjacent[s].begin(); i != adjacent[s].end();
++i)
if (!discovered[*i])
[Link](*i);
}
}
d)
void DFS(int s)
{
vector<bool> discovered(V, false);
stack<int> st;
[Link](s);
while (![Link]())
{
s = [Link]();
[Link]();
if (!discovered[s])
{
cout << s << " ";
Page 152 of 295
discovered[s] = false;
}
for (auto i = adjacent[s].begin(); i != adjacent[s].end();
++i)
if (discovered[*i])
[Link](*i);
}
}
View Answer
Answer: b
Explanation: In the correct version we first push the source
node into the stack. If the node has not been visited then it
is printed and marked as visited. Then the unvisited
adjacent nodes are added to the stack. Then the same
procedure is repeated for each node of the stack.
8. What is the space complexity of standard DFS(V: no. of
vertices E: no. of edges)?
a) O(V+E)
b) O(V)
Page 153 of 295
c) O(E)
d) O(V*E)
View Answer
Answer: b
Explanation: In the worst case the space complexity of DFS
will be O(V) in the case when all the vertices are stored in
stack. This space complexity is excluding the space required
to store the graph.
9. Which of the following data structure is used to
implement BFS?
a) linked list
b) tree
c) stack
d) queue
View Answer
Answer: d
Explanation: Queue is used in the standard implementation
of breadth first search. It is used to store the vertices
according to the code algorithm.
10. Choose the incorrect statement about DFS and BFS from
the following?
a) BFS is equivalent to level order traversal in trees
Page 154 of 295
b) DFS is equivalent to post order traversal in trees
c) DFS and BFS code has the same time complexity
d) BFS is implemented using queue
View Answer
Answer: b
Explanation: DFS is equivalent to pre order traversal in trees,
not post order traversal. It is so because in DFS we keep on
exploring as far as possible along each branch before
backtracking. So it should be equivalent to pre order
traversal.
Data Structure Questions and Answers – Breadth First
Search
This set of Data Structure Multiple Choice Questions &
Answers (MCQs) focuses on “Breadth First Search”.
1. Breadth First Search is equivalent to which of the
traversal in the Binary Trees?
a) Pre-order Traversal
b) Post-order Traversal
c) Level-order Traversal
d) In-order Traversal
View Answer
Page 155 of 295
Answer: c
Explanation: The Breadth First Search Algorithm searches
the nodes on the basis of level. It takes a node (level 0),
explores it’s neighbors (level 1) and so on.
2. Time Complexity of Breadth First Search is? (V – number
of vertices, E – number of edges)
a) O(V + E)
b) O(V)
c) O(E)
d) O(V*E)
View Answer
Answer: a
Explanation: The Breadth First Search explores every node
once and every edge once (in worst case), so it’s time
complexity is O(V + E).
3. The Data structure used in standard implementation of
Breadth First Search is?
a) Stack
b) Queue
c) Linked List
d) Tree
View Answer
Page 156 of 295
Answer: b
Explanation: The Breadth First Search explores every node
once and put that node in queue and then it takes out
nodes from the queue and explores it’s neighbors.
advertisement
4. The Breadth First Search traversal of a graph will result
into?
a) Linked List
b) Tree
c) Graph with back edges
d) Arrays
View Answer
Answer: b
Explanation: The Breadth First Search will make a graph
which don’t have back edges (a tree) which is known as
Breadth First Tree.
5. A person wants to visit some places. He starts from a
vertex and then wants to visit every place connected to this
vertex and so on. What algorithm he should use?
a) Depth First Search
b) Breadth First Search
c) Trim’s algorithm
Page 157 of 295
d) Kruskal’s algorithm
View Answer
Answer: b
Explanation: This is the definition of the Breadth First
Search. Exploring a node, then it’s neighbors and so on.
Sanfoundry Certification Contest of the Month is Live. 100+
Subjects. Participate Now!
6. Which of the following is not an application of Breadth
First Search?
a) Finding shortest path between two nodes
b) Finding bipartiteness of a graph
c) GPS navigation system
d) Path Finding
View Answer
Answer: d
Explanation: Breadth First Search can be applied to Bipartite
a graph, to find the shortest path between two nodes, in
GPS Navigation. In Path finding, Depth First Search is used.
7. When the Breadth First Search of a graph is unique?
a) When the graph is a Binary Tree
b) When the graph is a Linked List
c) When the graph is a n-ary Tree
Page 158 of 295
d) When the graph is a Ternary Tree
View Answer
Answer: b
Explanation: When Every node will have one successor then
the Breadth First Search is unique. In all other cases, when it
will have more than one successor, it can choose any of
them in arbitrary order.
8. Regarding implementation of Breadth First Search using
queues, what is the maximum distance between two nodes
present in the queue? (considering each edge length 1)
a) Can be anything
b) 0
c) At most 1
d) Insufficient Information
View Answer
Answer: c
Explanation: In the queue, at a time, only those nodes will
be there whose difference among levels is 1. Same as level
order traversal of the tree.
9. In BFS, how many times a node is visited?
a) Once
b) Twice
Page 159 of 295
c) Equivalent to number of indegree of the node
d) Thrice
View Answer
Answer: c
Explanation: In Breadth First Search, we have to see
whether the node is visited or not by it’s ancestor. If it is
visited, we won’t let it enter it in the queue.
Best First Search Multiple Choice Questions and Answers
(MCQs)
This set of Data Structures & Algorithms Multiple Choice
Questions & Answers (MCQs) focuses on “Best First Search”.
1. Is Best First Search a searching algorithm used in graphs.
a) True
b) False
View Answer
Answer: a
Explanation: Best First Search is a searching algorithm used
in graphs. It explores it by choosing a node by heuristic
evaluation rule. It is used in solving searching for related
problems.
2. Who described this Best First Search algorithm using
heuristic evaluation rule?
Page 160 of 295
a) Judea Pearl
b) Max Bezzel
c) Franz Nauck
d) Alan Turing
View Answer
Answer: a
Explanation: The best first search algorithm using heuristic
evaluation rule or function was proposed by an Israeli –
American computer scientist and philosopher Judea Pearl.
3. Which type of best first search algorithm was used to
predict the closeness of the end of path and its solution?
a) Greedy BFS
b) Divide and Conquer
c) Heuristic BFS
d) Combinatorial
View Answer
Answer: a
Explanation: The greedy best first search algorithm was used
to predict the closeness of the end of the path and its
solution by some of the computer scientists.
advertisement
Page 161 of 295
4. What is the other name of the greedy best first search?
a) Heuristic Search
b) Pure Heuristic Search
c) Combinatorial Search
d) Divide and Conquer Search
View Answer
Answer: b
Explanation: The greedy best first search algorithm was used
to predict the closeness of the end of the path and its
solution by some of the computer scientists. It is also known
as Pure Heuristic Search.
5. Which algorithm is used in graph traversal and path
finding?
a) A*
b) C*
c) D*
d) E*
View Answer
Answer: a
Explanation: In computer science A* algorithm is used in
graph traversal and path finding. It is a process of node
finding in between a path. It is an example of the best first
search.
Page 162 of 295
Subscribe Now: Design and Analysis of Algorithms
Newsletter | Important Subjects Newsletters
6. Which algorithm is used to find the least cost path from
source node to destination node?
a) A* BFS
b) C* BFS
c) D* BFS
d) B* BFS
View Answer
Answer: d
Explanation: In computer science, B* algorithm is used to
find the least cost path between the source node and the
destination node. It is an example of the best first search.
7. Which of the following is an example of Best First Search
algorithm?
a) A*
b) B*
c) C*
d) Both A* and B*
View Answer
Answer: d
Explanation: In computer science, A* algorithm is used in
Page 163 of 295
graph traversal and path finding. It is a process of node
finding in between a path. B* algorithm is used to find the
least cost path between the source node and the
destination node.
8. Which of the following is the greedy best first search?
a) Pure Heuristic Search
b) A*
c) B*
d) Both A* and B*
View Answer
Answer: a
Explanation: Pure Heuristic Search is also called greedy best
first search while A* and B* search algorithms are not
greedy best first search.
9. Which of the following scientists didn’t publish A*
algorithm?
a) Peter Hart
b) Nils Nilsson
c) Bertram Raphael
d) Hans Berliner
View Answer
Page 164 of 295
Answer: d
Explanation: Peter Hart Nils Nilsson Bertram Raphael are the
three scientists of SRI International who first published the
A* search algorithm which uses heuristics for better
performance. Hans Berliner published B* algorithm.
10. Who published the B* search algorithm?
a) Peter Hart
b) Nils Nilsson
c) Bertram Raphael
d) Hans Berliner
View Answer
Answer: d
Explanation: Hans Berliner was a Computer Science
professor who first published the B* search algorithm in
1979. While Peter Hart Nils Nilsson Bertram Raphael are the
three scientists of SRI International who first published the
A* search algorithm which uses heuristics for better
performance.
Minimum Spanning Tree Multiple Choice Questions and
Answers (MCQs)
Page 165 of 295
This set of Data Structures & Algorithms Multiple Choice
Questions & Answers (MCQs) focuses on “Minimum
Spanning Tree”.
1. Which of the following is false in the case of a spanning
tree of a graph G?
a) It is tree that spans G
b) It is a subgraph of the G
c) It includes every vertex of the G
d) It can be either cyclic or acyclic
View Answer
Answer: d
Explanation: A graph can have many spanning trees. Each
spanning tree of a graph G is a subgraph of the graph G, and
spanning trees include every vertex of the gram. Spanning
trees are always acyclic.
2. Every graph has only one minimum spanning tree.
a) True
b) False
View Answer
Answer: b
Explanation: Minimum spanning tree is a spanning tree with
the lowest cost among all the spacing trees. Sum of all of
Page 166 of 295
the edges in the spanning tree is the cost of the spanning
tree. There can be many minimum spanning trees for a
given graph.
3. Consider a complete graph G with 4 vertices. The graph G
has ____ spanning trees.
a) 15
b) 8
c) 16
d) 13
View Answer
Answer: c
Explanation: A graph can have many spanning trees. And a
complete graph with n vertices has n(n-2) spanning trees. So,
the complete graph with 4 vertices has 4(4-2) = 16 spanning
trees.
advertisement
4. The travelling salesman problem can be solved using
_________
a) A spanning tree
b) A minimum spanning tree
c) Bellman – Ford algorithm
Page 167 of 295
d) DFS traversal
View Answer
Answer: b
Explanation: In the travelling salesman problem we have to
find the shortest possible route that visits every city exactly
once and returns to the starting point for the given a set of
cities. So, travelling salesman problem can be solved by
contracting the minimum spanning tree.
5. Consider the graph M with 3 vertices. Its adjacency matrix
is shown below. Which of the following is true?
a) Graph M has no minimum spanning tree
b) Graph M has a unique minimum spanning trees of cost 2
c) Graph M has 3 distinct minimum spanning trees, each of
cost 2
d) Graph M has 3 spanning trees of different costs
View Answer
Answer: c
Explanation: Here all non-diagonal elements in the
adjacency matrix are 1. So, every vertex is connected every
other vertex of the graph. And, so graph M has 3 distinct
Page 168 of 295
minimum spanning trees.
Sanfoundry Certification Contest of the Month is Live. 100+
Subjects. Participate Now!
6. Consider a undirected graph G with vertices { A, B, C, D,
E}. In graph G, every edge has distinct weight. Edge CD is
edge with minimum weight and edge AB is edge with
maximum weight. Then, which of the following is false?
a) Every minimum spanning tree of G must contain CD
b) If AB is in a minimum spanning tree, then its removal
must disconnect G
c) No minimum spanning tree contains AB
d) G has a unique minimum spanning tree
View Answer
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.
Page 169 of 295
7. If all the weights of the graph are positive, then the
minimum spanning tree of the graph is a minimum cost
subgraph.
a) True
b) False
View Answer
Answer: a
Explanation: A subgraph is a graph formed from a subset of
the vertices and edges of the original graph. And the subset
of vertices includes all endpoints of the subset of the edges.
So, we can say MST of a graph is a subgraph when all
weights in the original graph are positive.
8. Consider the graph shown below. Which of the following
are the edges in the MST of the given graph?
a) (a-c)(c-d)(d-b)(d-b)
b) (c-a)(a-d)(d-b)(d-e)
c) (a-d)(d-c)(d-b)(d-e)
Page 170 of 295
d) (c-a)(a-d)(d-c)(d-b)(d-e)
View Answer
Answer: c
Explanation: The minimum spanning tree of the given graph
is shown below. It has cost 56.
9. Which of the following is not the algorithm to find the
minimum spanning tree of the given graph?
a) Boruvka’s algorithm
b) Prim’s algorithm
c) Kruskal’s algorithm
d) Bellman–Ford algorithm
View Answer
Answer: d
Explanation: The Boruvka’s algorithm, Prim’s algorithm and
Kruskal’s algorithm are the algorithms that can be used to
find the minimum spanning tree of the given graph.
The Bellman-Ford algorithm is used to find the shortest path
from the single source to all other vertices.
Page 171 of 295
10. Which of the following is false?
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
View Answer
Answer: d
Explanation: Every spanning tree has n – 1 edges if the
graph has n edges and has no cycles. The MST follows the
cut property, 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.
hortest Paths Multiple Choice Questions (MCQ)
This set of Data Structure Multiple Choice Questions &
Answers (MCQs) focuses on “Shortest Paths”.
1. Which is the correct technique for finding a maximum
matching in a graph?
a) BFS traversal
b) DFS traversal
Page 172 of 295
c) Shortest path traversal
d) Heap order traversal
View Answer
Answer: a
Explanation: The correct technique for finding a maximum
matching in a bipartite graph is by using a Breadth First
Search(BFS).
2. What is the running time of an unweighted shortest path
algorithm whose augmenting path is the path with the least
number of edges?
a) O(|E||V|)
b) O(|E|)
c) O(|E| log |V|)
d) O(|E|2|V|)
View Answer
Answer: d
Explanation: Each augmenting step takes O(|E|) using an
unweighted shortest path algorithm yielding a O(|E|2|V|)
bound on the running time.
3. Floyd Warshall Algorithm can be used for finding
_____________
a) Transitive closure
Page 173 of 295
b) Minimum spanning tree
c) Topological sort
d) Single source shortest path
View Answer
Answer: a
Explanation: One of the ways to compute the transitive
closure of a graph in Theta(N3) time is to assign a weight of 1
to each edge of E and then run the Floyd Warshall
Algorithm.
advertisement
4. Bellmann ford algorithm provides solution for
____________ problems.
a) Network flow
b) Single source shortest path
c) All pair shortest path
d) Sorting
View Answer
Answer: b
Explanation: Bellmann ford algorithm is used for finding
solutions for single source shortest path problems. If the
graph has no negative cycles that are reachable from the
Page 174 of 295
source then the algorithm produces the shortest paths and
their weights.
5. What is the pseudo code to compute the shortest path in
Dijkstra’s algorithm?
a)
if(T[w].Known)
if(T[v].Dist + C(v,w) < T[w].Dist) {
Increase (T[w].Dist to T[v].Dist +C(v,w));
T[w].path=v; }
b)
if(!T[w].Known)
if(T[v].Dist + C(v,w) > T[w].Dist) {
Decrease(T[w].Dist to T[v].Dist +C(v,w);
T[w].path=v; }
c)
if(!T[w].Known)
if(T[v].Dist + C(v,w) < T[w].Dist) {
Decrease(T[w].Dist to T[v].Dist +C(v,w));
T[w].path=v; }
Page 175 of 295
d)
if(T[w].Known)
if(T[v].Dist + C(v,w) < T[w].Dist) {
Increase(T[w].Dist to T[v].Dist);
T[w].path=v; }
View Answer
Answer: c
Explanation: If the known value of the adjacent vertex(w) is
not set then check whether the sum of distance from source
vertex(v) and cost to travel from source to adjacent vertex is
less than the existing distance of the adjacent node. If so,
perform decrease key operation.
6. Dijkstra’s Algorithm is used to solve _____________
problems.
a) Single source shortest path
b) All pair shortest path
c) Sorting
d) Network flow
View Answer
Page 176 of 295
Answer: a
Explanation: Dijkstra’s Algorithm is used for solving single
source shortest path problems. In this algorithm, a single
node is fixed as a source node and shortest paths from this
node to all other nodes in graph is found.
7. What approach is being followed in Floyd Warshall
Algorithm?
a) Linear Programming
b) Backtracking
c) Greedy technique
d) Dynamic Programming
View Answer
Answer: d
Explanation: Floyd Warshall Algorithm follows dynamic
programming approach because the all pair shortest paths
are computed in bottom up manner.
8. Which of the following is not an application of Breadth
First Search?
a) Path Finding
b) Finding bipartiteness of a graph
c) GPS navigation system
d) Finding shortest path between two nodes
View Answer
Page 177 of 295
Answer: a
Explanation: Breadth First Search can be applied to Bipartite
a graph, to find the shortest path between two nodes, in
GPS Navigation. In Path finding, Depth First Search is used.
9. Chan’s algorithm is used for computing _________
a) Shortest path between two points
b) Area of a polygon
c) Convex hull
d) Closest distance between two points
View Answer
Answer: c
Explanation: Chan’s algorithm is an output-sensitive
algorithm used to compute the convex hull set of n points in
a 2D or 3D space. Closest pair algorithm is used to compute
the closest distance between two points.
Dijkstra’s Algorithm Multiple Choice Questions and
Answers (MCQs)
This set of Data Structures & Algorithms Multiple Choice
Questions & Answers (MCQs) focuses on “Dijkstra’s
Algorithm”.
1. Dijkstra’s Algorithm is used to solve _____________
problems.
Page 178 of 295
a) All pair shortest path
b) Single source shortest path
c) Network flow
d) Sorting
View Answer
Answer: b
Explanation: Dijkstra’s Algorithm is used for solving single
source shortest path problems. In this algorithm, a single
node is fixed as a source node and shortest paths from this
node to all other nodes in graph is found.
2. Which of the following is the most commonly used data
structure for implementing Dijkstra’s Algorithm?
a) Max priority queue
b) Stack
c) Circular queue
d) Min priority queue
View Answer
Answer: d
Explanation: Minimum priority queue is the most commonly
used data structure for implementing Dijkstra’s Algorithm
because the required operations to be performed in
Dijkstra’s Algorithm match with specialty of a minimum
priority queue.
Page 179 of 295
3. What is the time complexity of Dijikstra’s algorithm?
a) O(N)
b) O(N3)
c) O(N2)
d) O(logN)
View Answer
Answer: c
Explanation: Time complexity of Dijkstra’s algorithm is O(N2)
because of the use of doubly nested for loops. It depends on
how the table is manipulated.
advertisement
4. Dijkstra’s Algorithm cannot be applied on
______________
a) Directed and weighted graphs
b) Graphs having negative weight function
c) Unweighted graphs
d) Undirected and unweighted graphs
View Answer
Answer: b
Explanation: Dijkstra’s Algorithm cannot be applied on
graphs having negative weight function because calculation
Page 180 of 295
of cost to reach a destination node from the source node
becomes complex.
5. What is the pseudo code to compute the shortest path in
Dijkstra’s algorithm?
a)
Note: Join free Sanfoundry classes at Telegram or Youtube
if(!T[w].Known)
if(T[v].Dist + C(v,w) < T[w].Dist) {
Decrease(T[w].Dist to T[v].Dist +C(v,w));
T[w].path=v; }
b)
if(T[w].Known)
if(T[v].Dist + C(v,w) < T[w].Dist) {
Increase (T[w].Dist to T[v].Dist +C(v,w));
T[w].path=v; }
c)
if(!T[w].Known)
if(T[v].Dist + C(v,w) > T[w].Dist) {
Decrease(T[w].Dist to T[v].Dist +C(v,w);
Page 181 of 295
T[w].path=v; }
d)
if(T[w].Known)
if(T[v].Dist + C(v,w) < T[w].Dist) {
Increase(T[w].Dist to T[v].Dist);
T[w].path=v; }
View Answer
Answer: a
Explanation: If the known value of the adjacent vertex(w) is
not set then check whether the sum of distance from source
vertex(v) and cost to travel from source to adjacent vertex is
less than the existing distance of the adjacent node. If so,
perform decrease key operation.
6. How many priority queue operations are involved in
Dijkstra’s Algorithm?
a) 1
b) 3
c) 2
Page 182 of 295
d) 4
View Answer
Answer: b
Explanation: The number of priority queue operations
involved is 3. They are insert, extract-min and decrease key.
7. How many times the insert and extract min operations
are invoked per vertex?
a) 1
b) 2
c) 3
d) 0
View Answer
Answer: a
Explanation: Insert and extract min operations are invoked
only once per vertex because each vertex is added only once
to the set and each edge in the adjacency list is examined
only once during the course of algorithm.
8. The maximum number of times the decrease key
operation performed in Dijkstra’s algorithm will be equal to
___________
a) Total number of vertices
b) Total number of edges
Page 183 of 295
c) Number of vertices – 1
d) Number of edges – 1
View Answer
Answer: b
Explanation: If the total number of edges in all adjacency list
is E, then there will be a total of E number of iterations,
hence there will be a total of at most E decrease key
operations.
9. What is running time of Dijkstra’s algorithm using Binary
min- heap method?
a) O(V)
b) O(VlogV)
c) O(E)
d) O(ElogV)
View Answer
Answer: d
Explanation: Time required to build a binary min heap is
O(V). Each decrease key operation takes O(logV) and there
are still at most E such operations. Hence total running time
is O(ElogV).
10. The running time of Bellmann Ford algorithm is lower
than that of Dijkstra’s Algorithm.
Page 184 of 295
a) True
b) False
View Answer
Answer: b
Explanation: The number of iterations involved in Bellmann
Ford Algorithm is more than that of Dijkstra’s Algorithm.
11. Dijkstra’s Algorithm run on a weighted, directed graph
G={V,E} with non-negative weight function w and source s,
terminates with d[u]=delta(s,u) for all vertices u in V.
a) True
b) False
View Answer
Answer: a
Explanation: The equality d[u]=delta(s,u) holds good when
vertex u is added to set S and this equality is maintained
thereafter by the upper bound property.
12. Given pseudo code of Dijkstra’s Algorithm.
//Initialise single source(G,s)
S=0
Q=V[G]
While Q != 0
Page 185 of 295
Do u=extract-min(Q)
S=S union {u}
For each vertex v in adj[u]
Do relax(u,v,w)
What happens when “While Q != 0” is changed to “while
Q>1”?
a) While loop gets executed for v times
b) While loop gets executed for v-1 times
c) While loop gets executed only once
d) While loop does not get executed
View Answer
Answer: b
Explanation: In the normal execution of Dijkstra’s Algorithm,
the while loop gets executed V times. The change in the
while loop statement causes it to execute only V – 1 times.
13. Consider the following graph.
If b is the source vertex, what is the minimum cost to reach f
Page 186 of 295
vertex?
a) 8
b) 9
c) 4
d) 6
View Answer
Answer: d
Explanation: The minimum cost to reach f vertex from b
vertex is 6 by having vertices g and e as intermediates.
b to g, cost is 1
g to e, cost is 4
e to f, cost is 1
hence total cost 1+4+1=6.
14. In the given graph, identify the shortest path having
minimum cost to reach vertex E if A is the source vertex.
a) a-b-e
b) a-c-e
c) a-c-d-e
Page 187 of 295
d) a-c-d-b-e
View Answer
Answer: b
Explanation: The minimum cost required to travel from
vertex A to E is via vertex C
A to C, cost= 3
C to E, cost= 2
Hence the total cost is 5.
15. Dijkstra’s Algorithm is the prime example for
___________
a) Greedy algorithm
b) Branch and bound
c) Back tracking
d) Dynamic programming
View Answer
Answer: a
Explanation: Dijkstra’s Algorithm is the prime example for
greedy algorithms because greedy algorithms generally
solve a problem in stages by doing what appears to be the
best thing at each stage.
Bellman-Ford Algorithm Multiple Choice Questions and
Answers (MCQs)
Page 188 of 295
This set of Data Structures & Algorithms Multiple Choice
Questions & Answers (MCQs) focuses on “Bellman-Ford
Algorithm”.
1. The Bellmann Ford algorithm returns _______ value.
a) Boolean
b) Integer
c) String
d) Double
View Answer
Answer: a
Explanation: The Bellmann Ford algorithm returns Boolean
value whether there is a negative weight cycle that is
reachable from the source.
2. Bellmann ford algorithm provides solution for
____________ problems.
a) All pair shortest path
b) Sorting
c) Network flow
d) Single source shortest path
View Answer
Answer: d
Explanation: Bellmann ford algorithm is used for finding
Page 189 of 295
solutions for single source 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.
3. Bellmann Ford algorithm is used to indicate whether the
graph has negative weight cycles or not.
a) True
b) False
View Answer
Answer: a
Explanation: Bellmann Ford algorithm returns true if the
graph does not have any negative weight cycles and returns
false when the graph has negative weight cycles.
advertisement
4. How many solution/solutions are available for a graph
having negative weight cycle?
a) One solution
b) Two solutions
c) No solution
d) Infinite solutions
View Answer
Page 190 of 295
Answer: c
Explanation: If the graph has any negative weight cycle then
the algorithm indicates that no solution exists for that
graph.
5. What is the running time of Bellmann Ford Algorithm?
a) O(V)
b) O(V2)
c) O(ElogV)
d) O(VE)
View Answer
Answer: d
Explanation: Bellmann Ford algorithm runs in time O(VE),
since the initialization takes O(V) for each of V-1 passes and
the for loop in the algorithm takes O(E) time. Hence the
total time taken by the algorithm is O(VE).
Sanfoundry Certification Contest of the Month is Live. 100+
Subjects. Participate Now!
6. How many times the for loop in the Bellmann Ford
Algorithm gets executed?
a) V times
b) V-1
c) E
Page 191 of 295
d) E-1
View Answer
Answer: b
Explanation: The for loop in the Bellmann Ford Algorithm
gets executed for V-1 times. After making V-1 passes, the
algorithm checks for a negative weight cycle and returns
appropriate boolean value.
7. Dijikstra’s Algorithm is more efficient than Bellmann Ford
Algorithm.
a) True
b) False
View Answer
Answer: a
Explanation: The running time of Bellmann Ford Algorithm is
O(VE) whereas Dijikstra’s Algorithm has running time of only
O(V2).
8. Identify the correct Bellmann Ford Algorithm.
a)
for i=1 to V[g]-1
do for each edge (u,v) in E[g]
do Relax(u,v,w)
Page 192 of 295
for each edge (u,v) in E[g]
do if d[v]>d[u]+w(u,v)
then return False
return True
b)
for i=1 to V[g]-1
for each edge (u,v) in E[g]
do if d[v]>d[u]+w(u,v)
then return False
return True
c)
for i=1 to V[g]-1
do for each edge (u,v) in E[g]
do Relax(u,v,w)
for each edge (u,v) in E[g]
do if d[v]<d[u]+w(u,v)
then return true
return True
d)
Page 193 of 295
for i=1 to V[g]-1
do for each edge (u,v) in E[g]
do Relax(u,v,w)
return True
View Answer
Answer: a
Explanation: After initialization, the algorithm makes v-1
passes over the edges of the graph. Each pass is one
iteration of the for loop and consists of relaxing each edge
of the graph once. Then it checks for the negative weight
cycle and returns an appropriate Boolean value.
9. What is the basic principle behind Bellmann Ford
Algorithm?
a) Interpolation
b) Extrapolation
c) Regression
d) Relaxation
View Answer
Page 194 of 295
Answer: d
Explanation: Relaxation methods which are also called as
iterative methods in which an approximation to the correct
distance is replaced progressively by more accurate values
till an optimum solution is found.
10. Bellmann Ford Algorithm can be applied for
_____________
a) Undirected and weighted graphs
b) Undirected and unweighted graphs
c) Directed and weighted graphs
d) All directed graphs
View Answer
Answer: c
Explanation: Bellmann Ford Algorithm can be applied for all
directed and weighted graphs. The weight function in the
graph may either be positive or negative.
11. Bellmann Ford algorithm was first proposed by
________
a) Richard Bellmann
b) Alfonso Shimbe
c) Lester Ford Jr
d) Edward F. Moore
View Answer
Page 195 of 295
Answer: b
Explanation: Alfonso Shimbe proposed Bellmann Ford
algorithm in the year 1955. Later it was published by
Richard Bellmann in 1957 and Lester Ford Jr in the year
1956. Hence it is called Bellmann Ford Algorithm.
12. Consider the following graph. What is the minimum cost
to travel from node A to node C?
a) 5
b) 2
c) 1
d) 3
View Answer
Answer: b
Explanation: The minimum cost to travel from node A to
node C is 2.
A-D, cost=1
D-B, cost=-2
Page 196 of 295
B-C, cost=3
Hence the total cost is 2.
13. In the given graph, identify the path that has minimum
cost to travel from node a to node f.
a) a-b-c-f
b) a-d-e-f
c) a-d-b-c-f
d) a-d-b-c-e-f
View Answer
Answer: d
Explanation: The minimum cost taken by the path a-d-b-c-e-
f is 4.
a-d, cost=2
d-b, cost=-2
b-c, cost=1
c-e, cost= 2
e-f, cost=1
Hence the total cost is 4.
Page 197 of 295
14. Bellmann Ford Algorithm is an example for
____________
a) Dynamic Programming
b) Greedy Algorithms
c) Linear Programming
d) Branch and Bound
View Answer
Answer: a
Explanation: In Bellmann Ford Algorithm the shortest paths
are calculated in bottom up manner which is similar to other
dynamic programming problems.
15. A graph is said to have a negative weight cycle when?
a) The graph has 1 negative weighted edge
b) The graph has a cycle
c) The total weight of the graph is negative
d) The graph has 1 or more negative weighted edges
View Answer
Answer: c
Explanation: When the total weight of the graph sums up to
a negative number then the graph is said to have a negative
weight cycle. Bellmann Ford Algorithm provides no solution
for such graphs.
Page 198 of 295
Floyd-Warshall Algorithm Multiple Choice Questions and
Answers (MCQs)
This set of Data Structures & Algorithms Multiple Choice
Questions & Answers (MCQs) focuses on “Floyd-Warshall
Algorithm”.
1. Floyd Warshall’s Algorithm is used for solving
____________
a) All pair shortest path problems
b) Single Source shortest path problems
c) Network flow problems
d) Sorting problems
View Answer
Answer: a
Explanation: Floyd Warshall’s Algorithm is used for solving
all pair shortest path problems. It means the algorithm is
used for finding the shortest paths between all pairs of
vertices in a graph.
2. Floyd Warshall’s Algorithm can be applied on __________
a) Undirected and unweighted graphs
b) Undirected graphs
c) Directed graphs
Page 199 of 295
d) Acyclic graphs
View Answer
Answer: c
Explanation: Floyd Warshall Algorithm can be applied in
directed graphs. From a given directed graph, an adjacency
matrix is framed and then all pair shortest path is computed
by the Floyd Warshall Algorithm.
3. What is the running time of the Floyd Warshall
Algorithm?
a) Big-oh(V)
b) Theta(V2)
c) Big-Oh(VE)
d) Theta(V3)
View Answer
Answer: d
Explanation: The running time of the Floyd Warshall
algorithm is determined by the triply nested for loops. Since
each execution of the for loop takes O(1) time, the
algorithm runs in time Theta(V3).
advertisement
4. What approach is being followed in Floyd Warshall
Algorithm?
Page 200 of 295
a) Greedy technique
b) Dynamic Programming
c) Linear Programming
d) Backtracking
View Answer
Answer: b
Explanation: Floyd Warshall Algorithm follows dynamic
programming approach because the all pair shortest paths
are computed in bottom up manner.
5. Floyd Warshall Algorithm can be used for finding
_____________
a) Single source shortest path
b) Topological sort
c) Minimum spanning tree
d) Transitive closure
View Answer
Answer: d
Explanation: One of the ways to compute the transitive
closure of a graph in Theta(N3) time is to assign a weight of 1
to each edge of E and then run the Floyd Warshall
Algorithm.
Page 201 of 295
Subscribe Now: Design and Analysis of Algorithms
Newsletter | Important Subjects Newsletters
6. What procedure is being followed in Floyd Warshall
Algorithm?
a) Top down
b) Bottom up
c) Big bang
d) Sandwich
View Answer
Answer: b
Explanation: Bottom up procedure is being used to compute
the values of the matrix elements dij(k). The input is an n x n
matrix. The procedure returns the matrix D(n) of the
shortest path weights.
7. Floyd- Warshall algorithm was proposed by
____________
a) Robert Floyd and Stephen Warshall
b) Stephen Floyd and Robert Warshall
c) Bernad Floyd and Robert Warshall
d) Robert Floyd and Bernad Warshall
View Answer
Page 202 of 295
8. Who proposed the modern formulation of Floyd-Warshall
Algorithm as three nested loops?
a) Robert Floyd
b) Stephen Warshall
c) Bernard Roy
d) Peter Ingerman
View Answer
Answer: d
Explanation: The modern formulation of Floyd-Warshall
Algorithm as three nested for-loops was proposed by Peter
Ingerman in the year 1962.
9. Complete the program.
n=rows[W]
D(0)=W
for k=1 to n
do for i=1 to n
do for j=1 to n
do ________________________________
return D(n)
a) dij(k)=min(dij(k-1), dik(k-1) – dkj(k-1))
b) dij(k)=max(dij(k-1), dik(k-1) – dkj(k-1))
Page 203 of 295
c) dij(k)=min(dij(k-1), dik(k-1) + dkj(k-1))
d) dij(k)=max(dij(k-1), dik(k-1) + dkj(k-1))
View Answer
Answer: c
Explanation: In order to compute the shortest path from
vertex i to vertex j, we need to find the minimum of 2 values
which are dij(k-1) and sum of dik(k-1) and dkj(k-1).
10. What happens when the value of k is 0 in the Floyd
Warshall Algorithm?
a) 1 intermediate vertex
b) 0 intermediate vertex
c) N intermediate vertices
d) N-1 intermediate vertices
View Answer
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 dij(0) = wij.
11. Using logical operator’s instead arithmetic operators
saves time and space.
a) True
Page 204 of 295
b) False
View Answer
Answer: a
Explanation: In computers, logical operations on single bit
values execute faster than arithmetic operations on integer
words of data.
12. The time taken to compute the transitive closure of a
graph is Theta(n2).
a) True
b) False
View Answer
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.
13. In the given graph, what is the minimum cost to travel
from vertex 1 to vertex 3?
Page 205 of 295
a) 3
b) 2
c) 10
d) -3
View Answer
Answer: d
Explanation: The minimum cost required to travel from
node 1 to node 5 is -3.
1-5, cost is -4
5-4, cost is 6
4-3, cost is -5
Hence total cost is -4 + 6 + -5 = -3.
14. In the given graph, how many intermediate vertices are
required to travel from node a to node e at a minimum
cost?
Page 206 of 295
a) 2
b) 0
c) 1
d) 3
View Answer
Answer: c
Explanation: The minimum cost to travel from node a to
node e is 1 by passing via nodes b and c.
a-b, cost 5
b-c, cost 3
c-e, cost -7
Hence the total cost is 1.
15. What is the formula to compute the transitive closure of
a graph?
a) tij(k) = tij(k-1) AND (tik(k-1) OR tkj(k-1))
b) tij(k) = tij(k-1) OR (tik(k-1) AND tkj(k-1))
c) tij(k) = tij(k-1) AND (tik(k-1) AND tkj(k-1))
Page 207 of 295
d) tij(k) = tij(k-1) OR (tik(k-1) OR tkj(k-1))
View Answer
Answer: b
Explanation: Transitive closure of a graph can be computed
by using Floyd Warshall algorithm. This method involves
substitution of logical operations (logical OR and logical
AND) for arithmetic operations min and + in Floyd Warshall
Algorithm.
Floyd Warshall Algorithm: dij(k)=min(dij(k-1), dik(k-1) +
dkj(k-1))
Transitive closure: tij(k)= tij(k-1) OR (tik(k-1) AND tkj(k-1)).
Data Structure Questions and Answers – Recursion
This set of Data Structure Multiple Choice Questions &
Answers (MCQs) focuses on “Recursion”.
1. Recursion is a method in which the solution of a problem
depends on ____________
a) Larger instances of different problems
b) Larger instances of the same problem
c) Smaller instances of the same problem
d) Smaller instances of different problems
View Answer
Page 208 of 295
Answer: c
Explanation: In recursion, the solution of a problem depends
on the solution of smaller instances of the same problem.
2. Which of the following problems can’t be solved using
recursion?
a) Factorial of a number
b) Nth fibonacci number
c) Length of a string
d) Problems without base case
View Answer
Answer: d
Explanation: Problems without base case leads to infinite
recursion call. In general, we will assume a base case to
avoid infinite recursion call. Problems like finding Factorial
of a number, Nth Fibonacci number and Length of a string
can be solved using recursion.
3. Recursion is similar to which of the following?
a) Switch Case
b) Loop
c) If-else
d) if elif else
View Answer
Page 209 of 295
Answer: b
Explanation: Recursion is similar to a loop.
advertisement
4. In recursion, the condition for which the function will stop
calling itself is ____________
a) Best case
b) Worst case
c) Base case
d) There is no such condition
View Answer
Answer: c
Explanation: For recursion to end at some point, there
always has to be a condition for which the function will not
call itself. This condition is known as base case.
5. What will happen when the below code snippet is
executed?
Subscribe Now: Design and Analysis of Algorithms
Newsletter | Important Subjects Newsletters
void my_recursive_function()
{
my_recursive_function();
Page 210 of 295
}
int main()
{
my_recursive_function();
return 0;
}
a) The code will be executed successfully and no output will
be generated
b) The code will be executed successfully and random
output will be generated
c) The code will show a compile time error
d) The code will run for some time and stop when the stack
overflows
View Answer
Answer: d
Explanation: Every function call is stored in the stack
memory. In this case, there is no terminating condition(base
case). So, my_recursive_function() will be called
continuously till the stack overflows and there is no more
space to store the function calls. At this point of time, the
program will stop abruptly.
Page 211 of 295
6. What is the output of the following code?
void my_recursive_function(int n)
{
if(n == 0)
return;
printf("%d ",n);
my_recursive_function(n-1);
}
int main()
{
my_recursive_function(10);
return 0;
}
a) 10
b) 1
c) 10 9 8 … 1 0
d) 10 9 8 … 1
View Answer
Answer: d
Explanation: The program prints the numbers from 10 to 1.
Page 212 of 295
7. What is the base case for the following code?
void my_recursive_function(int n)
{
if(n == 0)
return;
printf("%d ",n);
my_recursive_function(n-1);
}
int main()
{
my_recursive_function(10);
return 0;
}
a) return
b) printf(“%d “, n)
c) if(n == 0)
d) my_recursive_function(n-1)
View Answer
Page 213 of 295
Answer: c
Explanation: For the base case, the recursive function is not
called. So, “if(n == 0)” is the base case.
8. How many times is the recursive function called, when
the following code is executed?
void my_recursive_function(int n)
{
if(n == 0)
return;
printf("%d ",n);
my_recursive_function(n-1);
}
int main()
{
my_recursive_function(10);
return 0;
}
a) 9
b) 10
c) 11
Page 214 of 295
d) 12
View Answer
Answer: c
Explanation: The recursive function is called 11 times.
9. What does the following recursive code do?
void my_recursive_function(int n)
{
if(n == 0)
return;
my_recursive_function(n-1);
printf("%d ",n);
}
int main()
{
my_recursive_function(10);
return 0;
}
a) Prints the numbers from 10 to 1
b) Prints the numbers from 10 to 0
Page 215 of 295
c) Prints the numbers from 1 to 10
d) Prints the numbers from 0 to 10
View Answer
Answer: c
Explanation: The above code prints the numbers from 1 to
10.
10. Which of the following statements is true?
a) Recursion is always better than iteration
b) Recursion uses more memory compared to iteration
c) Recursion uses less memory compared to iteration
d) Iteration is always better and simpler than recursion
View Answer
Answer: b
Explanation: Recursion uses more memory compared to
iteration because every time the recursive function is called,
the function call is stored in stack.
11. What will be the output of the following code?
int cnt=0;
void my_recursive_function(int n)
{
if(n == 0)
Page 216 of 295
return;
cnt++;
my_recursive_function(n/10);
}
int main()
{
my_recursive_function(123456789);
printf("%d",cnt);
return 0;
}
a) 123456789
b) 10
c) 0
d) 9
View Answer
Answer: d
Explanation: The program prints the number of digits in the
number 123456789, which is 9.
12. What will be the output of the following code?
void my_recursive_function(int n)
Page 217 of 295
{
if(n == 0)
{
printf("False");
return;
}
if(n == 1)
{
printf("True");
return;
}
if(n%2==0)
my_recursive_function(n/2);
else
{
printf("False");
return;
}
Page 218 of 295
}
int main()
{
my_recursive_function(100);
return 0;
}
a) True
b) False
View Answer
Answer: b
Explanation: The function checks if a number is a power of
2. Since 100 is not a power of 2, it prints false.
13. What is the output of the following code?
int cnt = 0;
void my_recursive_function(char *s, int i)
{
if(s[i] == '\0')
return;
if(s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] ==
'u')
Page 219 of 295
cnt++;
my_recursive_function(s,i+1);
}
int main()
{
my_recursive_function("thisisrecursion",0);
printf("%d",cnt);
return 0;
}
a) 6
b) 9
c) 5
d) 10
View Answer
Answer: a
Explanation: The function counts the number of vowels in a
string. In this case the number is vowels is 6.
14. What is the output of the following code?
void my_recursive_function(int *arr, int val, int idx, int len)
{
Page 220 of 295
if(idx == len)
{
printf("-1");
return ;
}
if(arr[idx] == val)
{
printf("%d",idx);
return;
}
my_recursive_function(arr,val,idx+1,len);
}
int main()
{
int array[10] = {7, 6, 4, 3, 2, 1, 9, 5, 0, 8};
int value = 2;
int len = 10;
my_recursive_function(array, value, 0, len);
return 0;
Page 221 of 295
}
a) 3
b) 4
c) 5
d) 6
View Answer
Answer: b
Explanation: The program searches for a value in the given
array and prints the index at which the value is found. In this
case, the program searches for value = 2. Since, the index of
2 is 4(0 based indexing), the program prints 4.
Greedy Algorithms Multiple Choice Questions (MCQ)
This set of Data Structure Multiple Choice Questions &
Answers (MCQs) focuses on “Greedy Algorithms”.
1. The first step in the naïve greedy algorithm is?
a) adding flows with higher values
b) reversing flow if required
c) analysing the zero flow
d) calculating the maximum flow using trial and error
View Answer
Answer: c
Explanation: The first step in the naïve greedy algorithm is
Page 222 of 295
to start with the zero flow followed by adding edges with
higher values.
2. Suppose you have coins of denominations 1,3 and 4. You
use a greedy algorithm, in which you choose the largest
denomination coin which is not greater than the remaining
sum. For which of the following sums, will the algorithm
produce an optimal answer?
a) 100
b) 10
c) 6
d) 14
View Answer
Answer: a
Explanation: Using the greedy algorithm, three coins {4,1,1}
will be selected to make a sum of 6. But, the optimal answer
is two coins {3,3}. Similarly, four coins {4,4,1,1} will be
selected to make a sum of 10. But, the optimal answer is
three coins {4,3,3}. Also, five coins {4,4,4,1,1} will be
selected to make a sum of 14. But, the optimal answer is
four coins {4,4,3,3}. For a sum of 100, twenty-five coins {all
4’s} will be selected and the optimal answer is also twenty-
five coins {all 4’s}.
Page 223 of 295
3. Choose the correct statement from the following.
a) branch and bound is not suitable where a greedy
algorithm is not applicable
b) branch and bound divides a problem into at least 2 new
restricted sub problems
c) backtracking divides a problem into at least 2 new
restricted sub problems
d) branch and bound is more efficient than backtracking
View Answer
Answer: b
Explanation: Both backtracking as well as branch and bound
are problem solving algorithms. Branch and bound is less
efficient than backtracking. Branch and bound divides a
problem into at least 2 new restricted sub problems.
advertisement
4. Dijkstra’s Algorithm is the prime example for
___________
a) Dynamic programming
b) Back tracking
c) Branch and bound
d) Greedy algorithm
View Answer
Page 224 of 295
Answer: d
Explanation: Dijkstra’s Algorithm is the prime example for
greedy algorithms because greedy algorithms generally
solve a problem in stages by doing what appears to be the
best thing at each stage.
5. Bellmann Ford Algorithm is an example for ____________
a) Linear Programming
b) Greedy Algorithms
c) Dynamic Programming
d) Branch and Bound
View Answer
Answer: c
Explanation: In Bellmann Ford Algorithm the shortest paths
are calculated in bottom up manner which is similar to other
dynamic programming problems.
6. Which of the following algorithms is the best approach
for solving Huffman codes?
a) greedy algorithm
b) exhaustive search
c) divide and conquer algorithm
d) brute force algorithm
View Answer
Page 225 of 295
Answer: a
Explanation: Greedy algorithm is the best approach for
solving the Huffman codes problem since it greedily
searches for an optimal solution.
7. Fractional knapsack problem is solved most efficiently by
which of the following algorithm?
a) Backtracking
b) Greedy algorithm
c) Dynamic programming
d) Divide and conquer
View Answer
Answer: b
Explanation: Greedy algorithm is used to solve this problem.
We first sort items according to their value/weight ratio and
then add item with highest ratio until we cannot add the
next item as a whole. At the end, we add the next item as
much as we can.
8. Which of the following is false about the Kruskal’s
algorithm?
a) It constructs MST by selecting edges in increasing order of
their weights
b) It is a greedy algorithm
c) It uses union-find data structure
Page 226 of 295
d) It can accept cycles in the MST
View Answer
Answer: d
Explanation: Kruskal’s algorithm is a greedy algorithm to
construct the MST of the given graph. It constructs the MST
by selecting edges in increasing order of their weights and
rejects an edge if it may form the cycle. So, using Kruskal’s
algorithm is never formed.
Fractional Knapsack Problem Multiple Choice Questions
and Answers (MCQs)
This set of Data Structures & Algorithms Multiple Choice
Questions & Answers (MCQs) focuses on “Fractional
Knapsack Problem”.
1. Fractional knapsack problem is also known as
__________
a) 0/1 knapsack problem
b) Continuous knapsack problem
c) Divisible knapsack problem
d) Non continuous knapsack problem
View Answer
Answer: b
Explanation: Fractional knapsack problem is also called
Page 227 of 295
continuous knapsack problem. Fractional knapsack is solved
using dynamic programming.
2. Fractional knapsack problem is solved most efficiently by
which of the following algorithm?
a) Divide and conquer
b) Dynamic programming
c) Greedy algorithm
d) Backtracking
View Answer
Answer: c
Explanation: Greedy algorithm is used to solve this problem.
We first sort items according to their value/weight ratio and
then add item with highest ratio until we cannot add the
next item as a whole. At the end, we add the next item as
much as we can.
3. What is the objective of the knapsack problem?
a) To get maximum total value in the knapsack
b) To get minimum total value in the knapsack
c) To get maximum weight in the knapsack
d) To get minimum weight in the knapsack
View Answer
Page 228 of 295
Answer: a
Explanation: The objective is to fill the knapsack of some
given volume with different materials such that the value of
selected items is maximized.
advertisement
4. Which of the following statement about 0/1 knapsack and
fractional knapsack problem is correct?
a) In 0/1 knapsack problem items are divisible and in
fractional knapsack items are indivisible
b) Both are the same
c) 0/1 knapsack is solved using a greedy algorithm and
fractional knapsack is solved using dynamic programming
d) In 0/1 knapsack problem items are indivisible and in
fractional knapsack items are divisible
View Answer
Answer: d
Explanation: In fractional knapsack problem we can partially
include an item into the knapsack whereas in 0/1 knapsack
we have to either include or exclude the item wholly.
5. Time complexity of fractional knapsack problem is
____________
a) O(n log n)
Page 229 of 295
b) O(n)
c) O(n2)
d) O(nW)
View Answer
Answer: a
Explanation: As the main time taking a step is of sorting so it
defines the time complexity of our code. So the time
complexity will be O(n log n) if we use quick sort for sorting.
Subscribe Now: Design and Analysis of Algorithms
Newsletter | Important Subjects Newsletters
6. Fractional knapsack problem can be solved in time O(n).
a) True
b) False
View Answer
Answer: a
Explanation: It is possible to solve the problem in O(n) time
by adapting the algorithm for finding weighted medians.
7. Given items as {value,weight} pairs
{{40,20},{30,10},{20,5}}. The capacity of knapsack=20. Find
the maximum value output assuming items to be divisible.
a) 60
b) 80
Page 230 of 295
c) 100
d) 40
View Answer
Answer: a
Explanation: The value/weight ratio are-{2,3,4}. So we
include the second and third items wholly into the
knapsack. This leaves only 5 units of volume for the first
item. So we include the first item partially.
Final value = 20+30+(40/4)=60.
8. The result of the fractional knapsack is greater than or
equal to 0/1 knapsack.
a) True
b) False
View Answer
Answer: a
Explanation: As fractional knapsack gives extra liberty to
include the object partially which is not possible with 0/1
knapsack, thus we get better results with a fractional
knapsack.
9. The main time taking step in fractional knapsack problem
is ___________
a) Breaking items into fraction
Page 231 of 295
b) Adding items into knapsack
c) Sorting
d) Looping through sorted items
View Answer
Answer: c
Explanation: The main time taking step is to sort the items
according to their value/weight ratio. It defines the time
complexity of the code.
10. Given items as {value,weight} pairs
{{60,20},{50,25},{20,5}}. The capacity of knapsack=40. Find
the maximum value output assuming items to be divisible
and nondivisible respectively.
a) 100, 80
b) 110, 70
c) 130, 110
d) 110, 80
View Answer
Answer: d
Explanation: Assuming items to be divisible-
The value/weight ratio are {3, 2, 4}.So we include third and
first items wholly. So, now only 15 units of volume are left
for second item. So we include it partially.
Final volume = 20+60+50x(15/25)=80+30=110
Page 232 of 295
Assuming items to be indivisible- In this case we will have to
leave one item due to insufficient capacity.
Final volume = 60 + 20 = 80.
Huffman Code Multiple Choice Questions and Answers
(MCQs)
This set of Data Structures & Algorithms Multiple Choice
Questions & Answers (MCQs) focuses on “Huffman Code”.
1. Which of the following algorithms is the best approach
for solving Huffman codes?
a) exhaustive search
b) greedy algorithm
c) brute force algorithm
d) divide and conquer algorithm
View Answer
Answer: b
Explanation: Greedy algorithm is the best approach for
solving the Huffman codes problem since it greedily
searches for an optimal solution.
2. How many printable characters does the ASCII character
set consists of?
a) 120
b) 128
Page 233 of 295
c) 100
d) 98
View Answer
Answer: c
Explanation: Out of 128 characters in an ASCII set, roughly,
only 100 characters are printable while the rest are non-
printable.
3. Which bit is reserved as a parity bit in an ASCII set?
a) first
b) seventh
c) eighth
d) tenth
View Answer
Answer: c
Explanation: In an ASCII character set, seven bits are
reserved for character representation while the eighth bit is
a parity bit.
advertisement
4. How many bits are needed for standard encoding if the
size of the character set is X?
a) log X
b) X+1
Page 234 of 295
c) 2X
d) X2
View Answer
Answer: a
Explanation: If the size of the character set is X, then [log X]
bits are needed for representation in a standard encoding.
5. The code length does not depend on the frequency of
occurrence of characters.
a) true
b) false
View Answer
Answer: b
Explanation: The code length depends on the frequency of
occurrence of characters. The more frequent the character
occurs, the less is the length of the code.
Note: Join free Sanfoundry classes at Telegram or Youtube
6. In Huffman coding, data in a tree always occur?
a) roots
b) leaves
c) left sub trees
d) right sub trees
View Answer
Page 235 of 295
Answer: b
Explanation: In Huffman encoding, data is always stored at
the leaves of a tree inorder to compute the codeword
effectively.
7. From the following given tree, what is the code word for
the character ‘a’?
a) 011
b) 010
c) 100
d) 101
View Answer
Answer: a
Explanation: By recording the path of the node from root to
leaf, the code word for character ‘a’ is found to be 011.
Page 236 of 295
8. From the following given tree, what is the computed
codeword for ‘c’?
a) 111
b) 101
c) 110
d) 011
View Answer
Answer: c
Explanation: By recording the path of the node from root to
leaf, assigning left branch as 0 and right branch as 1, the
codeword for c is 110.
9. What will be the cost of the code if character ci is at depth
di and occurs at frequency fi?
a) cifi
b) ∫cifi
c) ∑fidi
Page 237 of 295
d) fidi
View Answer
Answer: c
Explanation: If character ci is at depth di and occurs at
frequency fi, the cost of the codeword obtained is ∑fidi.
10. An optimal code will always be present in a full tree.
a) true
b) false
View Answer
Answer: a
Explanation: An optimal tree will always have the property
that all nodes are either leaves or have two children.
Otherwise, nodes with one child could move up a level.
11. The type of encoding where no character code is the
prefix of another character code is called?
a) optimal encoding
b) prefix encoding
c) frequency encoding
d) trie encoding
View Answer
Answer: b
Explanation: Even if the character codes are of different
Page 238 of 295
lengths, the encoding where no character code is the prefix
of another character code is called prefix encoding.
12. What is the running time of the Huffman encoding
algorithm?
a) O(C)
b) O(log C)
c) O(C log C)
d) O( N log C)
View Answer
Answer: c
Explanation: If we maintain the trees in a priority queue,
ordered by weight, then the running time is given by O(C log
C).
13. What is the running time of the Huffman algorithm, if its
implementation of the priority queue is done using linked
lists?
a) O(C)
b) O(log C)
c) O(C log C)
d) O(C2)
View Answer
Page 239 of 295
Answer: d
Explanation: If the implementation of the priority queue is
done using linked lists, the running time of Huffman
algorithm is O(C2).
Backtracking Multiple Choice Questions and Answers
(MCQs)
This set of Data Structures & Algorithms Multiple Choice
Questions & Answers (MCQs) focuses on “Backtracking”.
1. Which of the problems cannot be solved by backtracking
method?
a) n-queen problem
b) subset sum problem
c) hamiltonian circuit problem
d) travelling salesman problem
View Answer
Answer: d
Explanation: N-queen problem, subset sum problem,
Hamiltonian circuit problems can be solved by backtracking
method whereas travelling salesman problem is solved by
Branch and bound method.
2. Backtracking algorithm is implemented by constructing a
tree of choices called as?
Page 240 of 295
a) State-space tree
b) State-chart tree
c) Node tree
d) Backtracking tree
View Answer
Answer: a
Explanation: Backtracking problem is solved by constructing
a tree of choices called as the state-space tree. Its root
represents an initial state before the search for a solution
begins.
3. What happens when the backtracking algorithm reaches
a complete solution?
a) It backtracks to the root
b) It continues searching for other possible solutions
c) It traverses from a different route
d) Recursively traverses through the same route
View Answer
Answer: b
Explanation: When we reach a final solution using a
backtracking algorithm, we either stop or continue
searching for other possible solutions.
advertisement
Page 241 of 295
4. A node is said to be ____________ if it has a possibility of
reaching a complete solution.
a) Non-promising
b) Promising
c) Succeeding
d) Preceding
View Answer
Answer: b
Explanation: If a node has a possibility of reaching the final
solution, it is called a promising node. Otherwise, it is non-
promising.
5. In what manner is a state-space tree for a backtracking
algorithm constructed?
a) Depth-first search
b) Breadth-first search
c) Twice around the tree
d) Nearest neighbour first
View Answer
Answer: a
Explanation: A state-space tree for a backtracking algorithm
is constructed in the manner of depth-first search so that it
is easy to look into.
Page 242 of 295
Subscribe Now: Design and Analysis of Algorithms
Newsletter | Important Subjects Newsletters
6. The leaves in a state-space tree represent only complete
solutions.
a) true
b) false
View Answer
Answer: b
Explanation: The leaves in a state space tree can either
represent non-promising dead ends or complete solutions
found by the algorithm.
7. In general, backtracking can be used to solve?
a) Numerical problems
b) Exhaustive search
c) Combinatorial problems
d) Graph coloring problems
View Answer
Answer: c
Explanation: Backtracking approach is used to solve complex
combinatorial problems which cannot be solved by
exhaustive search algorithms.
Page 243 of 295
8. Which one of the following is an application of the
backtracking algorithm?
a) Finding the shortest path
b) Finding the efficient quantity to shop
c) Ludo
d) Crossword
View Answer
Answer: d
Explanation: Crossword puzzles are based on backtracking
approach whereas the rest are travelling salesman problem,
knapsack problem and dice game.
9. Backtracking algorithm is faster than the brute force
technique
a) true
b) false
View Answer
Answer: a
Explanation: Backtracking is faster than brute force
approach since it can remove a large set of answers in one
test.
10. Which of the following logical programming languages is
not based on backtracking?
Page 244 of 295
a) Icon
b) Prolog
c) Planner
d) Fortran
View Answer
Answer: d
Explanation: Backtracking algorithm form the basis for icon,
planner and prolog whereas fortran is an ancient assembly
language used in second generation computers.
11. The problem of finding a list of integers in a given
specific range that meets certain conditions is called?
a) Subset sum problem
b) Constraint satisfaction problem
c) Hamiltonian circuit problem
d) Travelling salesman problem
View Answer
Answer: b
Explanation: Constraint satisfaction problem is the problem
of finding a list of integers under given constraints.
Constraint satisfaction problem is solved using a
backtracking approach.
Page 245 of 295
12. Who coined the term ‘backtracking’?
a) Lehmer
b) Donald
c) Ross
d) Ford
View Answer
Answer: a
Explanation: D.H. Lehmer was the first person to coin the
term backtracking. Initially, the backtracking facility was
provided using SNOBOL.
13. ___________ enumerates a list of promising nodes that
could be computed to give the possible solutions of a given
problem.
a) Exhaustive search
b) Brute force
c) Backtracking
d) Divide and conquer
View Answer
Answer: c
Explanation: Backtracking is a general algorithm that
evaluates partially constructed candidates that can be
developed further without violating problem constraints.
Page 246 of 295
14. The problem of finding a subset of positive integers
whose sum is equal to a given positive integer is called as?
a) n- queen problem
b) subset sum problem
c) knapsack problem
d) hamiltonian circuit problem
View Answer
Answer: b
Explanation: Subset sum problem is the problem of finding a
subset using the backtracking algorithm when summed,
equals a given integer.
15. The problem of placing n queens in a chessboard such
that no two queens attack each other is called as?
a) n-queen problem
b) eight queens puzzle
c) four queens puzzle
d) 1-queen problem
View Answer
Answer: a
Explanation: The problem of placing n-queens in a
chessboard such that no two queens are vertical or
horizontal or diagonal to each other is an n-queen problem.
The problem only exists for n = 1, 4, 8.
Page 247 of 295
Eight Queens Problem Multiple Choice Questions and
Answers (MCQs)
This set of Data Structures & Algorithms Multiple Choice
Questions & Answers (MCQs) focuses on “Eight Queens
Problem”.
1. Who published the eight queens puzzle?
a) Max Bezzel
b) Carl
c) Gauss
d) Friedrich
View Answer
Answer: a
Explanation: The first Eight Queen Puzzle was published by
Max Friedrich William Bezzel, who was a chess composer by
profession in 1848. He was a German chess composer and
the first person to publish the puzzle.
2. When was the Eight Queen Puzzle published?
a) 1846
b) 1847
c) 1848
d) 1849
View Answer
Page 248 of 295
Answer: c
Explanation: The first Eight Queen Puzzle was published by
Max Friedrich William Bezzel, who was a German chess
composer by profession. He published the puzzle in 1848.
3. Who published the first solution of the eight queens
puzzle?
a) Franz Nauck
b) Max Bezzel
c) Carl
d) Friedrich
View Answer
Answer: a
Explanation: The first solution to the Eight Queen Puzzle was
given by Franz Nauck in 1850. While the first Eight Queen
Puzzle was published by Max Friedrich William Bezzel, who
was a German chess composer.
advertisement
4. When was the first solution to Eight Queen Puzzle
published?
a) 1850
b) 1847
c) 1848
Page 249 of 295
d) 1849
View Answer
Answer: a
Explanation: The first solution to the Eight Queen Puzzle was
given by Franz Nauck in 1850. Max Friedrich William Bezzel,
who was a German chess composer by profession published
the puzzle in 1848.
5. Who published the extended version of eight queens
puzzle?
a) Franz Nauck
b) Max Bezzel
c) Carl
d) Friedrich
View Answer
Answer: a
Explanation: The first extended version to the Eight Queen
Puzzle was given by Franz Nauck in 1850. Max Friedrich
William Bezzel published the puzzle in 1848.
Subscribe Now: Design and Analysis of Algorithms
Newsletter | Important Subjects Newsletters
6. For how many queens was the extended version of Eight
Queen Puzzle applicable for n*n squares?
Page 250 of 295
a) 5
b) 6
c) 8
d) n
View Answer
Answer: d
Explanation: The extended version given by Franz Nauck of
the Eight Queen Puzzle was for n queens on n*n square
chessboard. Earlier the puzzle was proposed with 8 queens
on 8*8 board.
7. Who was the first person to find the solution of Eight
Queen Puzzle using determinant?
a) Max Bezzel
b) Frank Nauck
c) Gunther
d) Friedrich
View Answer
Answer: c
Explanation: S. Gunther was the first person to propose a
solution to the eight queen puzzle using determinant. Max
Friedrich William Bezzel published the puzzle and the first
solution to the Eight Queen Puzzle was given by Franz
Nauck.
Page 251 of 295
8. Who proposed the depth first backtracking algorithm?
a) Edsger Dijkshtra
b) Max Bezzel
c) Frank Nauck
d) Carl Friedrich
View Answer
Answer: a
Explanation: In 1972, depth first backtracking algorithm was
proposed by Edsger Dijkshtra to illustrate the Eight Queen
Puzzle. Max Friedrich William Bezzel published the puzzle
and the first solution to the Eight Queen Puzzle was given by
Franz Nauck.
9. How many solutions are there for 8 queens on 8*8
board?
a) 12
b) 91
c) 92
d) 93
View Answer
Answer: c
Explanation: For 8*8 chess board with 8 queens there are
total of 92 solutions for the puzzle. There are total of 12
fundamental solutions to the eight queen puzzle.
Page 252 of 295
10. Who publish the bitwise operation method to solve the
eight queen puzzle?
a) Zongyan Qiu
b) Martin Richard
c) Max Bezzel
d) Frank Nauck
View Answer
Answer: a
Explanation: The first person to publish the bitwise
operation method to solve the eight queen puzzle was
Zongyan Qiu. After him, it was published by Martin Richard.
11. How many fundamental solutions are there for the eight
queen puzzle?
a) 92
b) 10
c) 11
d) 12
View Answer
Answer: d
Explanation: There are total of 12 fundamental solutions to
the eight queen puzzle after removing the symmetrical
solutions due to rotation. For 8*8 chess board with 8
queens there are total of 92 solutions for the puzzle.
Page 253 of 295
12. Is it possible to have no four queens in a straight line as
the part of one of the solution to the eight queen puzzle.
a) True
b) False
View Answer
Answer: b
Explanation: No three queens lie in a straight line in one of
the fundamental solution of the eight queen puzzle.
13. How many fundamental solutions are the for 3 queens
on a 3*3 board?
a) 1
b) 12
c) 3
d) 0
View Answer
Answer: d
Explanation: There are in total zero solution to the 3 queen
puzzle for 3*3 chess board. Hence there are no fundamental
solutions. For 8*8 chess board with 8 queens there are total
of 12 fundamental solutions for the puzzle.
14. The six queen puzzle has a fewer solution than the five
queen puzzle.
Page 254 of 295
a) True
b) False
View Answer
Answer: a
Explanation: There are total 4 solutions for the six queen
puzzle and one fundamental solution while there are total
of 10 solutions for 5 queen puzzle and 2 fundamental
solutions.
15. Which ordered board is the highest enumerated board
till now?
a) 25*25
b) 26*26
c) 27*27
d) 28*28
View Answer
Answer: c
Explanation: The 27*27 board has the highest order board
with total 234,907,967,154,122,528 solutions. It also has
total of 29,363,495,934,315,694 fundamental solution.
ata Structure Questions and Answers – Dynamic
Programming
Page 255 of 295
This set of Data Structure Multiple Choice Questions &
Answers (MCQs) focuses on “Dynamic Programming”.
1. Which of the following is/are property/properties of a
dynamic programming problem?
a) Optimal substructure
b) Overlapping subproblems
c) Greedy approach
d) Both optimal substructure and overlapping subproblems
View Answer
Answer: d
Explanation: A problem that can be solved using dynamic
programming possesses overlapping subproblems as well as
optimal substructure properties.
2. If an optimal solution can be created for a problem by
constructing optimal solutions for its subproblems, the
problem possesses ____________ property.
a) Overlapping subproblems
b) Optimal substructure
c) Memoization
d) Greedy
View Answer
Page 256 of 295
Answer: b
Explanation: Optimal substructure is the property in which
an optimal solution is found for the problem by constructing
optimal solutions for the subproblems.
3. If a problem can be broken into subproblems which are
reused several times, the problem possesses ____________
property.
a) Overlapping subproblems
b) Optimal substructure
c) Memoization
d) Greedy
View Answer
Answer: a
Explanation: Overlapping subproblems is the property in
which value of a subproblem is used several times.
advertisement
4. If a problem can be solved by combining optimal
solutions to non-overlapping problems, the strategy is called
_____________
a) Dynamic programming
b) Greedy
c) Divide and conquer
Page 257 of 295
d) Recursion
View Answer
Answer: c
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. The optimal
solutions are then combined to get a global optimal
solution. For example, mergesort uses divide and conquer
strategy.
5. When dynamic programming is applied to a problem, it
takes far less time as compared to other methods that don’t
take advantage of overlapping subproblems.
a) True
b) False
View Answer
Answer: a
Explanation: Dynamic programming calculates the value of a
subproblem only once, while other methods that don’t take
advantage of the overlapping subproblems property may
calculate the value of the same subproblem several times.
So, dynamic programming saves the time of recalculation
and takes far less time as compared to other methods that
Page 258 of 295
don’t take advantage of the overlapping subproblems
property.
Sanfoundry Certification Contest of the Month is Live. 100+
Subjects. Participate Now!
6. A greedy algorithm can be used to solve all the dynamic
programming problems.
a) True
b) False
View Answer
Answer: b
Explanation: A greedy algorithm gives optimal solution for
all subproblems, but when these locally optimal solutions
are combined it may NOT result into a globally optimal
solution. Hence, a greedy algorithm CANNOT be used to
solve all the dynamic programming problems.
7. In dynamic programming, the technique of storing the
previously calculated values is called ___________
a) Saving value property
b) Storing value property
c) Memoization
d) Mapping
View Answer
Page 259 of 295
Answer: c
Explanation: Memoization is the technique in which
previously calculated values are stored, so that, these values
can be used to solve other subproblems.
8. When a top-down approach of dynamic programming is
applied to a problem, it usually _____________
a) Decreases both, the time complexity and the space
complexity
b) Decreases the time complexity and increases the space
complexity
c) Increases the time complexity and decreases the space
complexity
d) Increases both, the time complexity and the space
complexity
View Answer
Answer: b
Explanation: The top-down approach uses the memoization
technique which stores the previously calculated values.
Due to this, the time complexity is decreased but the space
complexity is increased.
9. Which of the following problems is NOT solved using
dynamic programming?
a) 0/1 knapsack problem
Page 260 of 295
b) Matrix chain multiplication problem
c) Edit distance problem
d) Fractional knapsack problem
View Answer
Answer: d
Explanation: The fractional knapsack problem is solved using
a greedy algorithm.
10. Which of the following problems should be solved using
dynamic programming?
a) Mergesort
b) Binary search
c) Longest common subsequence
d) Quicksort
View Answer
Answer: c
Explanation: The longest common subsequence problem
has both, optimal substructure and overlapping
subproblems. Hence, dynamic programming should be used
the solve this problem.
Hamming Code Multiple Choice Questions and Answers
(MCQs)
Page 261 of 295
This set of Data Structures & Algorithms Multiple Choice
Questions & Answers (MCQs) focuses on “Hamming Code”.
1. The most common hamming codes are a generalized
version of?
a) Hamming(7, 4) code
b) Hamming(8, 4) code
c) Hamming(6, 3) code
d) Hamming(5, 7) code
View Answer
Answer: a
Explanation: The most common hamming codes generalize
to form hamming(7, 4) code. It encodes four bits of data
into seven bits by adding three parity bits.
2. What is the minimal Hamming distance between any two
correct codewords?
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: c
Explanation: Since we use a generalized version of
Page 262 of 295
Hamming(7, 4) code, the minimal hamming distance is 3. It
cannot correct burst errors.
3. Why do we require hamming codes?
a) Error correction
b) Encryption only
c) Decryption
d) Bit stuffing
View Answer
Answer: a
Explanation: Hamming codes are used for the purpose of
error detection and correction. It is also used for channel
encoding and decoding. They are linear-error correcting
codes.
advertisement
4. Hamming codes can be used for both single-bit error and
burst error detection and correction.
a) True
b) False
View Answer
Answer: b
Explanation: Hamming bits are suitable only for single-bit
Page 263 of 295
error detection and correction and two bit error detection.
It is very unlikely to detect burst errors.
5. Who invented Hamming codes?
a) Richard Hamming
b) Ross Hamming
c) Shannon
d) Huffman
View Answer
Answer: a
Explanation: Richard W. Hamming invented hamming codes
in Bell Telephone Laboratory to minimize the errors in
punched card readers. Huffman invented huffman codes.
Shannon invented Shannon-Fanno codes.
Subscribe Now: Design and Analysis of Algorithms
Newsletter | Important Subjects Newsletters
6. What is the total block length ‘n’ of a Hamming code?
a) 2r
b) 2r-1
c) 2r-1-1
d) 2r+1
View Answer
Page 264 of 295
Answer: b
Explanation: Hamming codes are a class of binary linear
codes, hence r>=2. For a hamming(7, 4) code, the block
length ‘n’ is 2r-1 where r is the parity bit. Here, r=3.
7. What is the message length ‘k’ of a Hamming(7,4) code?
a) 2r-1
b) 2r-r+1
c) 2r-r-1
d) 2r+1-r
View Answer
Answer: c
Explanation: Hamming codes are a class of binary linear
codes, hence r>=2. For a hamming(7,4) code, the message
length ‘k’ is 2r-r-1 where r is the parity bit. Here, r=3.
8. What is the rate of hamming codes?
a) 1-[r/(2r-1)]
b) 1-(r/2r)
c) 1+(r/2r)
d) r/2r+1
View Answer
Answer: a
Explanation: Rate of a hamming code is message length
Page 265 of 295
divided by block length (i.e.) 2r-r-1/2r-1 = 1-[r/(2r-1)]. It is the
highest rate for a minimum distance of three.
9. A two-out-of-five code consists of _________
a) Two 0s and three 1s
b) Three 0s and two 1s
c) Four 0s and one 1s
d) One 0s and four 1s
View Answer
Answer: b
Explanation: A two-out-of-five code consists of three 0s and
two 1s. Hence, it contains ten possible combinations to
represent digits from 0-9.
10. Including a parity bit along with the data surely detects
the errors.
a) true
b) false
View Answer
11. ________ is the mechanism of sending data bits
multiple times to ensure consistency.
a) Repetition
b) Duplication
c) Mirroring
Page 266 of 295
d) Redundancy
View Answer
Answer: a
Explanation: Repeating data bits multiple times is done to
ensure consistency. If the data bit to be sent is a 1, a n=3
repetition code will send 111. If the bits are not the same,
an error has occurred.
12. An Extended hamming code is also called as __________
a) SEDDEC
b) SEDDED
c) SECDED
d) SECDEC
View Answer
Answer: c
Explanation: An Extended Hamming code is also called as
SECDED (Single Error Correction Double Error Detection).
The most popular codes are (72, 64) code and (127,120)
code.
13. What is the code rate of a repetition Hamming code (3,
1)?
a) 1
b) 3
Page 267 of 295
c) 1/3
d) 1.3
View Answer
Answer: c
Explanation: The code rate of a repetition hamming code is
the second number divided by the first number. Here, it is
1/3.
14. For a hamming code of parity bit m=8, what is the total
bits and data bits?
a) (255, 247)
b) (127, 119)
c) (31, 26)
d) (0, 8)
View Answer
Answer: a
Explanation: Total bits are computed as, 2m-1 = 28-1 =255.
Data bits are computed as 2m-m-1= 28-8-1= 247.
15. What is the rate of the hamming code of parity bit m=8?
a) 0.94
b) 0.92
c) 0.90
Page 268 of 295
d) 0.97
View Answer
Answer: d
Explanation: For a hamming code of parity bit 8, total bits =
255 and data bits = 247. Rate= data bits/ total bits
= 247/255 = 0.969 = 0.97.
This set of Data Structures & Algorithms Multiple Choice
Questions & Answers (MCQs) focuses on “P, NP, NP-hard,
NP-complete Complexity Classes”.
1. The worst-case efficiency of solving a problem in
polynomial time is?
a) O(p(n))
b) O(p( n log n))
c) O(p(n2))
d) O(p(m log n))
View Answer
Answer: a
Explanation: The worst-case efficiency of solving an problem
in polynomial time is O(p(n)) where p(n) is the polynomial
time of input size.
2. Problems that can be solved in polynomial time are
known as?
Page 269 of 295
a) intractable
b) tractable
c) decision
d) complete
View Answer
Answer: b
Explanation: Problems that can be solved in polynomial time
are known as tractable. Problems that cannot be solved in
polynomial time are intractable.
3. The sum and composition of two polynomials are always
polynomials.
a) true
b) false
View Answer
Answer: a
Explanation: One of the properties of polynomial functions
states that the sum and composition of two polynomials are
always polynomials.
advertisement
4. _________ is the class of decision problems that can be
solved by non-deterministic polynomial algorithms.
a) NP
Page 270 of 295
b) P
c) Hard
d) Complete
View Answer
Answer: a
Explanation: NP problems are called as non-deterministic
polynomial problems. They are a class of decision problems
that can be solved using NP algorithms.
5. Problems that cannot be solved by any algorithm are
called?
a) tractable problems
b) intractable problems
c) undecidable problems
d) decidable problems
View Answer
Answer: c
Explanation: Problems cannot be solved by any algorithm
are called undecidable problems. Problems that can be
solved in polynomial time are called Tractable problems.
Subscribe Now: Design and Analysis of Algorithms
Newsletter | Important Subjects Newsletters
Page 271 of 295
6. The Euler’s circuit problem can be solved in?
a) O(N)
b) O( N log N)
c) O(log N)
d) O(N2)
View Answer
Answer: d
Explanation: Mathematically, the run time of Euler’s circuit
problem is determined to be O(N2).
7. To which class does the Euler’s circuit problem belong?
a) P class
b) NP class
c) Partition class
d) Complete class
View Answer
Answer: a
Explanation: Euler’s circuit problem can be solved in
polynomial time. It can be solved in O(N2).
8. Halting problem is an example for?
a) decidable problem
b) undecidable problem
c) complete problem
Page 272 of 295
d) trackable problem
View Answer
Answer: b
Explanation: Halting problem by Alan Turing cannot be
solved by any algorithm. Hence, it is undecidable.
9. How many stages of procedure does a non-deterministic
algorithm consist of?
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: b
Explanation: A non-deterministic algorithm is a two-stage
procedure- guessing stage and verification stage.
10. A non-deterministic algorithm is said to be non-
deterministic polynomial if the time-efficiency of its
verification stage is polynomial.
a) true
b) false
View Answer
Page 273 of 295
Answer: a
Explanation: One of the properties of NP class problems
states that A non-deterministic algorithm is said to be non-
deterministic polynomial if the time-efficiency of its
verification stage is polynomial.
11. How many conditions have to be met if an NP- complete
problem is polynomially reducible?
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: b
Explanation: A function t that maps all yes instances of
decision problems D1 and D2 and t should be computed in
polynomial time are the two conditions.
12. To which of the following class does a CNF-satisfiability
problem belong?
a) NP class
b) P class
c) NP complete
d) NP hard
View Answer
Page 274 of 295
Answer: c
Explanation: The CNF satisfiability problem belongs to NP
complete class. It deals with Boolean expressions.
13. How many steps are required to prove that a decision
problem is NP complete?
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: b
Explanation: First, the problem should be NP. Next, it should
be proved that every problem in NP is reducible to the
problem in question in polynomial time.
14. Which of the following problems is not NP complete?
a) Hamiltonian circuit
b) Bin packing
c) Partition problem
d) Halting problem
View Answer
Answer: d
Explanation: Hamiltonian circuit, bin packing, partition
Page 275 of 295
problems are NP complete problems. Halting problem is an
undecidable problem.
15. The choice of polynomial class has led to the
development of an extensive theory called ________
a) computational complexity
b) time complexity
c) problem complexity
d) decision complexity
View Answer
Answer: a
Explanation: An extensive theory called computational
complexity seeks to classify problems according to their
inherent difficulty.
Hamiltonian Path Problem Multiple Choice Questions and
Answers (MCQs)
This set of Data Structures & Algorithms Multiple Choice
Questions & Answers (MCQs) focuses on “Hamiltonian Path
Problem”.
1. Which of the following algorithm can be used to solve the
Hamiltonian path problem efficiently?
a) branch and bound
b) iterative improvement
Page 276 of 295
c) divide and conquer
d) greedy algorithm
View Answer
Answer: a
Explanation: The Hamiltonian path problem can be solved
efficiently using branch and bound approach. It can also be
solved using a backtracking approach.
2. The problem of finding a path in a graph that visits every
vertex exactly once is called?
a) Hamiltonian path problem
b) Hamiltonian cycle problem
c) Subset sum problem
d) Turnpike reconstruction problem
View Answer
Answer: a
Explanation: Hamiltonian path problem is a problem of
finding a path in a graph that visits every node exactly once
whereas Hamiltonian cycle problem is finding a cycle in a
graph.
3. Hamiltonian path problem is _________
a) NP problem
b) N class problem
Page 277 of 295
c) P class problem
d) NP complete problem
View Answer
Answer: d
Explanation: Hamiltonian path problem is found to be NP
complete. Hamiltonian cycle problem is also an NP-
complete problem.
advertisement
4. There is no existing relationship between a Hamiltonian
path problem and Hamiltonian circuit problem.
a) true
b) false
View Answer
Answer: b
Explanation: There is a relationship between Hamiltonian
path problem and Hamiltonian circuit problem. The
Hamiltonian path in graph G is equal to Hamiltonian cycle in
graph H under certain conditions.
5. Which of the following problems is similar to that of a
Hamiltonian path problem?
a) knapsack problem
b) closest pair problem
Page 278 of 295
c) travelling salesman problem
d) assignment problem
View Answer
Answer: c
Explanation: Hamiltonian path problem is similar to that of a
travelling salesman problem since both the problem
traverses all the nodes in a graph exactly once.
Subscribe Now: Design and Analysis of Algorithms
Newsletter | Important Subjects Newsletters
6. Who formulated the first ever algorithm for solving the
Hamiltonian path problem?
a) Martello
b) Monte Carlo
c) Leonard
d) Bellman
View Answer
Answer: a
Explanation: The first ever problem to solve the Hamiltonian
path was the enumerative algorithm formulated by
Martello.
7. In what time can the Hamiltonian path problem can be
solved using dynamic programming?
Page 279 of 295
a) O(N)
b) O(N log N)
c) O(N2)
d) O(N2 2N)
View Answer
Answer: d
Explanation: Using dynamic programming, the time taken to
solve the Hamiltonian path problem is mathematically
found to be O(N2 2N).
8. In graphs, in which all vertices have an odd degree, the
number of Hamiltonian cycles through any fixed edge is
always even.
a) true
b) false
View Answer
Answer: a
Explanation: According to a handshaking lemma, in graphs,
in which all vertices have an odd degree, the number of
Hamiltonian cycles through any fixed edge is always even.
9. Who invented the inclusion-exclusion principle to solve
the Hamiltonian path problem?
a) Karp
Page 280 of 295
b) Leonard Adleman
c) Andreas Bjorklund
d) Martello
View Answer
Answer: c
Explanation: Andreas Bjorklund came up with the inclusion-
exclusion principle to reduce the counting of number of
Hamiltonian cycles.
10. For a graph of degree three, in what time can a
Hamiltonian path be found?
a) O(0.251n)
b) O(0.401n)
c) O(0.167n)
d) O(0.151n)
View Answer
Answer: a
Explanation: For a graph of maximum degree three, a
Hamiltonian path can be found in time O(0.251n).
11. What is the time complexity for finding a Hamiltonian
path for a graph having N vertices (using permutation)?
a) O(N!)
b) O(N! * N)
Page 281 of 295
c) O(log N)
d) O(N)
View Answer
Answer: b
Explanation: For a graph having N vertices traverse the
permutations in N! iterations and it traverses the
permutations to see if adjacent vertices are connected or
not takes N iterations (i.e.) O(N! * N).
12. How many Hamiltonian paths does the following graph
have?
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: a
Explanation: The above graph has only one Hamiltonian
path that is from a-b-c-d-e.
Page 282 of 295
13. How many Hamiltonian paths does the following graph
have?
a) 1
b) 2
c) 0
d) 3
View Answer
Answer: c
Explanation: The above graph has no Hamiltonian paths.
That is, we cannot traverse the graph with meeting vertices
exactly once.
Subset Sum Problem Multiple Choice Questions and
Answers (MCQs)
Page 283 of 295
This set of Data Structures & Algorithms Multiple Choice
Questions & Answers (MCQs) focuses on “Subset Sum
Problem”.
1. Under what condition any set A will be a subset of B?
a) if all elements of set B are also present in set A
b) if all elements of set A are also present in set B
c) if A contains more elements than B
d) if B contains more elements than A
View Answer
Answer: b
Explanation: Any set A will be called a subset of set B if all
elements of set A are also present in set B. So in such a case
set A will be a part of set B.
2. What is a subset sum problem?
a) finding a subset of a set that has sum of elements equal
to a given number
b) checking for the presence of a subset that has sum of
elements equal to a given number and printing true or false
based on the result
c) finding the sum of elements present in a set
d) finding the sum of all the subsets of a set
View Answer
Page 284 of 295
Answer: b
Explanation: In subset sum problem check for the presence
of a subset that has sum of elements equal to a given
number. If such a subset is present then we print true
otherwise false.
3. Which of the following is true about the time complexity
of the recursive solution of the subset sum problem?
a) It has an exponential time complexity
b) It has a linear time complexity
c) It has a logarithmic time complexity
d) it has a time complexity of O(n2)
View Answer
Answer: a
Explanation: Subset sum problem has both recursive as well
as dynamic programming solution. The recursive solution
has an exponential time complexity as it will require to
check for all subsets in worst case.
advertisement
4. What is the worst case time complexity of dynamic
programming solution of the subset sum
problem(sum=given subset sum)?
a) O(n)
Page 285 of 295
b) O(sum)
c) O(n2)
d) O(sum*n)
View Answer
Answer: d
Explanation: Subset sum problem has both recursive as well
as dynamic programming solution. The dynamic
programming solution has a time complexity of O(n*sum) as
it as a nested loop with limits from 1 to n and 1 to sum
respectively.
5. Subset sum problem is an example of NP-complete
problem.
a) true
b) false
View Answer
Answer: a
Explanation: Subset sum problem takes exponential time
when we implement a recursive solution. Subset sum
problem is known to be a part of NP complete problems.
Sanfoundry Certification Contest of the Month is Live. 100+
Subjects. Participate Now!
Page 286 of 295
6. Recursive solution of subset sum problem is faster than
dynamic problem solution in terms of time complexity.
a) true
b) false
View Answer
Answer: b
Explanation: The recursive solution to subset sum problem
takes exponential time complexity whereas the dynamic
programming solution takes polynomial time complexity. So
dynamic programming solution is faster in terms of time
complexity.
7. Which of the following is not true about subset sum
problem?
a) the recursive solution has a time complexity of O(2n)
b) there is no known solution that takes polynomial time
c) the recursive solution is slower than dynamic
programming solution
d) the dynamic programming solution has a time complexity
of O(n log n)
View Answer
Answer: d
Explanation: Recursive solution of subset sum problem is
slower than dynamic problem solution in terms of time
Page 287 of 295
complexity. Dynamic programming solution has a time
complexity of O(n*sum).
8. Which of the following should be the base case for the
recursive solution of subset sum problem?
a)
if(sum==0)
return true;
b)
if(sum==0)
return true;
if (n ==0 && sum!= 0)
return false;
c)
if (n ==0 && sum!= 0)
return false;
d)
if(sum<0)
return true;
if (n ==0 && sum!= 0)
Page 288 of 295
return false;
View Answer
Answer: b
Explanation: The base case condition defines the point at
which the program should stop recursion. In this case we
need to make sure that, the sum does not become 0 and
there should be elements left in our array for recursion to
happen.
9. What will be the output for the following code?
#include <stdio.h>
bool func(int arr[], int n, int sum)
{
if (sum == 0)
return true;
if (n == 0 && sum != 0)
return false;
if (arr[n-1] > sum)
return func(arr, n-1, sum);
Page 289 of 295
return func(arr, n-1, sum) || func(arr, n-1, sum-arr[n-1]);
}
int main()
{
int arr[] = {4,6, 12, 2};
int sum = 12;
int n = sizeof(arr)/sizeof(arr[0]);
if (func(arr, n, sum) == true)
printf("true");
else
printf("false");
return 0;
}
a) 12
b) 4 6 2
c) True
d) False
View Answer
Page 290 of 295
Answer: c
Explanation: The given code represents the recursive
approach of solving the subset sum problem. The output for
the code will be true if any subset is found to have sum
equal to the desired sum, otherwise false will be printed.
10. What will be the output for the following code?
#include <stdio.h>
bool func(int arr[], int n, int sum)
{
bool subarr[n+1][sum+1];
for (int i = 0; i <= n; i++)
subarr[i][0] = true;
for (int i = 1; i <= sum; i++)
subarr[0][i] = false;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= sum; j++)
{
if(j<arr[i-1])
Page 291 of 295
subarr[i][j] = subarr[i-1][j];
if (j >= arr[i-1])
subarr[i][j] = subarr[i-1][j] ||
subarr[i - 1][j-arr[i-1]];
}
}
return subarr[n][sum];
}
int main()
{
int arr[] = {3, 3, 4, 4, 7};
int sum = 5;
int n = sizeof(arr)/sizeof(arr[0]);
if (func(arr, n, sum) == true)
printf("true");
else
printf("false");
return 0;
Page 292 of 295
}
a) true
b) false
c) 0
d) error in code
View Answer
Answer: b
Explanation: The given code represents the dynamic
programming approach of solving the subset sum problem.
The output for the code will be true if any subset is found to
have sum equal to the desired sum, otherwise false will be
printed.
11. What will be the worst case time complexity for the
following code?
#include <stdio.h>
bool func(int arr[], int n, int sum)
{
if (sum == 0)
return true;
if (n == 0 && sum != 0)
return false;
Page 293 of 295
if (arr[n-1] > sum)
return func(arr, n-1, sum);
return func(arr, n-1, sum) || func(arr, n-1, sum-arr[n-1]);
}
int main()
{
int arr[] = {4,6, 12, 2};
int sum = 12;
int n = sizeof(arr)/sizeof(arr[0]);
if (func(arr, n, sum) == true)
printf("true");
else
printf("false");
return 0;
}
a) O(n log n)
b) O(n2)
c) O(2n)
Page 294 of 295
d) O(n2 log n)
View Answer
Answer: c
Explanation: The given code represents the recursive
approach solution of the subset sum problem. It has an
exponential time complexity as it will require to check for all
subsets in the worst case. It is equal to O(2n).
Page 295 of 295