DS ALL MCQs
DS ALL MCQs
DS ALL MCQs
1. A linear collection of data elements where the linear node is given by means of pointer is called?
a) Linked list
b) Node list
c) Primitive list
d) Unordered list
View Answer
Answer: a
Explanation: In Linked list each node has its own data and the address of next node. These nodes are linked
by using pointers. Node list is an object that consists of a list of all nodes in a document with in a particular
selected set of nodes.
2. Consider an implementation of unsorted singly linked list. Suppose it has its representation with a head
pointer only. Given the representation, which of the following operation can be implemented in O(1) time?
a) I and II
b) I and III
c) I, II and III
d) I, II and IV
View Answer
Answer: b
Explanation: We know the head node in the given linked list. Insertion and deletion of elements at the front
of the linked list completes in O (1) time whereas for insertion and deletion at the last node requires to
traverse through every node in the linked list. Suppose there are n elements in a linked list, we need to
traverse through each node. Hence time complexity becomes O(n).
3. In linked list each node contains a minimum of two fields. One field is data field to store the data second
field is?
a) Pointer to character
b) Pointer to integer
c) Pointer to node
d) Node
View Answer
Answer: c
Explanation: Each node in a linked list contains data and a pointer (reference) to the next node. Second field
contains pointer to node.
4. What would be the asymptotic time complexity to add a node at the end of singly linked list, if the pointer
is initially pointing to the head of the list?
a) O(1)
b) O(n)
c) θ(n)
d) θ(1)
View Answer
Answer: c
Explanation: In case of a linked list having n elements, we need to travel through every node of the list to
add the element at the end of the list. Thus asymptotic time complexity is θ(n).
5. What would be the asymptotic time complexity to insert an element at the front of the linked list (head is
known)?
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
View Answer
Answer: a
Explanation: To add an element at the front of the linked list, we will create a new node which holds the data
to be added to the linked list and pointer which points to head position in the linked list. The entire thing
happens within O (1) time. Thus the asymptotic time complexity is O (1).
6. What would be the asymptotic time complexity to find an element in the linked list?
a) O(1)
b) O(n)
c) O(n2)
d) O(n4)
View Answer
Answer: b
Explanation: If the required element is in the last position, we need to traverse the entire linked list. This will
take O (n) time to search the element.
7. What would be the asymptotic time complexity to insert an element at the second position in the linked
list?
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
View Answer
Answer: a
Explanation: A new node is created with the required element. The pointer of the new node points the node
to which the head node of the linked list is also pointing. The head node pointer is changed and it points to
the new node which we created earlier. The entire process completes in O (1) time. Thus the asymptotic time
complexity to insert an element in the second position of the linked list is O (1).
8. The concatenation of two lists can be performed in O(1) time. Which of the following variation of the
linked list can be used?
a) Singly linked list
b) Doubly linked list
c) Circular doubly linked list
d) Array implementation of list
View Answer
Answer: c
Explanation: We can easily concatenate two lists in O (1) time using singly or doubly linked list, provided
that we have a pointer to the last node at least one of the lists. But in case of circular doubly linked lists, we
will break the link in both the lists and hook them together. Thus circular doubly linked list concatenates two
lists in O (1) time.
struct node
{
int data;
struct node * next;
}
typedef struct node NODE;
NODE *ptr;
Answer: a
Explanation: As it represents the right way to create a node.
1. What kind of linked list is best to answer questions like “What is the item at position n?”
a) Singly linked list
b) Doubly linked list
c) Circular linked list
d) Array implementation of linked list
View Answer
Answer: d
Explanation: Arrays provide random access to elements by providing the index value within square brackets.
In the linked list, we need to traverse through each element until we reach the nth position. Time taken to
access an element represented in arrays is less than the singly, doubly and circular linked lists. Thus, array
implementation is used to access the item at the position n.
Answer: d
Explanation: It cannot be implemented using linked lists.
3. Linked list is considered as an example of ___________ type of memory allocation.
a) Dynamic
b) Static
c) Compile time
d) Heap
View Answer
Answer: a
Explanation: As memory is allocated at the run time.
Answer: b
Explanation: A linked list is a collection of objects linked together by references from an object to another
object. By convention these objects are names as nodes. Linked list consists of nodes where each node
contains one or more data fields and a reference(link) to the next node.
Answer: c
Explanation: Linked lists saves both space and time.
6. Which of the following points is/are not true about Linked List data structure when it is compared with an
array?
a) Arrays have better cache locality that can make them better in terms of performance
b) It is easy to insert and delete elements in Linked List
c) Random access is not allowed in a typical implementation of Linked Lists
d) Access of elements in linked list takes less time than compared to arrays
View Answer
Answer: d
Explanation: To access an element in a linked list, we need to traverse every element until we reach the
desired element. This will take more time than arrays as arrays provide random access to its elements.
7. What does the following function do for a given Linked List with first node as head?
Answer: b
Explanation: fun1() prints the given Linked List in reverse manner.
For Linked List 1->2->3->4->5, fun1() prints 5->4->3->2->1.
8. Which of the following sorting algorithms can be used to sort a random linked list with minimum time
complexity?
a) Insertion Sort
b) Quick Sort
c) Heap Sort
d) Merge Sort
View Answer
Answer: d
Explanation: Both Merge sort and Insertion sort can be used for linked lists. The slow random-access
performance of a linked list makes other algorithms (such as quicksort) perform poorly, and others (such as
heapsort) completely impossible. Since worst case time complexity of Merge Sort is O(nLogn) and Insertion
sort is O(n2), merge sort is preferred.
7. You are given pointers to first and last nodes of a singly linked list, which of the following operations are
dependent on the length of the linked list?
a) Delete the first element
b) Insert a new element as a first element
c) Delete the last element of the list
d) Add a new element at the end of the list
View Answer
Answer: c
Explanation: Deletion of the first element of the list is done in O (1) time by deleting memory and changing
the first pointer.
Insertion of an element as a first element can be done in O (1) time. We will create a node that holds data
and points to the head of the given linked list. The head pointer was changed to a newly created node.
Deletion of the last element requires a pointer to the previous node of last, which can only be obtained by
traversing the list. This requires the length of the linked list.
Adding a new element at the end of the list can be done in O (1) by changing the pointer of the last node to
the newly created node and last is changed to a newly created node.
8. In the worst case, the number of comparisons needed to search a singly linked list of length n for a given
element is?
a) log2 n
b) n⁄2
c) log2 n – 1
d) n
View Answer
Answer: d
Explanation: The worst-case happens if the required element is at last or the element is absent in the list. For
this, we need to compare every element in the linked list. If n elements are there, n comparisons will happen
in the worst case.
5. In the worst case, the number of comparisons needed to search a singly linked list of length n for a given
element is?
a) log 2 n
b) n⁄2
c) log 2 n – 1
d) n
View Answer
Answer: d
Explanation: In the worst case, the element to be searched has to be compared with all elements of the linked
list.
6. Given pointer to a node X in a singly linked list. Only one pointer is given, pointer to head node is not
given, can we delete the node X from given linked list?
a) Possible if X is not last node
b) Possible if size of linked list is even
c) Possible if size of linked list is odd
d) Possible if X is not first node
View Answer
Answer: a
Explanation: Following are simple steps.
Answer: d
Explanation: Array elements can be accessed in two steps. First, multiply the size of the data type with the
specified position, second, add this value to the base address. Both of these operations can be done in
constant time, hence accessing elements at a given index/position is faster.
2. What is the time complexity of inserting at the end in dynamic arrays?
a) O(1)
b) O(n)
c) O(logn)
d) Either O(1) or O(n)
View Answer
Answer: d
Explanation: Depending on whether the array is full or not, the complexity in dynamic array varies. If you
try to insert into an array that is not full, then the element is simply stored at the end, this takes O(1) time. If
you try to insert into an array which is full, first you will have to allocate an array with double the size of the
current array and then copy all the elements into it and finally insert the new element, this takes O(n) time.
3. What is the time complexity to count the number of elements in the linked list?
a) O(1)
b) O(n)
c) O(logn)
d) O(n2)
View Answer
Answer: b
Explanation: To count the number of elements, you have to traverse through the entire list, hence complexity
is O(n).
Answer: a
Explanation: You need a temp variable to keep track of current node, hence the space complexity is O(1).
Answer: d
Explanation: To implement file system, for separate chaining in hash-tables and to implement non-binary
trees linked lists are used. Elements are accessed sequentially in linked list. Random access of elements is
not an applications of linked list.
1. Which of the following is false about a doubly linked list?
a) We can navigate in both the directions
b) It requires more space than a singly linked list
c) The insertion and deletion of a node take a bit longer
d) Implementing a doubly linked list is easier than singly linked list
View Answer
Answer: d
Explanation: A doubly linked list has two pointers ‘left’ and ‘right’ which enable it to traverse in either
direction. Compared to singly liked list which has only a ‘next’ pointer, doubly linked list requires extra
space to store this extra pointer. Every insertion and deletion requires manipulation of two pointers, hence it
takes a bit longer time. Implementing doubly linked list involves setting both left and right pointers to
correct nodes and takes more time than singly linked list.
Answer: a
Explanation: Memory efficient doubly linked list has only one pointer to traverse the list back and forth. The
implementation is based on pointer difference. It uses bitwise XOR operator to store the front and rear
pointer addresses. Instead of storing actual memory address, every node store the XOR address of previous
and next nodes.
5. How do you calculate the pointer difference in a memory efficient double linked list?
a) head xor tail
b) pointer to previous node xor pointer to next node
c) pointer to previous node – pointer to next node
d) pointer to next node – pointer to previous node
View Answer
Answer: b
Explanation: The pointer difference is calculated by taking XOR of pointer to previous node and pointer to
the next node.
6. What is the worst case time complexity of inserting a node in a doubly linked list?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(1)
View Answer
Answer: c
Explanation: In the worst case, the position to be inserted maybe at the end of the list, hence you have to
traverse through the entire list to get to the correct position, hence O(n).
1. What differentiates a circular linked list from a normal linked list?
a) You cannot have the ‘next’ pointer point to null in a circular linked list
b) It is faster to traverse the circular linked list
c) You may or may not have the ‘next’ pointer point to null in a circular linked list
d) Head node is known in circular linked list
View Answer
Answer: c
Explanation: The ‘next’ pointer points to null only when the list is empty, otherwise it points to the head of
the list. Every node in a circular linked list can be a starting point(head).
4. What is the time complexity of searching for an element in a circular linked list?
a) O(n)
b) O(nlogn)
c) O(1)
d) O(n2)
View Answer
Answer: a
Explanation: In the worst case, you have to traverse through the entire list of n elements.
Answer: c
Explanation: Generally, round robin fashion is employed to allocate CPU time to resources which makes use
of the circular linked list data structure. Recursive function calls use stack data structure. Undo Operation in
text editor uses doubly linked lists. Hash tables uses singly linked lists.
Answer: b
Explanation: Time complexity of inserting a new node at the head of the list is O(n) because you have to
traverse through the list to find the tail node.
10. Consider a small circular linked list. How to detect the presence of cycles in this list effectively?
a) Keep one node as head and traverse another temp node till the end to check if its ‘next points to head
b) Have fast and slow pointers with the fast pointer advancing two nodes at a time and slow pointer
advancing by one node at a time
c) Cannot determine, you have to pre-define if the list contains cycles
d) Circular linked list itself represents a cycle. So no new cycles cannot be generated
View Answer
Answer: b
Explanation: Advance the pointers in such a way that the fast pointer advances two nodes at a time and slow
pointer advances one node at a time and check to see if at any given instant of time if the fast pointer points
to slow pointer or if the fast pointer’s ‘next’ points to the slow pointer. This is applicable for smaller lists.
1. What is the best case time complexity of deleting a node in a Singly Linked list?
a) O (n)
b) O (n2)
c) O (nlogn)
d) O (1)
View Answer
Answer: d
Explanation: Deletion of the head node in the linked list is taken as the best case. The successor of the head
node is changed to head and deletes the predecessor of the newly assigned head node. This process
completes in O(1) time.
2. Which of the following statements are not correct with respect to Singly Linked List(SLL) and Doubly
Linked List(DLL)?
a) Complexity of Insertion and Deletion at known position is O(n) in SLL and O(1) in DLL
b) SLL uses lesser memory per node than DLL
c) DLL has more searching power than SLL
d) Number of node fields in SLL is more than DLL
View Answer
Answer: d
Explanation: To insert and delete at known positions requires complete traversal of the list in worst case in
SLL, SLL consists of an item and a node field, while DLL has an item and two node fields, hence SLL
occupies lesser memory, DLL can be traversed both ways(left and right), while SLL can traverse in only one
direction, hence more searching power of DLL. Node fields in SLL is 2 (data and address of next node)
whereas in DLL is 3(data, address to next node, address to previous node).
Answer: b
Explanation: Adding items to a full stack is termed as stack underflow.
8. Consider these functions:
push() : push an element into the stack
pop() : pop the top-of-the-stack element
top() : returns the item stored in top-of-the-stack-node
What will be the output after performing these sequence of operations
push(20);
push(4);
top();
pop();
pop();
pop();
push(5);
top();
a) 20
b) 4
c) stack underflow
d) 5
View Answer
Answer: d
Explanation: 20 and 4 which were pushed are popped by the two pop() statements, the recent push() is 5,
hence top() returns 5.
9. Which of the following data structures can be used for parentheses matching?
a) n-ary tree
b) queue
c) priority queue
d) stack
View Answer
Answer: d
Explanation: For every opening brace, push it into the stack, and for every closing brace, pop it off the stack.
Do not take action for any other character. In the end, if the stack is empty, then the input has balanced
parentheses.
Answer: c
Explanation: Use one queue and one counter to count the number of elements in the queue.
1. In linked list implementation of queue, if only front pointer is maintained, which of the following
operation take worst case linear time?
a) Insertion
b) Deletion
c) To empty a queue
d) Both Insertion and To empty a queue
View Answer
Answer: d
Explanation: Since front pointer is used for deletion, so worst time for the other two cases.
Answer: c
Explanation: Since queue follows FIFO so new element inserted at last.
3. In linked list implementation of a queue, front and rear pointers are tracked. Which of these pointers will
change during an insertion into a NONEMPTY queue?
a) Only front pointer
b) Only rear pointer
c) Both front and rear pointer
d) No pointer will be changed
View Answer
Answer: b
Explanation: Since queue follows FIFO so new element inserted at last.
4. In linked list implementation of a queue, front and rear pointers are tracked. Which of these pointers will
change during an insertion into EMPTY queue?
a) Only front pointer
b) Only rear pointer
c) Both front and rear pointer
d) No pointer will be changed
View Answer
Answer: c
Explanation: Since its the starting of queue, so both values are changed.
5. In case of insertion into a linked queue, a node borrowed from the __________ list is inserted in the
queue.
a) AVAIL
b) FRONT
c) REAR
d) NULL
View Answer
Answer: a
Explanation: All the nodes are collected in AVAIL list.
advertisement
6. In linked list implementation of a queue, from where is the item deleted?
a) At the head of link list
b) At the centre position in the link list
c) At the tail of the link list
d) Node before the tail
View Answer
Answer: a
Explanation: Since queue follows FIFO so new element deleted from first.
7. In linked list implementation of a queue, the important condition for a queue to be empty is?
a) FRONT is null
b) REAR is null
c) LINK is empty
d) FRONT==REAR-1
View Answer
Answer: a
Explanation: Because front represents the deleted nodes.
8. The essential condition which is checked before insertion in a linked queue is?
a) Underflow
b) Overflow
c) Front value
d) Rear value
View Answer
Answer: b
Explanation: To check whether there is space in the queue or not.
9. The essential condition which is checked before deletion in a linked queue is?
a) Underflow
b) Overflow
c) Front value
d) Rear value
View Answer
Answer: a
Explanation: To check whether there is element in the list or not.
10. Which of the following is true about linked list implementation of queue?
a) In push operation, if new nodes are inserted at the beginning of linked list, then in pop operation, nodes
must be removed from end
b) In push operation, if new nodes are inserted at the beginning, then in pop operation, nodes must be
removed from the beginning
c) In push operation, if new nodes are inserted at the end, then in pop operation, nodes must be removed
from end
d) In push operation, if new nodes are inserted at the end, then in pop operation, nodes must be removed
from beginning
View Answer
Answer: a
Explanation: It can be done by both the methods.
1. With what data structure can a priority queue be implemented?
a) Array
b) List
c) Heap
d) Tree
View Answer
Answer: d
Explanation: Priority queue can be implemented using an array, a list, a binary search tree or a heap,
although the most efficient one being the heap.
Answer: c
Explanation: Undo operation is achieved using a stack.
4. What is the time complexity to insert a node based on key in a priority queue?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)
View Answer
Answer: c
Explanation: In the worst case, you might have to traverse the entire list.
Answer: c
Explanation: The lower priority process should wait until the CPU completes the processing higher priority
process. Interrupt handling is an advantage as interrupts should be given more priority than tasks at hand so
that interrupt can be serviced to produce desired results.
Answer: d
Explanation: In worst case, the entire queue has to be searched for the element having the highest priority.
This will take more time than usual. So deletion of elements is not an advantage.
8. What is the time complexity to insert a node based on position in a priority queue?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)
View Answer
Answer: c
Explanation: In the worst case, you might have to traverse the entire list.
1. What is a dequeue?
a) A queue with insert/delete defined for both front and rear ends of the queue
b) A queue implemented with a doubly linked list
c) A queue implemented with both singly and doubly linked lists
d) A queue with insert/delete defined for front side of the queue
View Answer
Answer: a
Explanation: A dequeue or a double ended queue is a queue with insert/delete defined for both front and rear
ends of the queue.
Answer: d
Explanation: All of the mentioned can be implemented with a dequeue.
7. What is the time complexity of deleting from the rear end of the dequeue implemented with a singly
linked list?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)
View Answer
Answer: c
Explanation: Since a singly linked list is used, first you have to traverse till the end, so the complexity is
O(n).
1. A linear list of elements in which deletion can be done from one end (front) and insertion can take place
only at the other end (rear) is known as _____________
a) Queue
b) Stack
c) Tree
d) Linked list
View Answer
Answer: a
Explanation: Linear list of elements in which deletion is done at front side and insertion at rear side is called
Queue. In stack we will delete the last entered element first.
2. The data structure required for Breadth First Traversal on a graph is?
a) Stack
b) Array
c) Queue
d) Tree
View Answer
Answer: c
Explanation: In Breadth First Search Traversal, BFS, starting vertex is first taken and adjacent vertices
which are unvisited are also taken. Again, the first vertex which was added as an unvisited adjacent vertex
list will be considered to add further unvisited vertices of the graph. To get the first unvisited vertex we need
to follows First In First Out principle. Queue uses FIFO principle.
Answer: a
Explanation: Element first added in queue will be deleted first which is FIFO principle.
Answer: a
Explanation: Circular Queue is also called as Ring Buffer. Circular Queue is a linear data structure in which
last position is connected back to the first position to make a circle. It forms a ring structure.
5. If the elements “A”, “B”, “C” and “D” are placed in a queue and are deleted one at a time, in what order
will they be removed?
a) ABCD
b) DCBA
c) DCAB
d) ABDC
View Answer
Answer: a
Explanation: Queue follows FIFO approach. i.e. First in First Out Approach. So, the order of removal
elements are ABCD.
6. A data structure in which elements can be inserted or deleted at/from both ends but not in the middle is?
a) Queue
b) Circular queue
c) Dequeue
d) Priority queue
Answer: c
Explanation: In dequeuer, we can insert or delete elements from both the ends. In queue, we will follow first
in first out principle for insertion and deletion of elements. Element with least priority will be deleted in a
priority queue.
7. A normal queue, if implemented using an array of size MAX_SIZE, gets full when?
a) Rear = MAX_SIZE – 1
b) Front = (rear + 1)mod MAX_SIZE
c) Front = rear + 1
d) Rear = front
View Answer
Answer: a
Explanation: When Rear = MAX_SIZE – 1, there will be no space left for the elements to be added in
queue. Thus queue becomes full.
Answer: c
Explanation: Simulation of recursion uses stack data structure. Simulation of arbitrary linked lists uses
linked lists. Simulation of resource allocation uses queue as first entered data needs to be given first priority
during resource allocation. Simulation of heap sort uses heap data structure.
Answer: b
Explanation: Queue always has two ends. So, single ended queue is not the type of queue.
Tree
1. How many children does a binary tree have?
a) 2
b) any number of children
c) 0 or 1 or 2
d) 0 or 1
View Answer
Answer: c
Explanation: Can have atmost 2 nodes.
Answer: c
Explanation: The size of array is fixed in normal arrays. We need to know the number of nodes in the tree
before array declaration. It is the main disadvantage of using arrays to represent binary trees.
3. What must be the ideal size of array if the height of tree is ‘l’?
a) 2l-1
b) l-1
c) l
d) 2l
View Answer
Answer: a
Explanation: Maximum elements in a tree (complete binary tree in worst case) of height ‘L’ is 2L-1. Hence
size of array is taken as 2L-1.
4. What are the children for node ‘w’ of a complete-binary tree in an array representation?
a) 2w and 2w+1
b) 2+w and 2-w
c) w+1/2 and w/2
d) w-1/2 and w+1/2
View Answer
Answer: a
Explanation: The left child is generally taken as 2*w whereas the right child will be taken as 2*w+1 because
root node is present at index 0 in the array and to access every index position in the array.
5. What is the parent for a node ‘w’ of a complete binary tree in an array representation when w is not 0?
a) floor(w-1/2)
b) ceil(w-1/2)
c) w-1/2
d) w/2
View Answer
Answer: a
Explanation: Floor of w-1/2 because we can’t miss a node.
6. If the tree is not a complete binary tree then what changes can be made for easy access of children of a
node in the array?
a) every node stores data saying which of its children exist in the array
b) no need of any changes continue with 2w and 2w+1, if node is at i
c) keep a seperate table telling children of a node
d) use another array parallel to the array with tree
View Answer
Answer: a
Explanation: Array cannot represent arbitrary shaped trees. It can only be used in case of complete trees. If
every node stores data saying that which of its children exists in the array then elements can be accessed
easily.
7. What must be the missing logic in place of missing lines for finding sum of nodes of binary tree in
alternate levels?
a)
i=i+pow(2,currentlevel);
currentlevel=currentlevel+2;
j=1;
b)
i=i+pow(2,currentlevel);
currentlevel=currentlevel+2;
j=0;
c)
i=i-pow(2,currentlevel);
currentlevel=currentlevel+2;
j=1;
d)
i=i+pow(2,currentlevel);
currentlevel=currentlevel+1;
j=1;
View Answer
Answer: a
Explanation: The i value must skip through all nodes in the next level and current level must be one+next
level.
8. Consider a situation of writing a binary tree into a file with memory storage efficiency in mind, is array
representation of tree is good?
a) yes because we are overcoming the need of pointers and so space efficiency
b) yes because array values are indexable
c) No it is not efficient in case of sparse trees and remaning cases it is fine
d) No linked list representation of tree is only fine
View Answer
Answer: c
Explanation: In case of sparse trees (where one node per level in worst cases), the array size (2h)-1 where h
is height but only h indexes will be filled and (2h)-1-h nodes will be left unused leading to space wastage.
9. Why is heap implemented using array representations than tree(linked list) representations though both
tree representations and heaps have same complexities?
for a tree
-insert: O(log n)
-delete: O(log n)
Then why go with array representation when both are having same values ?
a) arrays can store trees which are complete and heaps are not complete
b) lists representation takes more memory hence memory efficiency is less and go with arrays and arrays
have better caching
c) lists have better caching
d) In lists insertion and deletion is difficult
View Answer
Answer: b
Explanation: In memory the pointer address for next node may not be adjacent or nearer to each other and
also array have wonderful caching power from os and manipulating pointers is a overhead. Heap data
structure is always a complete binary tree.
10. Can a tree stored in an array using either one of inorder or post order or pre order traversals be again
reformed?
a) Yes just traverse through the array and form the tree
b) No we need one more traversal to form a tree
c) No in case of sparse trees
d) Yes by using both inorder and array elements
View Answer
Answer: b
Explanation: We need any two traversals for tree formation but if some additional stuff or techniques are
used while storing a tree in an array then one traversal can facilitate like also storing null values of a node in
array.
1. Advantages of linked list representation of binary trees over arrays?
a) dynamic size
b) ease of insertion/deletion
c) ease in randomly accessing a node
d) both dynamic size and ease in insertion/deletion
View Answer
Answer: d
Explanation: It has both dynamic size and ease in insertion and deletion as advantages.
Answer: d
Explanation: Random access is not possible with linked lists.
Answer: d
Explanation: Generally, all nodes in a tree are visited by using preorder, inorder and postorder traversing
algorithms.
Answer: a
Explanation: Level order is similar to bfs.
5. Identify the reason which doesn’t play a key role to use threaded binary trees?
a) The storage required by stack and queue is more
b) The pointers in most of nodes of a binary tree are NULL
c) It is Difficult to find a successor node
d) They occupy less size
View Answer
Answer: d
Explanation: Threaded binary trees are introduced to make the Inorder traversal faster without using any
stack or recursion. Stack and Queue require more space and pointers in the majority of binary trees are null
and difficulties are raised while finding successor nodes. Size constraints are not taken on threaded binary
trees, but they occupy less space than a stack/queue.
Join Sanfoundry@YouTube
6. The following lines talks about deleting a node in a binary tree.(the tree property must not be violated
after deletion)
i) from root search for the node to be deleted
ii)
iii) delete the node at
what must be statement ii) and fill up statement iii)
a) ii)-find random node,replace with node to be deleted. iii)- delete the node
b) ii)-find node to be deleted. iii)- delete the node at found location
c) ii)-find deepest node,replace with node to be deleted. iii)- delete a node
d) ii)-find deepest node,replace with node to be deleted. iii)- delete the deepest node
View Answer
Answer: d
Explanation: We just replace a to be deleted node with last leaf node of a tree. this must not be done in case
of BST or heaps.
7. What may be the psuedo code for finding the size of a tree?
a) find_size(root_node–>left_node) + 1 + find_size(root_node–>right_node)
b) find_size(root_node–>left_node) + find_size(root_node–>right_node)
c) find_size(root_node–>right_node) – 1
d) find_size(root_node–>left_node + 1
View Answer
Answer: a
Explanation: Draw a tree and analyze the expression. we are always taking size of left subtree and right
subtree and adding root value(1) to it and finally printing size.
8. What is missing in this logic of finding a path in the tree for a given sum (i.e checking whether there will
be a path from roots to leaf nodes with given sum)?
a) code for having recursive calls to either only left tree or right trees or to both subtrees depending on their
existence
b) code for having recursive calls to either only left tree or right trees
c) code for having recursive calls to either only left tree
d) code for having recursive calls to either only right trees
View Answer
Answer: a
Explanation: if(left subtree and right subtree) then move to both subtrees
else if only left subtree then move to left subtree carrying leftover_sum parameter
else if only right subtree then move to right subtree carrying leftover_sum parameter.
9. What must be the missing logic below so as to print mirror of a tree as below as an example?
if(rootnode):
mirror(rootnode-->left)
mirror(rootnode-->right)
//missing
end
Answer: a
Explanation: Mirror is another tree with left and right children of nodes are interchanged as shown in the
figure.
Answer: c
Explanation: We are checking if left or right node is what the argument sent or else if not the case then move
to left node or right node and print all nodes while searching for the argument node.
1. What is the maximum number of children that a binary tree node can have?
a) 0
b) 1
c) 2
d) 3
View Answer
Answer: c
Explanation: In a binary tree, a node can have atmost 2 nodes (i.e.) 0,1 or 2 left and right child.
a) Binary tree
b) Binary search tree
c) Fibonacci tree
d) AVL tree
View Answer
Answer: a
Explanation: The given tree is an example for binary tree since has got two children and the left and right
children do not satisfy binary search tree’s property, Fibonacci and AVL tree.
Answer: b
Explanation: A binary tree is a rooted tree and also an ordered tree (i.e) every node in a binary tree has at
most two children.
Answer: c
Explanation: Three common operations are performed in a binary tree- they are insertion, deletion and
traversal.
5. What is the traversal strategy used in the binary tree?
a) depth-first traversal
b) breadth-first traversal
c) random traversal
d) Priority traversal
View Answer
Answer: b
Explanation: Breadth first traversal, also known as level order traversal is the traversal strategy used in a
binary tree. It involves visiting all the nodes at a given level.
Answer: b
Explanation: Two kinds of insertion operation is performed in a binary tree- inserting a leaf node and
inserting an internal node.
Answer: c
Explanation: The above diagram is a depiction of deleting a node with 0 or 1 child since the node D which
has 1 child is deleted.
Answer: a
Explanation: General ordered tree can be mapped into binary tree by representing them in a left-child-right-
sibling way.
9. How many bits would a succinct binary tree occupy?
a) n+O(n)
b) 2n+O(n)
c) n/2
d) n
View Answer
Answer: b
Explanation: A succinct binary tree occupies close to minimum possible space established by lower bounds.
A succinct binary tree would occupy 2n+O(n) bits.
Answer: d
Explanation: The average depth of a binary tree is given as O(√N). In case of a binary search tree, it is O(log
N).
11. How many orders of traversal are applicable to a binary tree (In General)?
a) 1
b) 4
c) 2
d) 3
View Answer
Answer: d
Explanation: The three orders of traversal that can be applied to a binary tree are in-order, pre-order and post
order traversal.
12. If binary trees are represented in arrays, what formula can be used to locate a left child, if the node has
an index i?
a) 2i+1
b) 2i+2
c) 2i
d) 4i
View Answer
Answer: a
Explanation: If binary trees are represented in arrays, left children are located at indices 2i+1 and right
children at 2i+2.
Answer: b
Explanation: If a binary tree is represented in an array, parent nodes are found at indices (i-1)/2.
14. Which of the following properties are obeyed by all three tree – traversals?
a) Left subtrees are visited before right subtrees
b) Right subtrees are visited before left subtrees
c) Root node is visited before left subtree
d) Root node is visited before right subtree
View Answer
Answer: a
Explanation: In preorder, inorder and postorder traversal the left subtrees are visited before the right
subtrees. In Inorder traversal, the Left subtree is visited first then the Root node then the Right subtree. In
postorder traversal, the Left subtree is visited first, then Right subtree and then the Root node is visited.
a)
b)
c)
d)
View Answer
Answer: d
Explanation: Here,
Preorder Traversal is 1, 2, 5, 3, 4
Inorder Traversal is 2, 5, 1, 4, 3
Root node of binary tree is the first node in Preorder traversal.
The rough sketch of tree is:
Second node in preorder traversal is 2. This makes 5 as right child to node 2. The fourth node in preorder
traversal is 3. This makes 4 as right child to node 3. Thus the final tree is:
1. For the tree below, write the pre-order traversal.
a) 2, 7, 2, 6, 5, 11, 5, 9, 4
b) 2, 7, 5, 2, 6, 9, 5, 11, 4
c) 2, 5, 11, 6, 7, 4, 9, 5, 2
d) 2, 7, 5, 6, 11, 2, 5, 4, 9
View Answer
Answer: a
Explanation: Pre order traversal follows NLR(Node-Left-Right).
a) 2, 7, 2, 6, 5, 11, 5, 9, 4
b) 2, 7, 5, 2, 6, 9, 5, 11, 4
c) 2, 5, 11, 6, 7, 4, 9, 5, 2
d) 2, 7, 5, 6, 11, 2, 5, 4, 9
View Answer
Answer: c
Explanation: Post order traversal follows LRN(Left-Right-Node).
3. Select the code snippet which performs pre-order traversal.
a)
b)
c)
Join Sanfoundry@YouTube
public void preorder(Tree root)
{
System.out.println(root.data);
preorder(root.right);
preorder(root.left);
}
d)
b)
c)
d)
b)
c)
b)
d)
Answer: b
Explanation: Since you have to go through all the nodes, the complexity becomes O(n).
8. What is the space complexity of the post-order traversal in the recursive fashion? (d is the tree depth and n
is the number of nodes)
a) O(1)
b) O(nlogd)
c) O(logd)
d) O(d)
View Answer
Answer: d
Explanation: In the worst case we have d stack frames in the recursive call, hence the complexity is O(d).
Answer: b
Explanation: As the name itself suggests, pre-order traversal can be used.
10. Consider the following data. The pre order traversal of a binary tree is A, B, E, C, D. The in order
traversal of the same binary tree is B, E, A, D, C. The level order sequence for the binary tree is _________
a) A, C, D, B, E
b) A, B, C, D, E
c) A, B, C, E, D
d) D, B, E, A, C
View Answer
Answer: b
Explanation: The inorder sequence is B, E, A, D, C and Preorder sequence is A, B, E, C, D. The tree
11. Consider the following data and specify which one is Preorder Traversal Sequence, Inorder and
Postorder sequences.
S1: N, M, P, O, Q
S2: N, P, Q, O, M
S3: M, N, O, P, Q
a) S1 is preorder, S2 is inorder and S3 is postorder
b) S1 is inorder, S2 is preorder and S3 is postorder
c) S1 is inorder, S2 is postorder and S3 is preorder
d) S1 is postorder, S2 is inorder and S3 is preorder
View Answer
Answer: c
Explanation: Preorder traversal starts from the root node and postorder and inorder starts from the left child
node of the left subtree. The first node of S3 is different and for S1 and S2 it’s the same. Thus, S3 is
preorder traversal and the root node is M. Postorder traversal visits the root node at last. S2 has the root
node(M) at last that implies S2 is postorder traversal. S1 is inorder traversal as S2 is postorder traversal and
S3 is preorder traversal. Therefore, S1 is inorder traversal, S2 is postorder traversal and S3 is preorder
traversal
1. In postorder traversal of binary tree right subtree is traversed before visiting root.
a) True
b) False
View Answer
Answer: a
Explanation: Post-order method of traversing involves – i) Traverse left subtree in post-order, ii) Traverse
right subtree in post-order, iii) visit the root.
2. What is the possible number of binary trees that can be created with 3 nodes, giving the sequence N, M, L
when traversed in post-order.
a) 15
b) 3
c) 5
d) 8
View Answer
Answer: c
Explanation: 5 binary trees are possible and they are,
3. The post-order traversal of a binary tree is O P Q R S T. Then possible pre-order traversal will be
________
a) T Q R S O P
b) T O Q R P S
c) T Q O P S R
d) T Q O S P R
View Answer
Answer: c
Explanation: The last, second last nodes visited in post-order traversal are root and it’s right child
respectively. Option T Q R S O P can’t be a pre-order traversal, because nodes O, P are visited after the
nodes Q, R, S. Option T O Q R P S, can’t be valid, because the pre-order sequence given in option T O Q R
P S and given post-order traversal creates a tree with node T as root and node O as left subtree. Option T Q
O P S R is valid. Option T Q O S P R is not valid as node P is visited after visiting node S.
4. A binary search tree contains values 7, 8, 13, 26, 35, 40, 70, 75. Which one of the following is a valid
post-order sequence of the tree provided the pre-order sequence as 35, 13, 7, 8, 26, 70, 40 and 75?
a) 7, 8, 26, 13, 75, 40, 70, 35
b) 26, 13, 7, 8, 70, 75, 40, 35
c) 7, 8, 13, 26, 35, 40, 70, 75
d) 8, 7, 26, 13, 40, 75, 70, 35
View Answer
Answer: d
Explanation: The binary tree contains values 7, 8, 13, 26, 35, 40, 70, 75. The given pre-order sequence is 35,
13, 7, 8, 26, 70, 40 and 75. So, the binary search tree formed is
Thus post-order sequence for the tree is 8, 7, 26, 13, 40, 75, 70 and 35.
5. Which of the following pair’s traversals on a binary tree can build the tree uniquely?
a) post-order and pre-order
b) post-order and in-order
c) post-order and level order
d) level order and preorder
View Answer
Answer: b
Explanation: A binary tree can uniquely be created by post-order and in-order traversals.
advertisement
6. A full binary tree can be generated using ______
a) post-order and pre-order traversal
b) pre-order traversal
c) post-order traversal
d) in-order traversal
View Answer
Answer: a
Explanation: Every node in a full binary tree has either 0 or 2 children. A binary tree can be generated by
two traversals if one of them is in-order. But, we can generate a full binary tree using post-order and pre-
order traversals.
7. The maximum number of nodes in a tree for which post-order and pre-order traversals may be equal is
______
a) 3
b) 1
c) 2
d) any number
View Answer
Answer: b
Explanation: The tree with only one node has post-order and pre-order traversals equal.
8. The steps for finding post-order traversal are traverse the right subtree, traverse the left subtree or visit the
current node.
a) True
b) False
View Answer
Answer: b
Explanation: Left subtree is traversed first in post-order traversal, then the right subtree is traversed and then
the output current node.
9. The pre-order and in-order are traversals of a binary tree are T M L N P O Q and L M N T O P Q. Which
of following is post-order traversal of the tree?
a) L N M O Q P T
b) N M O P O L T
c) L M N O P Q T
d) O P L M N Q T
View Answer
Answer: a
Explanation: The tree generated by using given pre-order and in-order traversal is
Answer: b
Explanation: Consider a binary tree,
11. Find the postorder traversal of the binary tree shown below.
a) P Q R S T U V W X
b) W R S Q P V T U X
c) S W T Q X U V R P
d) S T W U X V Q R P
View Answer
Answer: c
Explanation: In postorder traversal the left subtree is traversed first and then the right subtree and then the
current node. So, the posturer traversal of the tree is, S W T Q X U V R P.
1. For the tree below, write the in-order traversal.
a) 6, 2, 5, 7, 11, 2, 5, 9, 4
b) 6, 5, 2, 11, 7, 4, 9, 5, 2
c) 2, 7, 2, 6, 5, 11, 5, 9, 4
d) 2, 7, 6, 5, 11, 2, 9, 5, 4
View Answer
Answer: a
Explanation: In-order traversal follows LNR(Left-Node-Right).
a) 2, 7, 2, 6, 5, 11, 5, 9, 4
b) 2, 7, 5, 2, 11, 9, 6, 5, 4
c) 2, 5, 11, 6, 7, 4, 9, 5, 2
d) 2, 7, 5, 6, 11, 2, 5, 4, 9
View Answer
Answer: b
Explanation: Level order traversal follows a breadth first search approach.
3. Select the code snippet which performs in-order traversal.
a)
b)
c)
d)
b)
c)
d)
5. What is the space complexity of the in-order traversal in the recursive fashion? (d is the tree depth and n is
the number of nodes)
a) O(1)
b) O(nlogd)
c) O(logd)
d) O(d)
View Answer
Answer: d
Explanation: In the worst case we have d stack frames in the recursive call, hence the complexity is O(d).
Answer: b
Explanation: Since you have to go through all the nodes, the complexity becomes O(n).
7. Which of the following graph traversals closely imitates level order traversal of a binary tree?
a) Depth First Search
b) Breadth First Search
c) Depth & Breadth First Search
d) Binary Search
View Answer
Answer: b
Explanation: Both level order tree traversal and breadth first graph traversal follow the principle that visit
your neighbors first and then move on to further nodes.
8. In a binary search tree, which of the following traversals would print the numbers in the ascending order?
a) Level-order traversal
b) Pre-order traversal
c) Post-order traversal
d) In-order traversal
View Answer
Answer: d
Explanation: In a binary search tree, a node’s left child is always lesser than the node and right child is
greater than the node, hence an in-order traversal would print them in a non decreasing fashion.
1. Which of the following is false about a binary search tree?
a) The left child is always lesser than its parent
b) The right child is always greater than its parent
c) The left and right sub-trees should also be binary search trees
d) In order sequence gives decreasing order of elements
View Answer
Answer: d
Explanation: In order sequence of binary search trees will always give ascending order of elements.
Remaining all are true regarding binary search trees.
b)
c)
3. What is the speciality about the inorder traversal of a binary search tree?
a) It traverses in a non increasing order
b) It traverses in an increasing order
c) It traverses in a random fashion
d) It traverses based on priority of the node
View Answer
Answer: b
Explanation: As a binary search tree consists of elements lesser than the node to the left and the ones greater
than the node to the right, an inorder traversal will give the elements in an increasing order.
a) Preorder traversal
b) Inorder traversal
c) Postorder traversal
d) Level order traversal
View Answer
Answer: c
Explanation: In a postorder traversal, first the left child is visited, then the right child and finally the parent.
5. What does the following piece of code do?
a) Preorder traversal
b) Inorder traversal
c) Postorder traversal
d) Level order traversal
View Answer
Answer: a
Explanation: In a preorder traversal, first the parent is visited, then the left child and finally the right child.
6. How will you find the minimum element in a binary search tree?
a)
b)
c)
d)
7. How will you find the maximum element in a binary search tree?
a)
b)
c)
d)
Answer: d
Explanation: Worst case arises when the tree is skewed(either to the left or right) in which case you have to
process all the nodes of the tree giving O(n) complexity, otherwise O(logn) as you process only the left half
or the right half of the tree.
9. Given that 2 elements are present in the tree, write a function to find the LCA(Least Common Ancestor)
of the 2 elements.
a)
b)
c)
10. What are the conditions for an optimal binary search tree and what is its advantage?
a) The tree should not be modified and you should know how often the keys are accessed, it improves the
lookup cost
b) You should know the frequency of access of the keys, improves the lookup time
c) The tree can be modified and you should know the number of elements in the tree before hand, it
improves the deletion time
d) The tree should be just modified and improves the lookup time
View Answer
Answer: a
Explanation: For an optimal binary search The tree should not be modified and we need to find how often
keys are accessed. Optimal binary search improves the lookup cost.
11. Construct a binary search tree with the below information.
The preorder traversal of a binary search tree 10, 4, 3, 5, 11, 12.
a)
b)
c)
d)
View Answer
Answer: c
Explanation: Preorder Traversal is 10, 4, 3, 5, 11, 12. Inorder Traversal of Binary search tree is equal to
ascending order of the nodes of the Tree. Inorder Traversal is 3, 4, 5, 10, 11, 12. The tree constructed using
Preorder and Inorder traversal is
1. What is an AVL tree?
a) a tree which is balanced and is a height balanced tree
b) a tree which is unbalanced and is a height balanced tree
c) a tree with three children
d) a tree with atmost 3 children
View Answer
Answer: a
Explanation: It is a self balancing tree with height difference atmost 1.
Answer: a
Explanation: In real world dealing with random values is often not possible, the probability that u are
dealing with non random values(like sequential) leads to mostly skew trees, which leads to worst case. hence
we make height balance by rotations.
i.
ii.
a) only i
b) only i and ii
c) only ii
d) i is not a binary search tree
View Answer
Answer: b
Explanation: The property of AVL tree is it is height balanced tree with difference of atmost 1 between left
and right subtrees. All AVL trees are binary search tree.
4. What is the maximum height of an AVL tree with p nodes?
a) p
b) log(p)
c) log(p)/2
d) p⁄2
View Answer
Answer: b
Explanation: Consider height of tree to be ‘he’, then number of nodes which totals to p can be written in
terms of height as N(he)=N(he-1)+1+N(he-2). since N(he) which is p can be written in terms of height as the
beside recurrence relation which on solving gives N(he)= O(logp) as worst case height.
5. To restore the AVL property after inserting a element, we start at the insertion point and move towards
root of that tree. is this statement true?
a) true
b) false
View Answer
Answer: a
Explanation: It is interesting to note that after insertion, only the path from that point to node or only that
subtrees are imbalanced interms of height.
Join Sanfoundry@YouTube
6. Given an empty AVL tree, how would you construct AVL tree when a set of numbers are given without
performing any rotations?
a) just build the tree with the given input
b) find the median of the set of elements given, make it as root and construct the tree
c) use trial and error
d) use dynamic programming to build the tree
View Answer
Answer: b
Explanation: Sort the given input, find the median element among them, make it as root and construct left
and right subtrees with elements lesser and greater than the median element recursively. this ensures the
subtrees differ only by height 1.
7. What maximum difference in heights between the leafs of a AVL tree is possible?
a) log(n) where n is the number of nodes
b) n where n is the number of nodes
c) 0 or 1
d) atmost 1
View Answer
Answer: a
Explanation: At every level we can form a tree with difference in height between subtrees to be atmost 1 and
so there can be log(n) such levels since height of AVL tree is log(n).
8. Consider the pseudo code:
if(left_tree_height== -1)
return left_tree_height
right_tree_height= avl(right_of_root)
if(right_tree_height==-1)
return right_tree_height
Does the above code can check if a binary search tree is an AVL tree?
a) yes
b) no
View Answer
Answer: a
Explanation: The condition to check the height difference between left and right subtrees is missing. if
(absolute(left_tree_height – right_tree_height)>1) must be added.
9. Consider the below left-left rotation pseudo code where the node contains value pointers to left, right
child nodes and a height value and Height() function returns height value stored at a particular node.
What is missing?
a) Height(w-left), x-height
b) Height(w-right), x-height
c) Height(w-left), x
d) Height(w-left)
View Answer
Answer: a
Explanation: In the code we are trying to make the left rotation and so we need to find maximum of those
two values.
Answer: b
Explanation: Every node in an AVL tree need to store the balance factor (-1, 0, 1) hence space costs to O(n),
n being number of nodes. but in red-black we can use the sign of number (if numbers being stored are only
positive) and hence save space for storing balancing information. there are even other reasons where
redblack is mostly prefered.
1. What is the special property of red-black trees and what root should always be?
a) a color which is either red or black and root should always be black color only
b) height of the tree
c) pointer to next node
d) a color which is either green or black
View Answer
Answer: a
Explanation: An extra attribute which is a color red or black is used. root is black because if it is red then
one of red-black tree property which states that number of black nodes from root to null nodes must be
same, will be violated.
Answer: a
Explanation: We impose such restrictions to achieve self balancing trees with logarithmic complexities for
insertions, deletions, search.
All the above formations are incorrect for it to be a redblack tree. then what may be the correct order?
a) 50-black root, 18-red left subtree, 100-red right subtree
b) 50-red root, 18-red left subtree, 100-red right subtree
c) 50-black root, 18-black left subtree, 100-red right subtree
d) 50-black root, 18-red left subtree, 100-black right subtree
View Answer
Answer: a
Explanation: Considering all the properties of red-black tree, 50 must be the black root and there are two
possibilities for subtrees. one is option “50-black root, 18-red left subtree, 100-red right subtree” and other is
making all nodes of the tree to be black.
4. What are the operations that could be performed in O(logn) time complexity by red-black tree?
a) insertion, deletion, finding predecessor, successor
b) only insertion
c) only finding predecessor, successor
d) for sorting
View Answer
Answer: a
Explanation: We impose restrictions to achieve logarithm time complexities.
impose restrictions are:
. root property is black
. every leaf is black
. children of red node are black
. all leaves have same black.
Answer: c
Explanation: RB tree is used for Linux kernel in the form of completely fair scheduler process scheduling
algorithm. It is used for faster insertions, retrievals.
advertisement
Answer: a
Explanation: Though both trees are balanced, when there are more insertions and deletions to make the tree
balanced, AVL trees should have more rotations, it would be better to use red-black. but if more search is
required AVL trees should be used.
7. Why Red-black trees are preferred over hash tables though hash tables have constant time complexity?
a) no they are not preferred
b) because of resizing issues of hash table and better ordering in redblack trees
c) because they can be implemented using trees
d) because they are balanced
View Answer
Answer: b
Explanation: Redblack trees have O(logn) for ordering elements in terms of finding first and next elements.
also whenever table size increases or decreases in hash table you need to perform rehashing which can be
very expensive in real time. also red black stores elements in sorted order rather than input order.
8. How can you save memory when storing color information in Red-Black tree?
a) using least significant bit of one of the pointers in the node for color information
b) using another array with colors of each node
c) storing color information in the node structure
d) using negative and positive numbering
View Answer
Answer: a
Explanation: The node pointers can be used to store color with the help of significant bits. the exceptions of
this method are in languages like java where pointers are not used this may not work.
Answer: a
Explanation: Red black when frequent inserts and deletes, AVL when less frequent inserts and deletes, B-
tree when using paging from a slow storage device.
10. What is the below pseudo code trying to do, where pt is a node pointer and root pointer?
Answer: a
Explanation: The code is taking the root node and to be inserted node and is performing insertion operation.
Graph
1. Which of the following statements for a simple graph is correct?
a) Every path is a trail
b) Every trail is a path
c) Every trail is a path as well as every path is a trail
d) Path and trail have no relation
Answer: a
Explanation: In a walk if the vertices are distinct it is called a path, whereas if the edges are distinct it is
called a trail.
a) B and E
b) C and D
c) A and E
d) C and B
Answer: d
Explanation: After removing either B or C, the graph becomes disconnected.
3. For the given graph(G), which of the following statements is true?
a) G is a complete graph
b) G is not a connected graph
c) The vertex connectivity of the graph is 2
d) The edge connectivity of the graph is 1
Answer: c
Explanation: After removing vertices B and C, the graph becomes disconnected.
Answer: b
Explanation: Number of ways in which every vertex can be connected to each other is nC2.
a) True
b) False
Answer: a
Explanation: In a regular graph, degrees of all the vertices are equal. In the given graph the degree of every
vertex is 3.
advertisement
6. In a simple graph, the number of edges is equal to twice the sum of the degrees of the vertices.
a) True
b) False
Answer: b
Explanation: The sum of the degrees of the vertices is equal to twice the number of edges.
Answer: b
Explanation: By euler’s formula the relation between vertices(n), edges(q) and regions(r) is given by n-
q+r=2.
8. If a simple graph G, contains n vertices and m edges, the number of edges in the Graph G'(Complement of
G) is ___________
a) (n*n-n-2*m)/2
b) (n*n+n+2*m)/2
c) (n*n-n-2*m)/2
d) (n*n-n+2*m)/2
Answer: a
Explanation: The union of G and G’ would be a complete graph so, the number of edges in G’= number of
edges in the complete form of G(nC2)-edges in G(m).
Answer: a
Explanation: A simple graph maybe connected or disconnected.
10. What is the maximum number of edges in a bipartite graph having 10 vertices?
a) 24
b) 21
c) 25
d) 16
Answer: c
Explanation: Let one set have n vertices another set would contain 10-n vertices.
Total number of edges would be n*(10-n), differentiating with respect to n, would yield the Answer.
11. Which of the following is true?
a) A graph may contain no edges and many vertices
b) A graph may contain many edges and no vertices
c) A graph may contain no edges and no vertices
d) A graph may contain no vertices and many edges
Answer: b
Explanation: A graph must contain at least one vertex.
12. For a given graph G having v vertices and e edges which is connected and has no cycles, which of the
following statements is true?
a) v=e
b) v = e+1
c) v + 1 = e
d) v = e-1
Answer: b
Explanation: For any connected graph with no cycles the equation holds true.
13. For which of the following combinations of the degrees of vertices would the connected graph be
eulerian?
a) 1,2,3
b) 2,3,4
c) 2,4,5
d) 1,3,5
Answer: a
Explanation: A graph is eulerian if either all of its vertices are even or if only two of its vertices are odd.
14. A graph with all vertices having equal degree is known as a __________
a) Multi Graph
b) Regular Graph
c) Simple Graph
d) Complete Graph
Answer: b
Explanation: The given statement is the definition of regular graphs.
Answer: c
Explanation: Adjacency Matrix, Adjacency List and Incidence Matrix are used to represent a graph.
1. The number of possible undirected graphs which may have self loops but no multiple edges and have n
vertices is ________
a) 2((n*(n-1))/2)
b) 2((n*(n+1))/2)
c) 2((n-1)*(n-1))/2)
d) 2((n*n)/2)
Answer: d
Explanation: There can be at most, n*n edges in an undirected graph.
2. Given a plane graph, G having 2 connected component, having 6 vertices, 7 edges and 4 regions. What
will be the number of connected components?
a) 1
b) 2
c) 3
d) 4
Answer: b
Explanation: Euler’s Identity says V – E + R = 1+ number of connected components.
3. Number of vertices with odd degrees in a graph having a eulerian walk is ________
a) 0
b) Can’t be predicted
c) 2
d) either 0 or 2
Answer: d
Explanation: If the start and end vertices for the path are same the Answer would be 0 otherwise 2.
Answer: b
Explanation: Statements iii) and v) are correct.
Answer: b
Explanation: Only paths and even cycles are bipartite graphs.
6. What is the number of vertices of degree 2 in a path graph having n vertices,here n>2.
a) n-2
b) n
c) 2
d) 0
Answer: a
Explanation: Only the first and the last vertex would have degree 1, others would be of degree 2.
Answer: a
Explanation: A trees is acyclic in nature.
Answer: d
Explanation: All three graphs are Complete graphs with 4 vertices.
9. In the given graph which edge should be removed to make it a Bipartite Graph?
a) A-C
b) B-E
c) C-D
d) D-E
Answer: a
Explanation: The resultant graph would be a Bipartite Graph having {A,C,E} and {D, B} as its subgroups.
10. What would the time complexity to check if an undirected graph with V vertices and E edges is Bipartite
or not given its adjacency matrix?
a) O(E*E)
b) O(V*V)
c) O(E)
d) O(V)
Answer: b
Explanation: A graph can be checked for being Bipartite by seeing if it is 2-colorable or not, which can be
obtained with the help of BFS.
1. Dijkstra’s Algorithm will work for both negative and positive weights?
a) True
b) False
Answer: b
Explanation: Dijkstra’s Algorithm assumes all weights to be non-negative.
2. A graph having an edge from each vertex to every other vertex is called a ___________
a) Tightly Connected
b) Strongly Connected
c) Weakly Connected
d) Loosely Connected
Answer: a
Explanation: This is a part of the nomenclature followed in Graph Theory.
3. What is the number of unlabeled simple directed graph that can be made with 1 or 2 vertices?
a) 2
b) 4
c) 5
d) 9
Answer: b
Explanation:
4. Floyd Warshall Algorithm used to solve the shortest path problem has a time complexity of __________
a) O(V*V)
b) O(V*V*V)
c) O(E*V)
d) O(E*E)
Answer: b
Explanation: The Algorithm uses Dynamic Programming and checks for every possible path.
Answer: b
Explanation: Same Graph may be drawn in different ways on paper.
advertisement
6. Assuming value of every weight to be greater than 10, in which of the following cases the shortest path of
a directed weighted graph from 2 vertices u and v will never change?
a) add all values by 10
b) subtract 10 from all the values
c) multiply all values by 10
d) in both the cases of multiplying and adding by 10
Answer: c
Explanation: In case of addition or subtraction the shortest path may change because the number of edges
between different paths may be different, while in case of multiplication path wont change.
7. What is the maximum possible number of edges in a directed graph with no self loops having 8 vertices?
a) 28
b) 64
c) 256
d) 56
Answer: d
Explanation: If a graph has V vertices than every vertex can be connected to a possible of V-1 vertices.
8. What would be the DFS traversal of the given Graph?
a) ABCED
b) AEDCB
c) EDCBA
d) ADECB
Answer: a
Explanation: In this case two Answers are possible including ADEBC.
10. What is the maximum number of edges present in a simple directed graph with 7 vertices if there exists
no cycles in the graph?
a) 21
b) 7
c) 6
d) 49
Answer: c
Explanation: If the no cycles exists then the difference between the number of vertices and edges is 1.
1. The number of elements in the adjacency matrix of a graph having 7 vertices is __________
a) 7
b) 14
c) 36
d) 49
Answer: d
Explanation: There are n*n elements in the adjacency matrix of a graph with n vertices.
2. What would be the number of zeros in the adjacency matrix of the given graph?
a) 10
b) 6
c) 16
d) 0
Answer: b
Explanation: Total number of values in the matrix is 4*4=16, out of which 6 entries are non zero.
Answer: a
Explanation: Only undirected graphs produce symmetric adjacency matrices.
4. The time complexity to calculate the number of edges in a graph whose information in stored in form of
an adjacency matrix is ____________
a) O(V)
b) O(E2)
c) O(E)
d) O(V2)
Answer: d
Explanation: As V entries are 0, a total of V2-V entries are to be examined.
5. For the adjacency matrix of a directed graph the row sum is the _________ degree and the column sum is
the ________ degree.
a) in, out
b) out, in
c) in, total
d) total, out
Answer: b
Explanation: Row number of the matrix represents the tail, while Column number represents the head of the
edge.
6. What is the maximum number of possible non zero values in an adjacency matrix of a simple graph with
n vertices?
a) (n*(n-1))/2
b) (n*(n+1))/2
c) n*(n-1)
d) n*(n+1)
Answer: c
Explanation: Out of n*n possible values for a simple graph the diagonal values will always be zero.
7. On which of the following statements does the time complexity of checking if an edge exists between two
particular vertices is not, depends?
a) Depends on the number of edges
b) Depends on the number of vertices
c) Is independent of both the number of edges and vertices
d) It depends on both the number of edges and vertices
Answer: c
Explanation: To check if there is an edge between to vertices i and j, it is enough to see if the value of A[i][j]
is 1 or 0, here A is the adjacency matrix.
8. In the given connected graph G, what is the value of rad(G) and diam(G)?
a) 2, 3
b) 3, 2
c) 2, 2
d) 3, 3
Answer: a
Explanation: Value of eccentricity for vertices A, C is 2 whereas for F, B, D, E it is 3.
Answer: d
Explanation: A simple graph must have no-self loops, should be undirected.
10. Given an adjacency matrix A = [ [0, 1, 1], [1, 0, 1], [1, 1, 0] ], The total no. of ways in which every
vertex can walk to itself using 2 edges is ________
a) 2
b) 4
c) 6
d) 8
Answer: c
Explanation: A2 = [ [2, 1, 1], [1, 2, 1], [1, 1, 2] ], all the 3 vertices can reach to themselves in 2 ways, hence a
total of 3*2, 6 ways.
11. If A[x+3][y+5] represents an adjacency matrix, which of these could be the value of x and y.
a) x=5, y=3
b) x=3, y=5
c) x=3, y=3
d) x=5, y=5
Answer: a
Explanation: All adjacency matrices are square matrices.
12. Two directed graphs(G and H) are isomorphic if and only if A=PBP-1, where P and A are adjacency
matrices of G and H respectively.
a) True
b) False
Answer: a
Explanation: This is a property of isomorphic graphs.
13. Given the following program, what will be the 3rd number that’d get printed in the output sequence for
the given input?
#include <bits/stdc++.h>
using namespace std;
int cur=0;
int G[10][10];
bool visited[10];
deque <int> q;
int main()
{
int num=0;
int n;
cin>>n;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
cin>>G[i][j];
for(int i=0;i<n;i++)
visited[i]=false;
fun(n);
return 0;
}
void fun(int n)
{
cout<<cur<<" ";
visited[cur]=true;
q.push_back(cur);
do
{
for(int j=0;j<n;j++)
{
if(G[cur][j]==1 && !visited[j])
{
q.push_back(j);
cout<<j<<" ";
visited[j]=true;
}
q.pop_front();
if(!q.empty())
cur=q.front();
}while(!q.empty());
}
Input Sequence:-
9
0 1 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0
0 0 0 1 1 1 0 0 1
0 0 1 0 0 0 0 0 0
0 0 1 0 0 0 0 1 0
0 0 1 0 0 0 1 0 0
0 0 0 0 0 1 0 1 1
0 0 0 0 1 0 1 0 0
1 0 1 0 0 0 1 0 0
a) 2
b) 6
c) 8
d) 4
Answer: c
Explanation: The given code performs the breadth first search routine on the Graph.
The sequence obtained would be 0 1 8 2 6 3 4 5 7.
14. For which type of graph, the given program won’t run infinitely? The Input would be in the form of an
adjacency Matrix and n is its dimension (1<n<10).
#include <bits/stdc++.h>
using namespace std;
int G[10][10];
void fun(int n);
int main()
{
int num=0;
int n;
cin>>n;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
cin>>G[i][j];
fun(n);
return 0;
}
void fun(int n)
{
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
if(G[i][j]==1)
j--;
}
Answer: b
Explanation: For any graph (except empty graph) having edges, the condition G[i][j]==1 would hold true,
which would result in an infinite loop.
15. Given the following adjacency matrix of a graph(G) determine the number of components in the G.
[0 1 1 0 0 0],
[1 0 1 0 0 0],
[1 1 0 0 0 0],
[0 0 0 0 1 0],
[0 0 0 1 0 0],
[0 0 0 0 0 0].
a) 1
b) 2
c) 3
d) 4
Answer: c
Explanation: 0th 1st and 2nd vertices form a component, 3rd and 4th forms another and 5th vertex forms a
component of a single vertex.
1. Space complexity for an adjacency list of an undirected graph having large values of V (vertices) and E
(edges) is ___________
a) O(E)
b) O(V*V)
c) O(E+V)
d) O(V)
Answer: c
Explanation: In an adjacency list for every vertex there is a linked list which have the values of the edges to
which it is connected.
2. For some sparse graph an adjacency list is more space efficient against an adjacency matrix.
a) True
b) False
Answer: a
Explanation: Space complexity for adjacency matrix is always O(V*V) while space complexity for
adjacency list in this case would be O(V).
Answer: a
Explanation: The maximum edges a vertex can have is V-1.
4. For the given conditions, which of the following is in the correct order of increasing space requirement?
i) Undirected, no weight
ii) Directed, no weight
iii) Directed, weighted
iv) Undirected, weighted
a) ii iii i iv
b) i iii ii iv
c) iv iii i ii
d) i ii iii iv
Answer: a
Explanation: i) takes v+4e, ii) takes v+2e, iii) takes v+3e, iv) takes v +6e space.
5. Space complexity for an adjacency list of an undirected graph having large values of V (vertices) and E
(edges) is __________
a) O(V)
b) O(E*E)
c) O(E)
d) O(E+V)
Answer: c
Explanation: In an adjacency list for every vertex there is a linked list which have the values of the edges to
which it is connected.
Join Sanfoundry@YouTube
6. Complete the given snippet of code for the adjacency list representation of a weighted directed graph.
class neighbor
{
int vertex, weight;
____ next;
}
class vertex
{
string name;
_____ adjlist;
}
vertex adjlists[101];
a) vertex, vertex
b) neighbor, vertex
c) neighbor, neighbor
d) vertex, neighbor
Answer: c
Explanation: Vertex would have a name and a linked list attached to it.
Answer: b
Explanation: In case of sparse graph most of the entries in the adjacency matrix would be 0, hence adjacency
list would be preferred.
Answer: a
Explanation: We can create a mapping from string to a vector, where string would be the name of the vertex
and vector would contains the name of the vertices to which it is connected.
9. What would be the time complexity of the following function which adds an edge between two vertices i
and j, with some weight ‘weigh’ to the graph having V vertices?
vector<int> adjacent[15] ;
vector<int> weight[15];
a) O(1)
b) O(V)
c) O(V*V)
d) O(log V)
Answer: a
Explanation: The function win in the constant time as all the four step takes constant time.
10. What would be the time complexity of the BFS traversal of a graph with n vertices and n1.25 edges?
a) O(n)
b) O(n1.25)
c) O(n2.25)
d) O(n*n)
Answer: b
Explanation: The time complexity for BFS is O(|V| + |E|) = O(n + n1.25) = O(n1.25).
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
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)
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
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.
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
d) Kruskal’s algorithm
Answer: b
Explanation: This is the definition of the Breadth First Search. Exploring a node, then it’s neighbors and so
on.
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
d) When the graph is a Ternary Tree
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
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.
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.
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
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.
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
Answer: a
Explanation: The Depth First Search is implemented using recursion. So, stack can be used as data structure
to implement depth first search.
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
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.
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
Answer: b
Explanation: When Every node will have one successor then the Depth 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 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
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.
Answer: c
Explanation: In Depth 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 stack.
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
c) pre order
d) in order
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
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).
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
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)
procedure DFS-non_recursive(G,v):
//let St be a stack
St.push(v)
while St is not empty
v = St.pop()
if v is not discovered:
label v as discovered
for all adjacent vertices of v do
St.push(a) //a being the adjacent vertex
b)
advertisement
procedure DFS-non_recursive(G,v):
//let St be a stack
St.pop()
while St is not empty
v = St.push(v)
if v is not discovered:
label v as discovered
for all adjacent vertices of v do
St.push(a) //a being the adjacent vertex
c)
procedure DFS-non_recursive(G,v):
//let St be a stack
St.push(v)
while St is not empty
v = St.pop()
if v is not discovered:
label v as discovered
for all adjacent vertices of v do
St.push(v)
d)
procedure DFS-non_recursive(G,v):
//let St be a stack
St.pop(v)
while St is not empty
v = St.pop()
if v is not discovered:
label v as discovered
for all adjacent vertices of v do
St.push(a) //a being the adjacent vertex
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=no.of
edges)?
a) O(V+E)
b) O(V)
c) O(E)
d) O(V*E)
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)
void DFS(int s)
{
vector<bool> discovered(V, true);
stack<int> st;
st.push(s);
while (!st.empty())
{
s = st.top();
st.pop();
if (!discovered[s])
{
cout << s << " ";
discovered[s] = true;
}
for (auto i = adjacent[s].begin(); i != adjacent[s].end(); ++i)
if (!discovered[*i])
st.push(*i);
}
}
b)
void DFS(int s)
{
vector<bool> discovered(V, false);
stack<int> st;
st.push(s);
while (!st.empty())
{
s = st.top();
st.pop();
if (!discovered[s])
{
cout << s << " ";
discovered[s] = true;
}
for (auto i = adjacent[s].begin(); i != adjacent[s].end(); ++i)
if (!discovered[*i])
st.push(*i);
}
}
c)
void DFS(int s)
{
vector<bool> discovered(V, false);
stack<int> st;
st.push(s);
while (!st.empty())
{
st.pop();
s = st.top();
if (!discovered[s])
{
cout << s << " ";
discovered[s] = true;
}
for (auto i = adjacent[s].begin(); i != adjacent[s].end(); ++i)
if (!discovered[*i])
st.push(*i);
}
}
d)
void DFS(int s)
{
vector<bool> discovered(V, false);
stack<int> st;
st.push(s);
while (!st.empty())
{
s = st.top();
st.pop();
if (!discovered[s])
{
cout << s << " ";
discovered[s] = false;
}
for (auto i = adjacent[s].begin(); i != adjacent[s].end(); ++i)
if (discovered[*i])
st.push(*i);
}
}
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)
c) O(E)
d) O(V*E)
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.
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
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
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.
Answer: a
Explanation: Branch and bound is a problem solving technique generally used for solving combinatorial
optimization problems. Branch and bound helps in solving them faster.
2. Which of the following is not a branch and bound strategy to generate branches?
a) LIFO branch and bound
b) FIFO branch and bound
c) Lowest cost branch and bound
d) Highest cost branch and bound
Answer: d
Explanation: LIFO, FIFO and Lowest cost branch and bound are different strategies to generate branches.
Lowest cost branch and bound helps us find the lowest cost path.
3. Which data structure is used for implementing a LIFO branch and bound strategy?
a) stack
b) queue
c) array
d) linked list
Answer: a
Explanation: Stack is the data structure is used for implementing LIFO branch and bound strategy. This
leads to depth first search as every branch is explored until a leaf node is discovered.
4. Which data structure is used for implementing a FIFO branch and bound strategy?
a) stack
b) queue
c) array
d) linked list
Answer: b
Explanation: Queue is the data structure is used for implementing FIFO branch and bound strategy.
Thisleads to breadth first search as every branch at depth is explored first before moving to the nodes at
greater depth.
5. Which data structure is most suitable for implementing best first branch and bound strategy?
a) stack
b) queue
c) priority queue
d) linked list
Answer: c
Explanation: Priority Queue is the data structure is used for implementing best first branch and bound
strategy. Dijkstra’s algorithm is an example of best first search algorithm.
6. Which of the following branch and bound strategy leads to breadth first search?
a) LIFO branch and bound
b) FIFO branch and bound
c) Lowest cost branch and bound
d) Highest cost branch and bound
Answer: b
Explanation: LIFO, FIFO and Lowest cost branch and bound are different strategies to generate branches.
FIFO branch and bound leads to breadth first search.
7. Which of the following branch and bound strategy leads to depth first search?
a) LIFO branch and bound
b) FIFO branch and bound
c) Lowest cost branch and bound
d) Highest cost branch and bound
Answer: a
Explanation: LIFO, FIFO and Lowest cost branch and bound are different strategies to generate branches.
LIFO branch and bound leads to depth first search.
8. Both FIFO branch and bound strategy and backtracking leads to depth first search.
a) true
b) false
Answer: b
Explanation: FIFO branch and bound leads to breadth first search. Whereas backtracking leads to depth first
search.
9. Both LIFO branch and bound strategy and backtracking leads to depth first search.
a) true
b) false
Answer: a
Explanation: Both backtrackings as well as branch and bound are problem solving algorithms. Both LIFO
branch and bound strategy and backtracking leads to depth first search.
10. Choose the correct statement from the following.
a) branch and bound is more efficient than backtracking
b) branch and bound is not suitable where a greedy algorithm is not applicable
c) branch and bound divides a problem into at least 2 new restricted sub problems
d) backtracking divides a problem into at least 2 new restricted sub problems
Answer: c
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.
11. Which of the following can traverse the state space tree only in DFS manner?
a) branch and bound
b) dynamic programming
c) greedy algorithm
d) backtracking
Answer: d
Explanation: Both backtracking as well as branch and bound are problem solving algorithms. Branch and
bound can traverse in DFS as well as BFS manner whereas backtracking only traverses in DFS manner.
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?
a) Judea Pearl
b) Max Bezzel
c) Franz Nauck
d) Alan Turing
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
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.
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
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.
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.
advertisement
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
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.
Answer: d
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. 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*
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.
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.
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.
Hash Table and Heap
1. What is a hash table?
a) A structure that maps values to keys
b) A structure that maps keys to values
c) A structure used for storage
d) A structure used to implement stack and queue
View Answer
Answer: b
Explanation: A hash table is used to implement associative arrays which has a key-value pair, so the has
table maps keys to values.
2. If several elements are competing for the same bucket in the hash table, what is it called?
a) Diffusion
b) Replication
c) Collision
d) Duplication
View Answer
Answer: c
Explanation: In a hash table, if sevaral elements are computing for the same bucket then there will be a clash
among elements. This condition is called Collision. The Collision is reduced by adding elements to a linked
list and head address of linked list is placed in hash table.
Answer: a
Explanation: Direct addressing is possible only when we can afford to allocate an array that has one position
for every possible key.
Answer: d
Explanation: Since every key has a unique array position, searching takes a constant time.
5. What is a hash function?
a) A function has allocated memory to keys
b) A function that computes the location of the key in the array
c) A function that creates an array
d) A function that computes the location of the values in the array
View Answer
Answer: b
Explanation: In a hash table, there are fewer array positions than the keys, so the position of the key in the
array has to be computed, this is done using the hash function.
Answer: d
Explanation: On increasing hash table size, space complexity will increase as we need to reallocate the
memory size of hash table for every collision. It is not the best technique to avoid a collision. We can avoid
collision by making hash function random, chaining method and uniform hashing.
Answer: c
Explanation: In simple chaining, load factor is the average number of elements stored in a chain, and is
given by the ratio of number of elements stored to the number of slots in the array.
Answer: a
Explanation: In simple uniform hashing, any given element is equally likely to hash into any of the slots
available in the array.
Answer: d
Explanation: There are two cases, once when the search is successful and when it is unsuccessful, but in
10. In simple chaining, what data structure is appropriate?
a) Singly linked list
b) Doubly linked list
c) Circular linked list
d) Binary trees
View Answer
Answer: b
Explanation: Deletion becomes easier with doubly linked list, hence it is appropriate.
Answer: c
Explanation: Universal hashing scheme uses a randomization approach whereas hashing by division and
hashing by multiplication are heuristic in nature.
Answer: a
Explanation: If the keys are known to be random real numbers k independently and uniformly distributed in
the range 0<=k<=1, the hash function which satisfies the condition of simple uniform hashing is
h(k)= lowerbound(km).
3. A good hash approach is to derive the hash value that is expected to be dependent of any patterns that
might exist in the data.
a) True
b) False
View Answer
Answer: b
Explanation: A hash value is expected to be unrelated or independent of any patterns in the distribution of
keys.
4. Interpret the given character string as an integer expressed in suitable radix notation.
Character string = pt
a) 14963
b) 14392
c) 12784
d) 14452
View Answer
Answer: d
Explanation: The given character string can be interpreted as (112,116) (Ascii values) then expressed as a
radix-128 integer, hence the value is 112*128 + 116 = 14452.
Answer: b
Explanation: In division method for creating hash functions, k keys are mapped into one of m slots by taking
the reminder of k divided by m.
Answer: a
Explanation: A prime number not too close to an exact power of 2 is often a good choice for m since it
reduces the number of collisions which are likely to occur.
Answer: b
Explanation: Universal hashing scheme provides better performance than other schemes because it uses a
unique randomisation approach.
8. Using division method, in a given hash table of size 157, the key of value 172 be placed at position ____
a) 19
b) 72
c) 15
d) 17
View Answer
Answer: c
Explanation: The key 172 can be placed at position 15 by using the formula
H(k) = k mod m
H(k) = 172 mod 157
H(k) = 15.
9. How many steps are involved in creating a hash function using a multiplication method?
a) 1
b) 4
c) 3
d) 2
View Answer
Answer: d
Explanation: In multiplication method 2 steps are involved. First multiplying the key value by a constant.
Then multiplying this value by m.
Answer: a
Explanation: The hash function can be computed by multiplying m with the fractional part of kA (kA mod
1) and then computing the floor value of the result.
Answer: c
Explanation: The value of m can be simply in powers of 2 since we can easily implement the function in
most computers. m=2p where p is an integer.
12. What is the table size when the value of p is 7 in multiplication method of creating hash functions?
a) 14
b) 128
c) 49
d) 127
View Answer
Answer: b
Explanation: In multiplication method of creating hash functions the table size can be taken in integral
13. What is the value of h(k) for the key 123456?
Given: p=14, s=2654435769, w=32
a) 123
b) 456
c) 70
d) 67
View Answer
Answer: d
Explanation: A = s/2w
A = 2654435769/ 232
k.A = 123456 * (2654435769/ 232)
= (76300 * 232) + 17612864
Hence r1= 76300; r0=17612864
Since w=14 the 14 most significant bits of r0 yield the value of h(k) as 67.
14. What is the average retrieval time when n keys hash to the same slot?
a) Theta(n)
b) Theta(n2)
c) Theta(nlog n)
d) Big-Oh(n2)
View Answer
Answer: a
Explanation: The average retrieval time when n keys hash to the same slot is given by Theta(n) as the
collision occurs in the hash table.
15. Collisions can be reduced by choosing a hash function randomly in a way that is independent of the keys
that are actually to be stored.
a) True
b) False
View Answer
Answer: a
Explanation: Because of randomization, the algorithm can behave differently on each execution, providing
good average case performance for any input.
1. In a max-heap, element with the greatest key is always in the which node?
a) Leaf node
b) First node of left sub tree
c) root node
d) First node of right sub tree
View Answer
Answer: c
Explanation: This is one of the property of max-heap that root node must have key greater than its children.
Answer: c
Explanation: The total possible operation in re locating the new location to a new element will be equal to
height of the heap.
4. The worst case complexity of deleting any arbitrary node value element from heap is __________
a) O(logn)
b) O(n)
c) O(nlogn)
d) O(n2)
View Answer
Answer: a
Explanation: The total possible operation in deleting the existing node and re locating new position to all its
connected nodes will be equal to height of the heap.
advertisement
Answer: a
Explanation: The property of heap that the value of root must be either greater or less than both of its
children makes it work like a priority queue.
6. If we implement heap as min-heap, deleting root node (value 1)from the heap. What would be the value of
root node after second iteration if leaf node (value 100) is chosen to replace the root at start.
a) 2
b) 100
c) 17
d) 3
View Answer
Answer: a
Explanation: As the root is deleted and node with value 100 is used as replaced one. There is a violation of
property that root node must have value less than its children. So there will be shuffling of node with value
7. If we implement heap as maximum heap , adding a new node of value 15 to the left most node of right
subtree. What value will be at leaf nodes of the right subtree of the heap.
a) 15 and 1
b) 25 and 1
c) 3 and 1
d) 2 and 3
View Answer
Answer: a
Explanation: As 15 is less than 25 so there would be no violation and the node will remain at that position.
So leaf nodes with value 15 and 1 will be at the position in right sub tree.
8. An array consists of n elements. We want to create a heap using the elements. The time complexity of
building a heap will be in order of
a) O(n*n*logn)
b) O(n*logn)
c) O(n*n)
d) O(n *logn *logn)
View Answer
Answer: b
Explanation: The total time taken will be N times the complexity of adding a single element to the heap.
And adding a single element takes logN time, so That is equal to N*logN.
Answer: a
Explanation: Descending priority queue arranges the elements based on their priority or value and allows
removing the elements in descending order. So, it can be efficiently implemented using max heap.
Answer: a
Explanation: In min heap, the insertion and deletion operation takes O(logn) time. Therefore, a selection sort
with n insertions and n deletions can be implemented using a min heap in O(nlogn) operations.
3. Which of the following is the valid min heap?
a)
b)
c)
d)
View Answer
Answer: d
Explanation: In min heap the smallest is located at the root and the largest elements are located at the leaf
nodes. So, all leaf nodes need to be checked to find the largest element.
4. The procedure given below is used to maintain min-order in the min heap. Find out the missing
statements, represented as X.
procedure TrickleDownMin(i)
if A[i] has children then
m := index of smallest of the children
or grandchildren (if any) of A[i]
if A[m] is a grandchild of A[i] then
if A[m] < A[i] then
swap A[i] and A[m]
X: _______________________
____________________
endif
TrickleDownMin(m)
endif
else //{A[m] is a child of A[i]}
if A[m] < A[i] then
swap A[i] and A[m]
endif
endif
Answer: a
Explanation: In TrickleDownMin() procedure, we maintain the min-ordering of the min heap. In this
procedure, we locate the lowest child or grandchild of the element at positions i. If the lowest element is
grandchild then we check that it is smaller than both, its parent and A[i].
5. The ascending 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: b
Explanation: The min heap is also known as ascending heap. Min heap of size n is an almost complete
binary tree of n nodes such that the element at each node is greater than or equal to the element at its parent
node.
6. The procedure FindMin() to find the minimum element and the procedure DeleteMin() to delete the
minimum element in min heap take _________
a) logarithmic and linear time constant respectively
b) constant and linear time respectively
c) constant and quadratic time respectively
d) constant and logarithmic time respectively
View Answer
Answer: d
Explanation: In the min heap, the root is the maximum element in the tree. So, locating it takes constant
time, but deleting it takes logarithmic time. Because after deleting it, the root is replaced with last element
and then the procedure to maintain the min ordering is invoked.
7. Which one of the following array elements represents a binary min heap?
a) 12 10 8 25 14 17
b) 8 10 12 25 14 17
c) 25 17 14 12 10 8
d) 14 17 25 10 12 8
View Answer
Answer: b
Explanation: A tree is min heap when data at every node in the tree is smaller than or equal to it’s children’ s
data. So, only 8 10 12 25 14 17 generates required tree.
8. In a binary min heap containing n elements, the largest element can be found in __________ time.
a) O(n)
b) O(nlogn)
c) O(logn)
d) O(1)
View Answer
Answer: a
Explanation: In min heap the smallest is located at the root and the largest elements are located at the leaf
nodes. So, all leaf nodes need to be checked to find the largest element. Thus, worst case time will be O (n).
9. Min heap is a complete binary tree.
a) True
b) False
View Answer
Answer: a
Explanation: A tree, in which all levels are fully filled, except possibly the last level, is called as the
complete binary tree. And min heap maintains shape property, so it is a complete binary tree. The shape
property ensures that all levels in the min heap are fully filled, except the last one, and, if the last level is not
filled completely, then fill the elements from left to right.
10. What will be the position of 5, when a max heap is constructed on the input elements 5, 70, 45, 7, 12, 15,
13, 65, 30, 25?
a) 5 will be at root
b) 5 will be at last level
c) 5 will be at second level
d) 5 can be anywhere in heap
View Answer
Answer: b
Explanation: In max heap the greatest element is at the root and the smallest elements are at the last level.
As 5 is the smallest input element, it will be at the last level.
Answer: a
Explanation: Primary collision occurs due to linear probing technique. It is overcome using a quadratic
probing technique.
2. How many probes are required on average for insertion and successful search?
a) 4 and 10
b) 2 and 6
c) 2.5 and 1.5
d) 3.5 and 1.5
View Answer
Answer: c
Explanation: Using formula, the average number of probes required for insertion is 2.5 and for a successful
search, it is 1.5.
3. What is the load factor for an open addressing technique?
a) 1
b) 0.5
c) 1.5
d) 0
View Answer
Answer: b
Explanation: The load factor for an open addressing technique should be 0.5. For separate chaining
technique, the load factor is 1.
4. Which of the following is not a collision resolution strategy for open addressing?
a) Linear probing
b) Quadratic probing
c) Double hashing
d) Rehashing
View Answer
Answer: d
Explanation: Linear probing, quadratic probing and double hashing are all collision resolution strategies for
open addressing whereas rehashing is a different technique.
5. In linear probing, the cost of an unsuccessful search can be used to compute the average cost of a
successful search.
a) True
b) False
View Answer
Answer: a
Explanation: Using random collision resolution algorithm, the cost of an unsuccessful search can be used to
compute the average cost of a successful search.
6. Which of the following is the correct function definition for linear probing?
a) F(i)= 1
b) F(i)=i
c) F(i)=i2
d) F(i)=i+1
View Answer
Answer: b
Explanation: The function used in linear probing is defined as, F(i)=I where i=0,1,2,3….,n.
7. ___________ is not a theoretical problem but actually occurs in real implementations of probing.
a) Hashing
b) Clustering
c) Rehashing
d) Collision
View Answer
Answer: b
Explanation: Clustering is not a theoretical problem but it occurs in implementations of hashing. Rehashing
is a kind of hashing.
8. What is the hash function used in linear probing?
a) H(x)= key mod table size
b) H(x)= (key+ F(i2)) mod table size
c) H(x)= (key+ F(i)) mod table size
d) H(x)= X mod 17
View Answer
Answer: c
Explanation: The hash function used in linear probing is defined to be H(x)= (key+ F(i)) mod table size
where i=0,1,2,3,…,n.
Answer: a
Explanation: If misspelling detection is important, an entire dictionary can be pre-hashed and words can be
checked in constant time.
10. In the following given hash table, use linear probing to find the location of 49.
0
1
2
3
4
5
6
7
8 18
9 89
a) 7
b) 6
c) 2
d) 0
View Answer
Answer: d
Explanation: Initially, collision occurs while hashing 49 for the first time.
Hence, after setting f(i)=1, the hashed location is found to be 0.
11. What is the formula to find the expected number of probes for an unsuccessful search in linear probing?
a) 121+1(1−⅄)
b) 121+1(1−⅄)2
c) 121+1(1+⅄)
d) 121+1(1+⅄)(1−⅄)
View Answer
Answer: b
Explanation: The mathematical formula for calculating the number of probes for an unsuccessful search is
121+1(1−⅄)2. For insertion, it is 121+1(1−⅄)
Greedy Algo
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 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.
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.
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)
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.
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
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.
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
Assuming items to be indivisible- In this case we will have to leave one item due to insufficient capacity.
Final volume = 60 + 20 = 80.
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
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.
Answer: c
Explanation: In an ASCII character set, seven bits are reserved for character representation while the eighth
bit is a parity bit.
4. How many bits are needed for standard encoding if the size of the character set is X?
a) log X
b) X+1
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.
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.
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
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.
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 lengths, the encoding where no character code is the
prefix of another character code is called prefix encoding.
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
Answer: d
Explanation: If the implementation of the priority queue is done using linked lists, the running time of
Huffman algorithm is O(C2).
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.
Answer: b
Explanation: Minimum spanning tree is a spanning tree with the lowest cost among all the spacing trees.
Sum of all of 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.
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?
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 minimum spanning trees.
6. Consider a undirected graph G with vertices { A, B, C, D, E}. In graph G, every edge has distinct weight.
Edge CD is edge 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.
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.
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)
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.
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.
1. Kruskal’s algorithm is used to ______
a) find minimum spanning tree
b) find single source shortest path
c) find all pair shortest path algorithm
d) traverse the graph
View Answer
Answer: a
Explanation: The Kruskal’s algorithm is used to find the minimum spanning tree of the connected graph. It
construct the MST by finding the edge having the least possible weight that connects two trees in the forest.
Answer: c
Explanation: Kruskal’s algorithm uses a greedy algorithm approach to find the MST of the connected
weighted graph. In the greedy method, we attempt to find an optimal solution in stages.
What is the weight of the minimum spanning tree using the Kruskal’s algorithm?
a) 24
b) 23
c) 15
d) 19
View Answer
Answer: d
Explanation: Kruskal’s algorithm constructs the minimum spanning tree by constructing by adding the edges
to spanning tree one-one by one. The MST for the given graph is,
Answer: b
Explanation: Kruskal’s algorithm involves sorting of the edges, which takes O(E logE) time, where E is a
number of edges in graph and V is the number of vertices. After sorting, all edges are iterated and union-find
algorithm is applied. union-find algorithm requires O(logV) time. So, overall Kruskal’s algorithm requires
O(E log V) time.
5. Consider the following graph. Using Kruskal’s algorithm, which edge will be selected first?
a) GF
b) DE
c) BE
d) BG
View Answer
Answer: c
Explanation: In Krsuskal’s algorithm the edges are selected and added to the spanning tree in increasing
order of their weights. Therefore, the first edge selected will be the minimal one. So, correct option is BE.
advertisement
6. Which of the following edges form minimum spanning tree on the graph using kruskals algorithm?
a) (B-E)(G-E)(E-F)(D-F)
b) (B-E)(G-E)(E-F)(B-G)(D-F)
c) (B-E)(G-E)(E-F)(D-E)
d) (B-E)(G-E)(E-F)(D-F)(D-G)
View Answer
Answer: a
Explanation: Using Krushkal’s algorithm on the given graph, the generated minimum spanning tree is
shown below.
Answer: b
Explanation: Prim’s algorithm iterates from one node to another, so it can not be applied for disconnected
graph. Kruskal’s algorithm can be applied to the disconnected graphs to construct the minimum cost forest.
Kruskal’s algorithm is comparatively easier and simpler than prim’s algorithm.
8. Which of the following is false about the Kruskal’s algorithm?
a) It is a greedy algorithm
b) It constructs MST by selecting edges in increasing order of their weights
c) It can accept cycles in the MST
d) It uses union-find data structure
View Answer
Answer: c
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.
9. Kruskal’s algorithm is best suited for the dense graphs than the prim’s algorithm.
a) True
b) False
View Answer
Answer: b
Explanation: Prim’s algorithm outperforms the Kruskal’s algorithm in case of the dense graphs. It is
significantly faster if graph has more edges than the Kruskal’s algorithm.
Answer: d
Explanation: In Kruskal’s algorithm, the disjoint-set data structure efficiently identifies the components
containing a vertex and adds the new edges. And Kruskal’s algorithm always finds the MST for the
connected graph.
Answer: a
Explanation: Steps in Prim’s algorithm: (I) Select any vertex of given graph and add it to MST (II) Add the
edge of minimum weight from a vertex not in MST to the vertex in MST; (III) It MST is complete the stop,
otherwise go to step (II).
2. Consider the given graph.
What is the weight of the minimum spanning tree using the Prim’s algorithm,starting from vertex a?
a) 23
b) 28
c) 27
d) 11
View Answer
Answer: c
Explanation: In Prim’s algorithm, we select a vertex and add it to the MST. Then we add the minimum edge
from the vertex in MST to vertex not in MST. From, figure shown below weight of MST = 27.
3. Worst case is the worst case time complexity of Prim’s algorithm if adjacency matrix is used?
a) O(log V)
b) O(V2)
c) O(E2)
d) O(V log E)
View Answer
Answer: b
Explanation: Use of adjacency matrix provides the simple implementation of the Prim’s algorithm. In Prim’s
algorithm, we need to search for the edge with a minimum for that vertex. So, worst case time complexity
will be O(V2), where V is the number of vertices.
Answer: b
Explanation: Prim’s algorithm uses a greedy algorithm approach to find the MST of the connected weighted
graph. In greedy method, we attempt to find an optimal solution in stages.
5. Prim’s algorithm resembles Dijkstra’s algorithm.
a) True
b) False
View Answer
Answer: a
Explanation: In Prim’s algorithm, the MST is constructed starting from a single vertex and adding in new
edges to the MST that link the partial tree to a new vertex outside of the MST. And Dijkstra’s algorithm also
rely on the similar approach of finding the next closest vertex. So, Prim’s algorithm resembles Dijkstra’s
algorithm.
6. Kruskal’s algorithm is best suited for the sparse graphs than the prim’s algorithm.
a) True
b) False
View Answer
Answer: a
Explanation: Prim’s algorithm and Kruskal’s algorithm perform equally in case of the sparse graphs. But
Kruskal’s algorithm is simpler and easy to work with. So, it is best suited for sparse graphs.
Which of the following edges form the MST of the given graph using Prim’a algorithm, starting from vertex
4.
a) (4-3)(5-3)(2-3)(1-2)
b) (4-3)(3-5)(5-1)(1-2)
c) (4-3)(3-5)(5-2)(1-5)
d) (4-3)(3-2)(2-1)(1-5)
View Answer
Answer: d
Explanation: The MST for the given graph using Prim’s algorithm starting from vertex 4 is,
Answer: d
Explanation: The Prim’s algorithm was developed by Vojtěch Jarník and it was latter discovered by the duo
Prim and Dijkstra. Therefore, Prim’s algorithm is also known as DJP Algorithm.
9. Prim’s algorithm can be efficiently implemented using _____ for graphs with greater density.
a) d-ary heap
b) linear search
c) fibonacci heap
d) binary search
View Answer
Answer: a
Explanation: In Prim’s algorithm, we add the minimum weight edge for the chosen vertex which requires
searching on the array of weights. This searching can be efficiently implemented using binary heap for
dense graphs. And for graphs with greater density, Prim’s algorithm can be made to run in linear time using
d-ary heap(generalization of binary heap).
Answer: b
Explanation: Prim’s algorithm can be implemented using Fibonacci heap and it never accepts cycles. And
Prim’s algorithm follows greedy approach. Prim’s algorithms span from one vertex to another.
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.
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.
Answer: b
Explanation: Dijkstra’s Algorithm cannot be applied on graphs having negative weight function because
calculation 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)
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);
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.
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
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.
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.
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.
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
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.
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.
1. You are given an array of elements where each array element represents the MAXIMUM number of
jumps that can be made in the forward direction from that element. You have to find the minimum number
of jumps that are required to reach the end of the array. Which of these methods can be used to solve the
problem?
a) Dynamic Programming
b) Greedy Algorithm
c) Recursion
d) Recursion and Dynamic Programming
View Answer
Answer: d
Explanation: Both recursion and dynamic programming can be used to solve minimum number of jumps
problem.
2. Consider the following array:
{1, 3, 5, 8, 9, 2, 6, 7, 6}
What is the minimum number of jumps required to reach the end of the array?
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: c
Explanation: The jumps made will be:{1 -> 2 -> 4 -> 9}. So, the number of jumps is three.
#include<stdio.h>
#include<limits.h>
int min_jumps(int *arr, int strt, int end)
{
int idx;
if(strt == end)
return 0;
if(arr[strt] == 0) // jump cannot be made
return INT_MAX;
int min = INT_MAX;
for(idx = 1; idx <= arr[strt] && strt + idx <= end; idx++)
{
int jumps = min_jumps(____,____,____) + 1;
if(jumps < min)
min = jumps;
}
return min;
}
int main()
{
int arr[] ={1, 3, 5, 8, 9, 2, 6, 7, 6},len = 9;
int ans = min_jumps(arr, 0, len-1);
printf("%d\n",ans);
return 0;
}
Which of these arguments should be passed by the min_jumps function represented by the blanks?
a) arr, strt + idx, end
b) arr + idx, strt, end
c) arr, strt, end
d) arr, strt, end + idx
View Answer
Answer: a
Explanation: arr, strt + idx, end should be passed as arguments.
4. For a given array, there can be multiple ways to reach the end of the array using minimum number of
jumps.
a) True
b) False
View Answer
Answer: a
Explanation: Consider the array {1,2,3,4,5}. It is possible to reach the end in the following ways: {1 -> 2 ->
3 -> 5} or {1 -> 2 -> 4 -> 5}.
5. What is the output of the following program?
#include<stdio.h>
#include<limits.h>
int min_jumps(int *arr, int strt, int end)
{
int idx;
if(strt == end)
return 0;
if(arr[strt] == 0) // jump cannot be made
return INT_MAX;
int min = INT_MAX;
for(idx = 1; idx <= arr[strt] && strt + idx <= end; idx++)
{
int jumps = min_jumps(arr, strt + idx, end) + 1;
if(jumps < min)
min = jumps;
}
return min;
}
int main()
{
int arr[] ={1, 2, 3, 4, 5, 4, 3, 2, 1},len = 9;
int ans = min_jumps(arr, 0, len-1);
printf("%d\n",ans);
return 0;
}
a) 4
b) 5
c) 6
d) 7
View Answer
Answer: a
Explanation: The program prints the minimum number of jumps required to reach the end of the array. One
way reach the end using minimum number of jumps is
{1 -> 2 -> 4 -> 8 -> 9}. So, the number of jumps is 4.
6. For any array, given that at most one element is non-zero, it is ALWAYS possible to reach the end of the
array using minimum jumps.
a) True
b) False
View Answer
Answer: b
Explanation: Consider the array {1,0,2,3,4}.
In this case, only one element is 0 but it is not possible to reach the end of the array.
7. Consider the following dynamic programming implementation of the minimum jumps problem:
#include<stdio.h>
#include<limits.h>
int min_jump(int *arr, int len)
{
int j, idx, jumps[len];
jumps[len - 1] = 0;
for(idx = len - 2; idx >= 0; idx--)
{
int tmp_min = INT_MAX;
for(j = 1; j <= arr[idx] && idx + j < len; j++)
{
if(jumps[idx + j] + 1 < tmp_min)
tmp_min = jumps[idx + j] + 1;
}
jumps[idx] = tmp_min;
}
return jumps[0];
}
int main()
{
int arr[] ={1, 1, 1, 1, 1, 1, 1, 1, 1},len = 9;
int ans = min_jump(arr,len);
printf("%d\n",ans);
return 0;
}
Which of the following “for” loops can be used instead of the inner for loop so that the output doesn’t
change?
a) for(j = 1; j < arr[idx] + len; j++)
b) for(j = 0; j < arr[idx] – len; j++)
c) for(j = idx + 1; j < len && j <= arr[idx] + idx; j++)
d) No change is required
View Answer
Answer: d
Explanation: None of the above mentioned “for” loops can be used instead of the inner for loop. Note, for(j
= idx + 1; j < len && j <= arr[idx] + idx; j++) covers the same range as the inner for loop but it produces the
wrong output because the indexing inside the loops changes as “j” takes different values in the two “for”
loops.
]
8. What is the time complexity of the following dynamic programming implementation used to find the
minimum number of jumps?
#include<stdio.h>
#include<limits.h>
int min_jump(int *arr, int len)
{
int j, idx, jumps[len];
jumps[len - 1] = 0;
for(idx = len - 2; idx >= 0; idx--)
{
int tmp_min = INT_MAX;
for(j = 1; j <= arr[idx] && idx + j < len; j++)
{
if(jumps[idx + j] + 1 < tmp_min)
tmp_min = jumps[idx + j] + 1;
}
jumps[idx] = tmp_min;
}
return jumps[0];
}
int main()
{
int arr[] ={1, 1, 1, 1, 1, 1, 1, 1, 1},len = 9;
int ans = min_jump(arr,len);
printf("%d\n",ans);
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) None of the mentioned
View Answer
Answer: c
Explanation: The time complexity of the above dynamic programming implementation is O(n2).
9. What is the space complexity of the following dynamic programming implementation used to find the
minimum number of jumps?
#include<stdio.h>
#include<limits.h>
int min_jump(int *arr, int len)
{
int j, idx, jumps[len];
jumps[len - 1] = 0;
for(idx = len - 2; idx >= 0; idx--)
{
int tmp_min = INT_MAX;
for(j = 1; j <= arr[idx] && idx + j < len; j++)
{
if(jumps[idx + j] + 1 < tmp_min)
tmp_min = jumps[idx + j] + 1;
}
jumps[idx] = tmp_min;
}
return jumps[0];
}
int main()
{
int arr[] ={1, 1, 1, 1, 1, 1, 1, 1, 1},len = 9;
int ans = min_jump(arr,len);
printf("%d\n",ans);
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(5)
View Answer
Answer: b
Explanation: The space complexity of the above dynamic programming implementation is O(n).
10. What is the output of the following program?
#include<stdio.h>
#include<limits.h>
int min_jump(int *arr, int len)
{
int j, idx, jumps[len];
jumps[len - 1] = 0;
for(idx = len - 2; idx >= 0; idx--)
{
int tmp_min = INT_MAX;
for(j = 1; j <= arr[idx] && idx + j < len; j++)
{
if(jumps[idx + j] + 1 < tmp_min)
tmp_min = jumps[idx + j] + 1;
}
jumps[idx] = tmp_min;
}
return jumps[0];
}
int main()
{
int arr[] ={1, 1, 1, 1, 1, 1, 1, 1, 1},len = 9;
int ans = min_jump(arr,len);
printf("%d\n",ans);
return 0;
}
a) 7
b) 8
c) 9
d) 10
View Answer
Answer: b
Explanation: The program prints the minimum jumps required to reach the end of the array, which is 8 and
so the output is 8.
11. What is the output of the following program?
#include<stdio.h>
#include<limits.h>
int min_jump(int *arr, int len)
{
int j, idx, jumps[len];
jumps[len - 1] = 0;
for(idx = len - 2; idx >= 0; idx--)
{
int tmp_min = INT_MAX;
for(j = 1; j <= arr[idx] && idx + j < len; j++)
{
if(jumps[idx + j] + 1 < tmp_min)
tmp_min = jumps[idx + j] + 1;
}
jumps[idx] = tmp_min;
}
return jumps[0];
}
int main()
{
int arr[] ={9, 9, 9, 9, 9, 9, 9, 9, 9},len = 9;
int ans = min_jump(arr,len);
printf("%d\n",ans);
return 0;
}
a) 1
b) 6
c) 2
d) 7
View Answer
Answer: a
Explanation: The program prints the minimum jumps required to reach the end of the array, which is 1 and
so the output is 1.
Divied and Conquer
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)
{
return recursive(arr,mid+1,high,key);
}
else
{
return recursive(arr,low,mid-1,key);
}
}
b)
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)
{
return recursive(arr,mid-1,high,key);
}
else
{
return recursive(arr,low,mid+1,key);
}
}
c)
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)
{
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);
}
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
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
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.
Answer: d
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.
c)
d)
Answer: b
Explanation: Since ‘mid’ is calculated for every iteration or 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.
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).
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.
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.
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.
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
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).
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.
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.
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?
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.
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.
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.
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.
b)
c)
}
}
d)
}
}
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.
Answer: b
Explanation: Quick sort is the fastest known sorting algorithm because of its highly optimized inner loop.
Answer: a
Explanation: In quick sort, the array is divided into sub-arrays and then it is sorted (divide-and-conquer
strategy).
3. What is the worst case time complexity of a quick sort algorithm?
a) O(N)
b) O(N log N)
c) O(N2)
d) O(log N)
View Answer
Answer: c
Explanation: The worst case performance of a quick sort algorithm is mathematically found to be O(N2).
4. Which of the following methods is the most effective for picking the pivot element?
a) first element
b) last element
c) median-of-three partitioning
d) random element
View Answer
Answer: c
Explanation: Median-of-three partitioning is the best method for choosing an appropriate pivot element.
Picking a first, last or random element as a pivot is not much effective.
5. Find the pivot element from the given input using median-of-three partitioning method.
8, 1, 4, 9, 6, 3, 5, 2, 7, 0.
a) 8
b) 7
c) 9
d) 6
View Answer
Answer: d
Explanation: Left element=8, right element=0,
Centre=[position(left+right)/2]=6.
Answer: a
Explanation: This is the safest method to choose the pivot element since it is very unlikely that a random
pivot would consistently provide a poor partition.
Answer: c
Explanation: The best case and average case analysis of a quick sort algorithm are mathematically found to
be O(N log N).
8. Which of the following sorting algorithms is used along with quick sort to sort the sub arrays?
a) Merge sort
b) Shell sort
c) Insertion sort
d) Bubble sort
View Answer
Answer: c
Explanation: Insertion sort is used along with quick sort to sort the sub arrays.
It is used only at the end.
Answer: a
Explanation: Quick sort uses join operation since join is a faster operation than merge.
10. How many sub arrays does the quick sort algorithm divide the entire array into?
a) one
b) two
c) three
d) four
View Answer
Answer: b
Explanation: The entire array is divided into two partitions, 1st sub array containing elements less than the
pivot element and 2nd sub array containing elements greater than the pivot element.
Answer: a
Explanation: Choosing the first element as pivot is the worst method because if the input is pre-sorted or in
reverse order, then the pivot provides a poor partition.
12. Which among the following is the best cut-off range to perform insertion sort within a quick sort?
a) N=0-5
b) N=5-20
c) N=20-30
d) N>30
View Answer
Answer: b
Explanation: A good cut-off range is anywhere between N=5 and N=20 to avoid nasty degenerate cases.
1. Quick sort is a __________
a) greedy algorithm
b) divide and conquer algorithm
c) dynamic programming algorithm
d) backtracking algorithm
View Answer
Answer: b
Explanation: Quick sort is a divide and conquer algorithm. Quick sort first partitions a large array into two
smaller sub-arrays. And then recursively sorts the sub-arrays.
Answer: d
Explanation: The worst case running time for Quick sort is O(n2). In Quick sort, the worst case behaviour
occurs when the partitioning routine produces two sub-arrays one with n – 1 element and other with 0
elements.
3. Apply Quick sort on a given sequence 7 11 14 6 9 4 3 12. What is the sequence after first phase, pivot is
first element?
a) 6 4 3 7 11 9 14 12
b) 6 3 4 7 9 14 11 12
c) 7 6 14 11 9 4 3 12
d) 7 6 4 3 9 14 11 12
View Answer
Answer: b
Explanation: Let’s apply Quick sort on the given sequence,
For first phase, pivot = 7
7 11 14 6 9 4 3 12
i j
7 11 14 6 9 4 3 12
i j
7 3 14 6 9 4 11 12
i j
7 3 4 6 9 14 11 12
i j
7 3 4 6 9 14 11 12
j i
6 3 4 7 9 14 11 12
4. The best case behaviour occurs for quick sort is, if partition splits the array of size n into __________
a) n/2 : (n/2) – 1
b) n/2 : n/3
c) n/4 : 3n/2
d) n/4 : 3n/4
View Answer
Answer: a
Explanation: The best case analysis of quick sort occurs when the partition splits the array into two
subarrays, each of size no more than n/2 since one is of size n/2 and one of size (n/2) – 1.
5. Quick sort is a stable sorting algorithm.
a) True
b) False
View Answer
Answer: b
Explanation: In stable sorting algorithm the records with equal keys appear in the same order in the sorted
sequence as they appear in the input unsorted sequence. Quick sort does not preserve the relative order of
equal sort items. Therefore, Quick sort is not a stable sort.
6. Consider the Quick sort algorithm in which the partitioning procedure splits elements into two sub-arrays
and each sub-array contains at least one-fourth of the elements. Let T(n) be the number of comparisons
required to sort array of n elements. Then T(n)<=?
a) T(n) <= 2 T(n/4) + cn
b) T(n) <= T(n/4) + T(3n/4) + cn
c) T(n) <= 2 T(3n/4) + cn
d) T(n) <= T(n/3) + T(3n/4) + cn
View Answer
Answer: b
Explanation: If there are n/4 elements in one sub-array then T(n/4) comparisons are needed for this sub-
array. And T(3n/4) comparison are required for the rest 4n/5 elements, and cn is time required for finding
the pivot. If there are more than n/4 elements in one sub-array then other sub-array will have less than 3n/4
elements and time complexity will be less than T(n/4) + T(3n/4) + cn.
7. Consider the Quick sort algorithm which sorts elements in ascending order using the first element as
pivot. Then which of the following input sequence will require a maximum number of comparisons when
this algorithm is applied on it?
a) 22 25 56 67 89
b) 52 25 76 67 89
c) 22 25 76 67 50
d) 52 25 89 67 76
View Answer
Answer: a
Explanation: If the input sequence is already sorted then worst case behaviour occurs for the Quick sort
algorithm which use the first element as pivot. Therefore, the input sequence given in 22 25 56 67 89 will
require a maximum number of comparisons.
8. A machine needs a minimum of 200 sec to sort 1000 elements by Quick sort. The minimum time needed
to sort 200 elements will be approximately __________
a) 60.2 sec
b) 45.54 sec
c) 31.11 sec
d) 20 sec
View Answer
Answer: c
Explanation: The Quick sort requires nlog2n comparisons in best case, where n is size of input array. So,
1000 * log21000 ≈ 9000 comparisons are required to sort 1000 elements, which takes 200 sec. To sort 200
elements minimum of 200 * log2200 ≈ 1400 comparisons are required. This will take 200 * 1400 / 9000 ≈
31.11 sec.
9. Which one of the following sorting algorithm is best suited to sort an array of 1 million elements?
a) Bubble sort
b) Insertion sort
c) Merge sort
d) Quick sort
View Answer
Answer: d
Explanation: The Quick sort is best suited to sort the array of 1 million elements. The practical
implementations of Quick sort use randomised version. In practice randomised Quick sort algorithms rarely
shows worst case behaviour and is almost always O(nlogn). And Quick sort requires little additional space
and exhibits good cache locality.
Answer: d
Explanation: Quick sort is a space-optimised version of the binary tree sort. In binary sort tree, the elements
are inserted sequentially into the binary search tree and Quick sort organises elements into a tree that is
implied by the recursive calls.
Answer: b
Explanation: First you divide(partition) the array based on the pivot element and sort accordingly.
2. Select the appropriate recursive call for QuickSort.(arr is the array, low is the starting index and high is
the ending index of the array, partition returns the pivot element, we will see the code for partition very
soon)
a)
b)
c)
d)
Answer: d
Explanation: When the input array is already sorted.
Answer: c
Explanation: QuickSort is randomized by placing the input data in the randomized fashion in the array or by
choosing a random element in the array as a pivot.
b)
private static int partition(int[] arr, int low, int high)
{
c)
private static int partition(int[] arr, int low, int high)
{
Answer: a
Explanation: The array is partitioned into equal halves, using the Divide and Conquer master theorem, the
complexity is found to be O(nlogn).
7. The given array is arr = {2,3,4,1,6}. What are the pivots that are returned as a result of subsequent
partitioning?
a) 1 and 3
b) 3 and 1
c) 2 and 6
d) 6 and 2
View Answer
Answer: a
Explanation: The call to partition returns 1 and 3 as the pivot elements.
Answer: a
Explanation: The position of partition(split) is unknown, hence all(n) possibilities are considered, the
average is found by adding all and dividing by n.
9. The given array is arr = {2,6,1}. What are the pivots that are returned as a result of subsequent
partitioning?
a) 1 and 6
b) 6 and 1
c) 2 and 6
d) 1
View Answer
Answer: d
Explanation: There is only one pivot with which the array will be sorted, the pivot is 1.
10. Which of the following is not true about QuickSort?
a) in-place algorithm
b) pivot position can be changed
c) adaptive sorting algorithm
d) can be implemented as a stable sort
View Answer
Answer: b
Explanation: Once a pivot is chosen, its position is finalized in the sorted array, it cannot be modified.
Answer: a
Explanation: Euclid’s algorithm is basically used to find the GCD of two numbers. It cannot be directly
applied to three or more numbers at a time.
Answer: b
Explanation: Euclid invented Euclid’s algorithm. Sieve provided an algorithm for finding prime numbers.
Gabriel lame proved a theorem in Euclid’s algorithm.
Answer: c
Explanation: Euclid’s algorithm states that the GCD of two numbers does not change even if the bigger
number is replaced by a difference of two numbers. So, GCD of 16 and 12 and 12 and (16-12)=4 is the
same.
Answer: c
Explanation: Solving quadratic equations is not an application of Euclid’s algorithm whereas the rest of the
options are mathematical applications of Euclid’s algorithm.
5. The Euclid’s algorithm runs efficiently if the remainder of two numbers is divided by the minimum of
two numbers until the remainder is zero.
a) True
b) False
View Answer
Answer: a
Explanation: The Euclid’s algorithm runs efficiently if the remainder of two numbers is divided by the
minimum of two numbers until the remainder is zero. This improvement in efficiency was put forth by
Gabriel Lame.
6. According to Gabriel lame, how many steps does Euclid’s algorithm require to solve a problem?
a) Less than five times the number of digits
b) More than five times the number of digits
c) Less than two times the number of digits
d) More than two times the number of digits
View Answer
Answer: a
Explanation: The Euclid’s algorithm requires less than five times the number of digits. It runs by dividing
two numbers. It stops when a remainder zero is reached.
Answer: b
Explanation: Lagrange’s four square theorem is one of the mathematical applications of Euclid’s algorithm
and it is the basic tool for proving theorems in number theory. It can be generalized into other types of
numbers like the Gaussian integers.
8. If GCD of two numbers is 1, then the two numbers are said to be ________
a) Co-prime numbers
b) Prime numbers
c) Composite numbers
d) Rational numbers
View Answer
Answer: a
Explanation: If GCD of two numbers is 1, they are called as co-prime or relatively prime numbers. It does
not mean that they are prime numbers. They don’t have any prime factors in common.
Answer: a
Explanation: The total running time of Euclid’s algorithm according to Lame’s analysis is found to be O(N).
10. Euclidean algorithm does not require the calculation of prime factors.
a) True
b) False
View Answer
Answer: a
Explanation: Euclid’s algorithm does not require the calculation of prime factors. We derive the answer
straight away using formula. And also, factorization is complex.
Answer: a
Explanation: The formula for computing GCD of two numbers using Euclidean algorithm is given as GCD
(m,n)= GCD (n, m mod n). It is used recursively until zero is obtained as a remainder.
12. What is the total running time of the binary GCD algorithm?
a) O(N)
b) O(N2)
c) O(log N)
d) O(N log N)
View Answer
Answer: b
Explanation: Binary GCD algorithm is a sub division of Euclidean algorithm with more faster operations. Its
running time is given by O(N2).
Answer: c
Explanation: GCD(m,n)=GCD(n, m mod n)
GCD(20,12)=GCD( 12,8)
= GCD(8,4)
= GCD(4,0) = 4.
Answer: a
Explanation: Objective of tower of hanoi problem is to move all disks to some other rod by following the
following rules-1) Only one disk can be moved at a time. 2) Disk can only be moved if it is the uppermost
disk of the stack. 3) No disk should be placed over a smaller disk.
Answer: c
Explanation: The rule is to not put a disk over a smaller one. Putting a smaller disk over larger one is
allowed.
3. The time complexity of the solution tower of hanoi problem using recursion is _________
a) O(n2)
b) O(2n)
c) O(n log n)
d) O(n)
View Answer
Answer: b
Explanation: Time complexity of the problem can be found out by solving the recurrence relation:
T(n)=2T(n-1)+c. Result of this relation is found to be equal to 2n. It can be solved using substitution.
4. Recurrence equation formed for the tower of hanoi problem is given by _________
a) T(n) = 2T(n-1)+n
b) T(n) = 2T(n/2)+c
c) T(n) = 2T(n-1)+c
d) T(n) = 2T(n/2)+n
View Answer
Answer: c
Explanation: As there are 2 recursive calls to n-1 disks and one constant time operation so the recurrence
relation will be given by T(n) = 2T(n-1)+c.
5. Minimum number of moves required to solve a tower of hanoi problem with n disks is __________
a) 2n
b) 2n-1
c) n2
d) n2-1
View Answer
Answer: b
Explanation: Minimum number of moves can be calculated by solving the recurrence relation – T(n)=2T(n-
1)+c. Alternatively we can observe the pattern formed by the series of number of moves 1,3,7,15…..Either
way it turn out to be equal to 2n-1.
6. Space complexity of recursive solution of tower of hanoi puzzle is ________
a) O(1)
b) O(n)
c) O(log n)
d) O(n log n)
View Answer
Answer: b
Explanation: Space complexity of tower of hanoi problem can be found out by solving the recurrence
relation T(n)=T(n-1)+c. Result of this relation is found out to be n. It can be solved using substitution.
7. Which of the following functions correctly represent the solution to tower of hanoi puzzle?
a)
b)
c)
d)
Answer: a
Explanation: Iterative solution to tower of hanoi puzzle also exists. Its approach depends on whether the
total numbers of disks are even or odd.
10. Minimum time required to solve tower of hanoi puzzle with 4 disks assuming one move takes 2 seconds,
will be __________
a) 15 seconds
b) 30 seconds
c) 16 seconds
d) 32 seconds
View Answer
Answer: b
Explanation: Number of moves = 24-1=16-1=15
Time for 1 move = 2 seconds
Time for 15 moves = 15×2 = 30 seconds.
Dynamic Programming
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
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.
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
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 don’t take advantage of the overlapping subproblems property.
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
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.
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.
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.
Answer: d
Explanation: Each of the above mentioned methods can be used to find the nth fibonacci term.
int fibo(int n)
if n <= 1
return n
return __________
Answer: d
Explanation: Consider the first five terms of the fibonacci sequence: 0,1,1,2,3. The 6th term can be found by
adding the two previous terms, i.e. fibo(6) = fibo(5) + fibo(4) = 3 + 2 = 5. Therefore,the nth term of a
fibonacci sequence would be given by:
fibo(n) = fibo(n-1) + fibo(n-2).
3. What is the time complexity of the recursive implementation used to find the nth fibonacci term?
a) O(1)
b) O(n2)
c) O(n!)
d) Exponential
View Answer
Answer: d
Explanation: The recurrence relation is given by fibo(n) = fibo(n – 1) + fibo(n – 2). So, the time complexity
is given by:
T(n) = T(n – 1) + T(n – 2)
Approximately,
T(n) = 2 * T(n – 1)
= 4 * T(n – 2)
= 8 * T(n – 3)
:
:
:
= 2k * T(n – k)
This recurrence will stop when n – k = 0
i.e. n = k
Therefore, T(n) = 2n * O(0) = 2n
Hence, it takes exponential time.
It can also be proved by drawing the recursion tree and counting the number of leaves.
4. Suppose we find the 8th term using the recursive implementation. The arguments passed to the function
calls will be as follows:
fibonacci(8)
fibonacci(7) + fibonacci(6)
fibonacci(6) + fibonacci(5) + fibonacci(5) + fibonacci(4)
fibonacci(5) + fibonacci(4) + fibonacci(4) + fibonacci(3) + fibonacci(4)
+ fibonacci(3) + fibonacci(3) + fibonacci(2)
:
:
:
Answer: c
Explanation: From the function calls, we can see that fibonacci(4) is calculated twice and fibonacci(3) is
calculated thrice. Thus, the same subproblem is solved many times and hence the function calls show the
overlapping subproblems property.
#include<stdio.h>
int fibo(int n)
{
if(n<=1)
return n;
return fibo(n-1) + fibo(n-2);
}
int main()
{
int r = fibo(50000);
printf("%d",r);
return 0;
}
a) 1253556389
b) 5635632456
c) Garbage value
d) Runtime error
Answer: d
6. What is the space complexity of the recursive implementation used to find the nth fibonacci term?
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
View Answer
Answer: a
Explanation: The recursive implementation doesn’t store any values and calculates every value from scratch.
So, the space complexity is O(1).
int fibo(int n)
if n == 0
return 0
else
prevFib = 0
curFib = 1
for i : 1 to n-1
nextFib = prevFib + curFib
__________
__________
return curFib
prevFib = curFib
curFib = curFib
b)
prevFib = nextFib
curFib = prevFib
c)
prevFib = curFib
curFib = nextFib
d)
prevFib = nextFib
nextFib = curFib
View Answer
Answer: c
Explanation: The lines, prevFib = curFib and curFib = nextFib, make the code complete.
8. What is the time complexity of the following for loop method used to compute the nth fibonacci term?
int fibo(int n)
if n == 0
return 0
else
prevFib = 0
curFib = 1
for i : 1 to n-1
nextFib = prevFib + curFib
prevFib = curFib
curFib = nextFib
return curFib
a) O(1)
b) O(n)
c) O(n2)
d) Exponential
View Answer
Answer: b
Explanation: To calculate the nth term, the for loop runs (n – 1) times and each time a for loop is run, it
takes a constant time. Therefore, the time complexity is of the order of n.
9. What is the space complexity of the following for loop method used to compute the nth fibonacci term?
int fibo(int n)
if n == 0
return 0
else
prevFib = 0
curFib = 1
for i : 1 to n-1
nextFib = prevFib + curFib
prevFib = curFib
curFib = nextFib
return curFib
a) O(1)
b) O(n)
c) O(n2)
d) Exponential
View Answer
Answer: a
Explanation: To calculate the nth term, we just store the previous term and the current term and then
calculate the next term using these two terms. It takes a constant space to store these two terms and hence
O(1) is the answer.
10. What will be the output when the following code is executed?
#include<stdio.h>
int fibo(int n)
{
if(n==0)
return 0;
int i;
int prevFib=0,curFib=1;
for(i=1;i<=n-1;i++)
{
int nextFib = prevFib + curFib;
prevFib = curFib;
curFib = nextFib;
}
return curFib;
}
int main()
{
int r = fibo(10);
printf("%d",r);
return 0;
}
a) 34
b) 55
c) Compile error
d) Runtime error
View Answer
Answer: b
Explanation: The output is the 10th fibonacci number, which is 55.
11. Consider the following code to find the nth fibonacci term using dynamic programming:
1. int fibo(int n)
2. int fibo_terms[100000] //arr to store the fibonacci numbers
3. fibo_terms[0] = 0
4. fibo_terms[1] = 1
5.
6. for i: 2 to n
7. fibo_terms[i] = fibo_terms[i - 1] + fibo_terms[i - 2]
8.
9. return fibo_terms[n]
Answer: a
Explanation: We find the nth fibonacci term by finding previous fibonacci terms, i.e. by solving
subproblems. Hence, line 7 shows the optimal substructure property.
12. Consider the following code to find the nth fibonacci term using dynamic programming:
1. int fibo(int n)
2. int fibo_terms[100000] //arr to store the fibonacci numbers
3. fibo_terms[0] = 0
4. fibo_terms[1] = 1
5.
6. for i: 2 to n
7. fibo_terms[i] = fibo_terms[i - 1] + fibo_terms[i - 2]
8.
9. return fibo_terms[n]
Answer: c
Explanation: Line 7 stores the current value that is calculated, so that the value can be used later directly
without calculating it from scratch. This is memoization.
13. What is the time complexity of the following dynamic programming implementation used to compute
the nth fibonacci term?
1. int fibo(int n)
2. int fibo_terms[100000] //arr to store the fibonacci numbers
3. fibo_terms[0] = 0
4. fibo_terms[1] = 1
5.
6. for i: 2 to n
7. fibo_terms[i] = fibo_terms[i - 1] + fibo_terms[i - 2]
8.
9. return fibo_terms[n]
a) O(1)
b) O(n)
c) O(n2)
d) Exponential
View Answer
Answer: b
Explanation: To calculate the nth term, the for loop runs (n – 1) times and each time a for loop is run, it
takes a constant time. Therefore, the time complexity is of the order of n.
14. What is the space complexity of the following dynamic programming implementation used to compute
the nth fibonacci term?
int fibo(int n)
int fibo_terms[100000] //arr to store the fibonacci numbers
fibo_terms[0] = 0
fibo_terms[1] = 1
for i: 2 to n
fibo_terms[i] = fibo_terms[i - 1] + fibo_terms[i - 2]
return fibo_terms[n]
a) O(1)
b) O(n)
c) O(n2)
d) Exponential
View Answer
Answer: b
Explanation: To calculate the nth term, we store all the terms from 0 to n – 1. So, it takes O(n) space.
15. What will be the output when the following code is executed?
#include<stdio.
int fibo(int n)
{
int i;
int fibo_terms[100];
fibo_terms[0]=0;
fibo_terms[1]=1;
for(i=2;i<=n;i++)
fibo_terms[i] = fibo_terms[i-2] + fibo_terms[i-1];
return fibo_terms[n];
}
int main()
{
int r = fibo(8);
printf("%d",r);
return 0;
}
a) 34
b) 55
c) Compile error
d) 21
View Answer
Answer: d
Explanation: The program prints the 8th fibonacci term, which is 21.
1. Given a one-dimensional array of integers, you have to find a sub-array with maximum sum. This is the
maximum sub-array sum problem. Which of these methods can be used to solve the problem?
a) Dynamic programming
b) Two for loops (naive method)
c) Divide and conquer
d) Dynamic programming, naïve method and Divide and conquer methods
View Answer
Answer: d
Explanation: Dynamic programming, naïve method and Divide and conquer methods can be used to solve
the maximum sub array sum problem.
Answer: b
Explanation: The maximum sub-array sum is 5.
Answer: d
Explanation: All the elements are negative. So, the maximum sub-array sum will be equal to the largest
element. The largest element is -1 and therefore, the maximum sub-array sum is -1.
4. Consider the following naive method to find the maximum sub-array sum:
#include<stdio.h>
int main()
{
int arr[1000]={2, -1, 3, -4, 1, -2, -1, 5, -4}, len=9;
int cur_max, tmp_max, strt_idx, sub_arr_idx;
cur_max = arr[0];
for(strt_idx = 0; strt_idx < len; strt_idx++)
{
tmp_max=0;
for(sub_arr_idx = strt_idx; sub_arr_idx < len; sub_arr_idx++)
{
tmp_max +=arr[sub_arr_idx];
if(tmp_max > cur_max)
_____________;
}
}
printf("%d",cur_max);
return 0;
}
Answer: d
Explanation: If the tmp_max element is greater than the cur_max element, we make cur_max equal to
tmp_max, i.e. cur_max = tmp_max.
5. What is the time complexity of the following naive method used to find the maximum sub-array sum in an
array containing n elements?
#include<stdio.h>
int main()
{
int arr[1000]={2, -1, 3, -4, 1, -2, -1, 5, -4}, len=9;
int cur_max, tmp_max, strt_idx, sub_arr_idx;
cur_max = arr[0];
for(strt_idx = 0; strt_idx < len; strt_idx++)
{
tmp_max=0;
for(sub_arr_idx = strt_idx; sub_arr_idx < len; sub_arr_idx++)
{
tmp_max +=arr[sub_arr_idx];
if(tmp_max > cur_max)
_____________;
}
}
printf("%d",cur_max);
return 0;
}
a) O(n2)
b) O(n)
c) O(n3)
d) O(1)
View Answer
Answer: a
6. What is the space complexity of the following naive method used to find the maximum sub-array sum in
an array containing n elements?
#include<stdio.h>
int main()
{
int arr[1000]={2, -1, 3, -4, 1, -2, -1, 5, -4}, len=9;
int cur_max, tmp_max, strt_idx, sub_arr_idx;
cur_max = arr[0];
for(strt_idx = 0; strt_idx < len; strt_idx++)
{
tmp_max=0;
for(sub_arr_idx = strt_idx; sub_arr_idx < len; sub_arr_idx++)
{
tmp_max +=arr[sub_arr_idx];
if(tmp_max > cur_max)
_____________;
}
}
printf("%d",cur_max);
return 0;
}
a) O(n2)
b) O(1)
c) O(n3)
d) O(n)
View Answer
Answer: b
Explanation: The naive method uses only a constant space. So, the space complexity is O(1).
7. What is the output of the following naive method used to find the maximum sub-array sum?
#include<stdio.h>
int main()
{
int arr[1000] = {-2, -5, 6, -2, 3, -1, 0,-5, 6}, len = 9;
int cur_max, tmp_max, strt_idx, sub_arr_idx;
cur_max = arr[0];
for(strt_idx = 0; strt_idx < len; strt_idx++)
{
tmp_max = 0;
for(sub_arr_idx = strt_idx; sub_arr_idx < len; sub_arr_idx++)
{
tmp_max += arr[sub_arr_idx];
if(tmp_max > cur_max)
cur_max = tmp_max;
}
}
printf("%d",cur_max);
return 0;
}
a) 6
b) 9
c) 7
d) 4
View Answer
Answer: c
Explanation: The naive method prints the maximum sub-array sum, which is 7.
8. What is the time complexity of the divide and conquer algorithm used to find the maximum sub-array
sum?
a) O(n)
b) O(logn)
c) O(nlogn)
d) O(n2)
View Answer
Answer: c
Explanation: The time complexity of the divide and conquer algorithm used to find the maximum sub-array
sum is O(nlogn).
9. What is the space complexity of the divide and conquer algorithm used to find the maximum sub-array
sum?
a) O(n)
b) O(1)
c) O(n!)
d) O(n2)
View Answer
Answer: b
Explanation: The divide and conquer algorithm uses a constant space. So, the space complexity is O(1).
1. The longest increasing subsequence problem is a problem to find the length of a subsequence from a
sequence of array elements such that the subsequence is sorted in increasing order and it’s length is
maximum. This problem can be solved using __________
a) Recursion
b) Dynamic programming
c) Brute force
d) Recursion, Dynamic programming, Brute force
View Answer
Answer: d
Explanation: The longest increasing subsequence problem can be solved using all of the mentioned methods.
Answer: d
Explanation: The longest increasing subsequence is {-10, 9, 10, 13, 14}.
3. Find the length of the longest increasing subsequence for the given sequence:
{-10, 24, -9, 35, -21, 55, -41, 76, 84}
a) 5
b) 4
c) 3
d) 6
View Answer
Answer: d
Explanation: The longest increasing subsequence is {-10, 24, 35, 55, 76, 84} and it’s length is 6.
4. For any given sequence, there will ALWAYS be a unique increasing subsequence with the longest length.
a) True
b) False
View Answer
Answer: b
Explanation: For a given sequence, it is possible that there is more than one subsequence with the longest
length.
Consider, the following sequence: {10,11,12,1,2,3}:
There are two longest increasing subsequences: {1,2,3} and {10,11,12}.
5. The number of increasing subsequences with the longest length for the given sequence are:
{10, 9, 8, 7, 6, 5}
a) 3
b) 4
c) 5
d) 6
View Answer
Answer: d
Explanation: Each array element individually forms a longest increasing subsequence and so, the length of
the longest increasing subsequence is 1. So, the number of increasing subsequences with the longest length
is 6.
6. In the brute force implementation to find the longest increasing subsequence, all the subsequences of a
given sequence are found. All the increasing subsequences are then selected and the length of the longest
subsequence is found. What is the time complexity of this brute force implementation?
a) O(n)
b) O(n2)
c) O(n!)
d) O(2n)
View Answer
Answer: d
Explanation: The time required to find all the subsequences of a given sequence is 2n, where ‘n’ is the
number of elements in the sequence. So, the time complexity is O(2n).
7. Complete the following dynamic programming implementation of the longest increasing subsequence
problem:
#include<stdio.h>
int longest_inc_sub(int *arr, int len)
{
int i, j, tmp_max;
int LIS[len]; // array to store the lengths of the longest increasing
subsequence
LIS[0]=1;
for(i = 1; i < len; i++)
{
tmp_max = 0;
for(j = 0; j < i; j++)
{
if(arr[j] < arr[i])
{
if(LIS[j] > tmp_max)
___________;
}
}
LIS[i] = tmp_max + 1;
}
int max = LIS[0];
for(i = 0; i < len; i++)
if(LIS[i] > max)
max = LIS[i];
return max;
}
int main()
{
int arr[] = {10,22,9,33,21,50,41,60,80}, len = 9;
int ans = longest_inc_sub(arr, len);
printf("%d",ans);
return 0;
}
a) tmp_max = LIS[j]
b) LIS[i] = LIS[j]
c) LIS[j] = tmp_max
d) tmp_max = LIS[i]
View Answer
Answer: a
Explanation: tmp_max is used to store the maximum length of an increasing subsequence for any ‘j’ such
that: arr[j] < arr[i] and 0 < j < i.
So, tmp_max = LIS[j] completes the code.
8. What is the time complexity of the following dynamic programming implementation used to find the
length of the longest increasing subsequence?
#include<stdio.h>
int longest_inc_sub(int *arr, int len)
{
int i, j, tmp_max;
int LIS[len]; // array to store the lengths of the longest increasing
subsequence
LIS[0]=1;
for(i = 1; i < len; i++)
{
tmp_max = 0;
for(j = 0; j < i; j++)
{
if(arr[j] < arr[i])
{
if(LIS[j] > tmp_max)
tmp_max = LIS[j];
}
}
LIS[i] = tmp_max + 1;
}
int max = LIS[0];
for(i = 0; i < len; i++)
if(LIS[i] > max)
max = LIS[i];
return max;
}
int main()
{
int arr[] = {10,22,9,33,21,50,41,60,80}, len = 9;
int ans = longest_inc_sub(arr, len);
printf("%d",ans);
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(nlogn)
View Answer
Answer: c
Explanation: The time complexity of the above dynamic programming implementation used to find the
length of the longest increasing subsequence is O(n2).
9. What is the space complexity of the following dynamic programming implementation used to find the
length of the longest increasing subsequence?
#include<stdio.h>
int longest_inc_sub(int *arr, int len)
{
int i, j, tmp_max;
int LIS[len]; // array to store the lengths of the longest increasing
subsequence
LIS[0]=1;
for(i = 1; i < len; i++)
{
tmp_max = 0;
for(j = 0; j < i; j++)
{
if(arr[j] < arr[i])
{
if(LIS[j] > tmp_max)
tmp_max = LIS[j];
}
}
LIS[i] = tmp_max + 1;
}
int max = LIS[0];
for(i = 0; i < len; i++)
if(LIS[i] > max)
max = LIS[i];
return max;
}
int main()
{
int arr[] = {10,22,9,33,21,50,41,60,80}, len = 9;
int ans = longest_inc_sub(arr, len);
printf("%d",ans);
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(nlogn)
View Answer
Answer: b
Explanation: The above dynamic programming implementation uses space equal to the length of the
sequence. So, the space complexity of the above dynamic programming implementation used to find the
length of the longest increasing subsequence is O(n).
10. What is the output of the following program?
#include<stdio.h>
int longest_inc_sub(int *arr, int len)
{
int i, j, tmp_max;
int LIS[len]; // array to store the lengths of the longest increasing
subsequence
LIS[0]=1;
for(i = 1; i < len; i++)
{
tmp_max = 0;
for(j = 0; j < i; j++)
{
if(arr[j] < arr[i])
{
if(LIS[j] > tmp_max)
tmp_max = LIS[j];
}
}
LIS[i] = tmp_max + 1;
}
int max = LIS[0];
for(i = 0; i < len; i++)
if(LIS[i] > max)
max = LIS[i];
return max;
}
int main()
{
int arr[] = {10,22,9,33,21,50,41,60,80}, len = 9;
int ans = longest_inc_sub(arr, len);
printf("%d",ans);
return 0;
}
a) 3
b) 4
c) 5
d) 6
View Answer
Answer: d
Explanation: The program prints the length of the longest increasing subsequence, which is 6.
11. What is the value stored in LIS[5] after the following program is executed?
#include<stdio.h>
int longest_inc_sub(int *arr, int len)
{
int i, j, tmp_max;
int LIS[len]; // array to store the lengths of the longest increasing
subsequence
LIS[0]=1;
for(i = 1; i < len; i++)
{
tmp_max = 0;
for(j = 0; j < i; j++)
{
if(arr[j] < arr[i])
{
if(LIS[j] > tmp_max)
tmp_max = LIS[j];
}
}
LIS[i] = tmp_max + 1;
}
int max = LIS[0];
for(i = 0; i < len; i++)
if(LIS[i] > max)
max = LIS[i];
return max;
}
int main()
{
int arr[] = {10,22,9,33,21,50,41,60,80}, len = 9;
int ans = longest_inc_sub(arr, len);
printf("%d",ans);
return 0;
}
a) 2
b) 3
c) 4
d) 5
View Answer
Answer: c
Explanation: The value stored in LIS[5] after the program is executed is 4.
Answer: b
Explanation: Knapsack problem is an example of 2D dynamic programming.
2. Which of the following methods can be used to solve the Knapsack problem?
a) Brute force algorithm
b) Recursion
c) Dynamic programming
d) Brute force, Recursion and Dynamic Programming
View Answer
Answer: d
Explanation: Brute force, Recursion and Dynamic Programming can be used to solve the knapsack problem.
3. You are given a knapsack that can carry a maximum weight of 60. There are 4 items with weights {20,
30, 40, 70} and values {70, 80, 90, 200}. What is the maximum value of the items you can carry using the
knapsack?
a) 160
b) 200
c) 170
d) 90
View Answer
Answer: a
Explanation: The maximum value you can get is 160. This can be achieved by choosing the items 1 and 3
that have a total weight of 60.
Answer: b
Explanation: In this case, questions are used instead of items. Each question has a score which is same as
each item having a value. Also, each question takes a time t which is same as each item having a weight w.
You have to maximize the score in time T which is same as maximizing the value using a bag of weight W.
5. What is the time complexity of the brute force algorithm used to solve the Knapsack problem?
a) O(n)
b) O(n!)
c) O(2n)
d) O(n3)
View Answer
Answer: c
Explanation: In the brute force algorithm all the subsets of the items are found and the value of each subset
is calculated. The subset of items with the maximum value and a weight less than equal to the maximum
allowed weight gives the answer. The time taken to calculate all the subsets is O(2n).
6. The 0-1 Knapsack problem can be solved using Greedy algorithm.
a) True
b) False
View Answer
Answer: b
Explanation: The Knapsack problem cannot be solved using the greedy algorithm.
#include<stdio.h>
int find_max(int a, int b)
{
if(a > b)
return a;
return b;
}
int knapsack(int W, int *wt, int *val,int n)
{
int ans[n + 1][W + 1];
int itm,w;
for(itm = 0; itm <= n; itm++)
ans[itm][0] = 0;
for(w = 0;w <= W; w++)
ans[0][w] = 0;
for(itm = 1; itm <= n; itm++)
{
for(w = 1; w <= W; w++)
{
if(wt[itm - 1] <= w)
ans[itm][w] = ______________;
else
ans[itm][w] = ans[itm - 1][w];
}
}
return ans[n][W];
}
int main()
{
int w[] = {10,20,30}, v[] = {60, 100, 120}, W = 50;
int ans = knapsack(W, w, v, 3);
printf("%d",ans);
return 0;
}
Answer: a
Explanation: find_max(ans[itm – 1][w – wt[itm – 1]] + val[itm – 1], ans[itm – 1][w]) completes the above
code.
8. What is the time complexity of the following dynamic programming implementation of the Knapsack
problem with n items and a maximum weight of W?
#include<stdio.h>
int find_max(int a, int b)
{
if(a > b)
return a;
return b;
}
int knapsack(int W, int *wt, int *val,int n)
{
int ans[n + 1][W + 1];
int itm,w;
for(itm = 0; itm <= n; itm++)
ans[itm][0] = 0;
for(w = 0;w <= W; w++)
ans[0][w] = 0;
for(itm = 1; itm <= n; itm++)
{
for(w = 1; w <= W; w++)
{
if(wt[itm - 1] <= w)
ans[itm][w] = find_max(ans[itm - 1][w-wt[itm - 1]]+val[itm - 1],
ans[itm - 1][w]);
else
ans[itm][w] = ans[itm - 1][w];
}
}
return ans[n][W];
}
int main()
{
int w[] = {10,20,30}, v[] = {60, 100, 120}, W = 50;
int ans = knapsack(W, w, v, 3);
printf("%d",ans);
return 0;
}
a) O(n)
b) O(n + w)
c) O(nW)
d) O(n2)
View Answer
Answer: c
Explanation: The time complexity of the above dynamic programming implementation of the Knapsack
problem is O(nW).
9. What is the space complexity of the following dynamic programming implementation of the Knapsack
problem?
#include<stdio.h>
int find_max(int a, int b)
{
if(a > b)
return a;
return b;
}
int knapsack(int W, int *wt, int *val,int n)
{
int ans[n + 1][W + 1];
int itm,w;
for(itm = 0; itm <= n; itm++)
ans[itm][0] = 0;
for(w = 0;w <= W; w++)
ans[0][w] = 0;
for(itm = 1; itm <= n; itm++)
{
for(w = 1; w <= W; w++)
{
if(wt[itm - 1] <= w)
ans[itm][w] = find_max(ans[itm - 1][w - wt[itm - 1]]+val[itm - 1],
ans[itm - 1][w]);
else
ans[itm][w] = ans[itm - 1][w];
}
}
return ans[n][W];
}
int main()
{
int w[] = {10,20,30}, v[] = {60, 100, 120}, W = 50;
int ans = knapsack(W, w, v, 3);
printf("%d",ans);
return 0;
}
a) O(n)
b) O(n + w)
c) O(nW)
d) O(n2)
View Answer
Answer: c
Explanation: The space complexity of the above dynamic programming implementation of the Knapsack
problem is O(nW).
10. What is the output of the following code?
#include<stdio.h>
int find_max(int a, int b)
{
if(a > b)
return a;
return b;
}
int knapsack(int W, int *wt, int *val,int n)
{
int ans[n + 1][W + 1];
int itm,w;
for(itm = 0; itm <= n; itm++)
ans[itm][0] = 0;
for(w = 0;w <= W; w++)
ans[0][w] = 0;
for(itm = 1; itm <= n; itm++)
{
for(w = 1; w <= W; w++)
{
if(wt[itm - 1] <= w)
ans[itm][w] = find_max(ans[itm - 1][w-wt[itm - 1]]+val[itm - 1],
ans[itm - 1][w]);
else
ans[itm][w] = ans[itm - 1][w];
}
}
return ans[n][W];
}
int main()
{
int w[] = {10,20,30}, v[] = {60, 100, 120}, W = 50;
int ans = knapsack(W, w, v, 3);
printf("%d",ans);
return 0;
}
a) 120
b) 100
c) 180
d) 220
View Answer
Answer: d
Explanation: The output of the above code is 220
1. Which of the following methods can be used to solve the longest common subsequence problem?
a) Recursion
b) Dynamic programming
c) Both recursion and dynamic programming
d) Greedy algorithm
View Answer
Answer: c
Explanation: Both recursion and dynamic programming can be used to solve the longest subsequence
problem.
2. Consider the strings “PQRSTPQRS” and “PRATPBRQRPS”. What is the length of the longest common
subsequence?
a) 9
b) 8
c) 7
d) 6
View Answer
Answer: c
Explanation: The longest common subsequence is “PRTPQRS” and its length is 7.
3. Which of the following problems can be solved using the longest subsequence problem?
a) Longest increasing subsequence
b) Longest palindromic subsequence
c) Longest bitonic subsequence
d) Longest decreasing subsequence
View Answer
Answer: b
Explanation: To find the longest palindromic subsequence in a given string, reverse the given string and then
find the longest common subsequence in the given string and the reversed string.
Answer: b
Explanation: Longest common subsequence is an example of 2D dynamic programming.
5. What is the time complexity of the brute force algorithm used to find the longest common subsequence?
a) O(n)
b) O(n2)
c) O(n3)
d) O(2n)
View Answer
Answer: d
Explanation: The time complexity of the brute force algorithm used to find the longest common
subsequence is O(2n).
6. Consider the following dynamic programming implementation of the longest common subsequence
problem:
#include<stdio.h>
#include<string.h>
int max_num(int a, int b)
{
if(a > b)
return a;
return b;
}
int lcs(char *str1, char *str2)
{
int i,j,len1,len2;
len1 = strlen(str1);
len2 = strlen(str2);
int arr[len1 + 1][len2 + 1];
for(i = 0; i <= len1; i++)
arr[i][0] = 0;
for(i = 0; i <= len2; i++)
arr[0][i] = 0;
for(i = 1; i <= len1; i++)
{
for(j = 1; j <= len2; j++)
{
if(str1[i-1] == str2[j - 1])
______________;
else
arr[i][j] = max_num(arr[i - 1][j], arr[i][j - 1]);
}
}
return arr[len1][len2];
}
int main()
{
char str1[] = " abcedfg", str2[] = "bcdfh";
int ans = lcs(str1,str2);
printf("%d",ans);
return 0;
}
Answer: b
Explanation: The line, arr[i][j] = 1 + arr[i – 1][j – 1] completes the above code.
7. What is the time complexity of the following dynamic programming implementation of the longest
common subsequence problem where length of one string is “m” and the length of the other string is “n”?
#include<stdio.h>
#include<string.h>
int max_num(int a, int b)
{
if(a > b)
return a;
return b;
}
int lcs(char *str1, char *str2)
{
int i,j,len1,len2;
len1 = strlen(str1);
len2 = strlen(str2);
int arr[len1 + 1][len2 + 1];
for(i = 0; i <= len1; i++)
arr[i][0] = 0;
for(i = 0; i <= len2; i++)
arr[0][i] = 0;
for(i = 1; i <= len1; i++)
{
for(j = 1; j <= len2; j++)
{
if(str1[i-1] == str2[j - 1])
arr[i][j] = 1 + arr[i - 1][j - 1];
else
arr[i][j] = max_num(arr[i - 1][j], arr[i][j - 1]);
}
}
return arr[len1][len2];
}
int main()
{
char str1[] = " abcedfg", str2[] = "bcdfh";
int ans = lcs(str1,str2);
printf("%d",ans);
return 0;
}
a) O(n)
b) O(m)
c) O(m + n)
d) O(mn)
View Answer
Answer: d
Explanation: The time complexity of the above dynamic programming implementation of the longest
common subsequence is O(mn).
8. What is the space complexity of the following dynamic programming implementation of the longest
common subsequence problem where length of one string is “m” and the length of the other string is “n”?
#include<stdio.h>
#include<string.h>
int max_num(int a, int b)
{
if(a > b)
return a;
return b;
}
int lcs(char *str1, char *str2)
{
int i,j,len1,len2;
len1 = strlen(str1);
len2 = strlen(str2);
int arr[len1 + 1][len2 + 1];
for(i = 0; i <= len1; i++)
arr[i][0] = 0;
for(i = 0; i <= len2; i++)
arr[0][i] = 0;
for(i = 1; i <= len1; i++)
{
for(j = 1; j <= len2; j++)
{
if(str1[i-1] == str2[j - 1])
arr[i][j] = 1 + arr[i - 1][j - 1];
else
arr[i][j] = max_num(arr[i - 1][j], arr[i][j - 1]);
}
}
return arr[len1][len2];
}
int main()
{
char str1[] = " abcedfg", str2[] = "bcdfh";
int ans = lcs(str1,str2);
printf("%d",ans);
return 0;
}
a) O(n)
b) O(m)
c) O(m + n)
d) O(mn)
View Answer
Answer: d
Explanation: The space complexity of the above dynamic programming implementation of the longest
common subsequence is O(mn).
9. What is the output of the following code?
#include<stdio.h>
#include<string.h>
int max_num(int a, int b)
{
if(a > b)
return a;
return b;
}
int lcs(char *str1, char *str2)
{
int i,j,len1,len2;
len1 = strlen(str1);
len2 = strlen(str2);
int arr[len1 + 1][len2 + 1];
for(i = 0; i <= len1; i++)
arr[i][0] = 0;
for(i = 0; i <= len2; i++)
arr[0][i] = 0;
for(i = 1; i <= len1; i++)
{
for(j = 1; j <= len2; j++)
{
if(str1[i-1] == str2[j - 1])
arr[i][j] = 1 + arr[i - 1][j - 1];
else
arr[i][j] = max_num(arr[i - 1][j], arr[i][j - 1]);
}
}
return arr[len1][len2];
}
int main()
{
char str1[] = "hbcfgmnapq", str2[] = "cbhgrsfnmq";
int ans = lcs(str1,str2);
printf("%d",ans);
return 0;
}
a) 3
b) 4
c) 5
d) 6
View Answer
Answer: b
Explanation: The program prints the length of the longest common subsequence, which is 4.
10. Which of the following is the longest common subsequence between the strings “hbcfgmnapq” and
“cbhgrsfnmq” ?
a) hgmq
b) cfnq
c) bfmq
d) fgmna
View Answer
Answer: d
Explanation: The length of the longest common subsequence is 4. But ‘fgmna’ is not the longest common
subsequence as its length is 5.
11. What is the value stored in arr[2][3] when the following code is executed?
#include<stdio.h>
#include<string.h>
int max_num(int a, int b)
{
if(a > b)
return a;
return b;
}
int lcs(char *str1, char *str2)
{
int i,j,len1,len2;
len1 = strlen(str1);
len2 = strlen(str2);
int arr[len1 + 1][len2 + 1];
for(i = 0; i <= len1; i++)
arr[i][0] = 0;
for(i = 0; i <= len2; i++)
arr[0][i] = 0;
for(i = 1; i <= len1; i++)
{
for(j = 1; j <= len2; j++)
{
if(str1[i-1] == str2[j - 1])
arr[i][j] = 1 + arr[i - 1][j - 1];
else
arr[i][j] = max_num(arr[i - 1][j], arr[i][j - 1]);
}
}
return arr[len1][len2];
}
int main()
{
char str1[] = "hbcfgmnapq", str2[] = "cbhgrsfnmq";
int ans = lcs(str1,str2);
printf("%d",ans);
return 0;
}
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: a
Explanation: The value stored in arr[2][3] is 1.
12. What is the output of the following code?
#include<stdio.h>
#include<string.h>
int max_num(int a, int b)
{
if(a > b)
return a;
return b;
}
int lcs(char *str1, char *str2)
{
int i,j,len1,len2;
len1 = strlen(str1);
len2 = strlen(str2);
int arr[len1 + 1][len2 + 1];
for(i = 0; i <= len1; i++)
arr[i][0] = 0;
for(i = 0; i <= len2; i++)
arr[0][i] = 0;
for(i = 1; i <= len1; i++)
{
for(j = 1; j <= len2; j++)
{
if(str1[i-1] == str2[j - 1])
arr[i][j] = 1 + arr[i - 1][j - 1];
else
arr[i][j] = max_num(arr[i - 1][j], arr[i][j - 1]);
}
}
return arr[len1][len2];
}
int main()
{
char str1[] = "abcd", str2[] = "efgh";
int ans = lcs(str1,str2);
printf("%d",ans);
return 0;
}
a) 3
b) 2
c) 1
d) 0
View Answer
Answer: d
Explanation: The program prints the length of the longest common subsequence, which is 0.
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.
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.
Answer: b
Explanation: When we reach a final solution using a backtracking algorithm, we either stop or continue
searching for other possible solutions.
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.
Answer: b
Explanation: The leaves in a state space tree can either represent non-promising dead ends or complete
solutions found by the algorithm.
Answer: c
Explanation: Backtracking approach is used to solve complex combinatorial problems which cannot be
solved by exhaustive search algorithms.
Answer: d
Explanation: Crossword puzzles are based on backtracking approach whereas the rest are travelling
salesman problem, knapsack problem and dice game.
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?
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.
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.
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.
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.
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.
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.
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.
6. For how many queens was the extended version of Eight Queen Puzzle applicable for n*n squares?
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.
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.
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.
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.
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.
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
Answer: c
Explanation: Queens attack each other in three directions- vertical, horizontal and diagonal.
Answer: a
Explanation: Placing n queens so that no two queens attack each other is n-queens problem. If n=8, it is
called as 8-queens problem.
3. Where is the n-queens problem implemented?
a) carom
b) chess
c) ludo
d) cards
View Answer
Answer: b
Explanation: N-queens problem occurs in chess. It is the problem of placing n- queens in a n*n chess board.
Answer: b
Explanation: Unlike a real chess game, n-queens occur in a n-queen problem since it is the problem of
dealing with n-queens.
5. In n-queen problem, how many values of n does not provide an optimal solution?
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: b
Explanation: N-queen problem does not provide an optimal solution of only three values of n (i.e.) n=2,3.
Answer: d
Explanation: Of the following given approaches, n-queens problem can be solved using backtracking. It can
also be solved using branch and bound.
7. Of the following given options, which one of the following is a correct option that provides an optimal
solution for 4-queens problem?
a) (3,1,4,2)
b) (2,3,1,4)
c) (4,3,2,1)
d) (4,2,3,1)
View Answer
Answer: a
Explanation: Of the following given options for optimal solutions of 4-queens problem, (3, 1, 4, 2) is the
right option.
8. How many possible solutions exist for an 8-queen problem?
a) 100
b) 98
c) 92
d) 88
View Answer
Answer: c
Explanation: For an 8-queen problem, there are 92 possible combinations of optimal solutions.
Answer: d
Explanation: For a 10-queen problem, 724 possible combinations of optimal solutions are available.
Answer: b
Explanation: For n=1, the n-queen problem has a trivial and real solution and it is represented by
Answer: d
Explanation: The minimum number of queens needed to occupy every square in n-queens problem is called
domination number. While n=8, the domination number is 5.
12. Of the following given options, which one of the following does not provides an optimal solution for 8-
queens problem?
a) (5,3,8,4,7,1,6,2)
b) (1,6,3,8,3,2,4,7)
c) (4,1,5,8,6,3,7,2)
d) (6,2,7,1,4,8,5,3)
View Answer
Answer: b
Explanation: The following given options for optimal solutions of 8-queens problem, (1,6,3,8,3,2,4,7) does
not provide an optimal solution.
1. Which of the following algorithm can be used to solve the Hamiltonian path problem efficiently?
a) branch and bound
b) iterative improvement
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.
Answer: d
Explanation: Hamiltonian path problem is found to be NP complete. Hamiltonian cycle problem is also an
NP- complete problem.
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.
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.
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?
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
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)
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.
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.