Fdsall
Fdsall
Fdsall
Answer: b
Explanation: Array contains elements only of the same type.
Answer: c
Explanation: This is the syntax to initialize an array in C.
Answer: c
Explanation: Note that int arr[]; is declaration whereas int arr[] = new int[3]; is to instantiate an array.
4. Which of the following is the correct way to declare a multidimensional array in Java?
a) int[] arr;
b) int arr[[]];
c) int[][]arr;
d) int[[]] arr;
Answer: c
Explanation: The syntax to declare multidimensional array in java is either int[][] arr; or int arr[][];
advertisement
public class array
{
public static void main(String args[])
{
int []arr = {1,2,3,4,5};
System.out.println(arr[2]);
System.out.println(arr[4]);
}
}
a) 3 and 5
b) 5 and 3
c) 2 and 4
d) 4 and 2
Answer: a
Explanation: Array indexing starts from 0.
a) 4
b) 5
c) ArrayIndexOutOfBoundsException
d) InavlidInputException
Answer: c
Explanation: Trying to access an element beyond the limits of an array gives
ArrayIndexOutOfBoundsException.
Answer: b
Explanation: ArrayIndexOutOfBoundsException is a run-time exception and the compilation is error-free.
Answer: d
Explanation: Whenever a particular memory location is referred to, it is likely that the locations nearby are
also referred, arrays are stored as contiguous blocks in memory, so if you want to access array elements,
spatial locality makes it to access quickly.
Answer: b
Explanation: Arrays are of fixed size. If we insert elements less than the allocated size, unoccupied positions
can’t be used again. Wastage will occur in memory.
Answer: d
Explanation: Since there are 15 int elements and each int is of 4bytes, we get 15*4 = 60bytes.
Answer: a
Explanation: In general, Array Indexing starts from 0. Thus, the index of the first element in an array is 0.
Answer: a
Explanation: Elements in an array are accessed randomly. In Linked lists, elements are accessed
sequentially.
Answer: d
Explanation: Elements in the stack are removed using pop operation. Pop operation removes the top most
element in the stack i.e. last entered element.
3. In a stack, if a user tries to remove an element from an empty stack it is called _________
a) Underflow
b) Empty collection
c) Overflow
d) Garbage Collection
Answer: a
Explanation: Underflow occurs when the user performs a pop operation on an empty stack. Overflow occurs
when the stack is full and the user performs a push operation. Garbage Collection is used to recover the
memory occupied by objects that are no longer used.
4. Pushing an element into stack already having five elements and stack size of 5, then stack becomes
___________
a) Overflow
b) Crash
c) Underflow
d) User flow
Answer: a
Explanation: The stack is filled with 5 elements and pushing one more element causes a stack overflow. This
results in overwriting memory, code and loss of unsaved work on the computer.
Answer: d
Explanation: In stack data structure, elements are added one by one using push operation. Stack follows
LIFO Principle i.e. Last In First Out(LIFO).
advertisement
Answer: d
Explanation: Data transfer between the two asynchronous process uses the queue data structure for
synchronisation. The rest are all stack applications.
7. Consider the usual algorithm for determining whether a sequence of parentheses is balanced. The
maximum number of parentheses that appear on the stack AT ANY ONE TIME when the algorithm
analyzes: (()(())(()))?
a) 1
b) 2
c) 3
d) 4 or more
Answer: c
Explanation: In the entire parenthesis balancing method when the incoming token is a left parenthesis it is
pushed into stack. A right parenthesis makes pop operation to delete the elements in stack till we get left
parenthesis as top most element. 3 elements are there in stack before right parentheses comes. Therefore,
maximum number of elements in stack at run time is 3.
8. Consider the usual algorithm for determining whether a sequence of parentheses is balanced. Suppose that
you run the algorithm on a sequence that contains 2 left parentheses and 3 right parentheses (in some order).
The maximum number of parentheses that appear on the stack AT ANY ONE TIME during the
computation?
a) 1
b) 2
c) 3
d) 4 or more
Answer: b
Explanation: In the entire parenthesis balancing method when the incoming token is a left parenthesis it is
pushed into stack. A right parenthesis makes pop operation to delete the elements in stack till we get left
parenthesis as top most element. 2 left parenthesis are pushed whereas one right parenthesis removes one of
left parenthesis. 2 elements are there before right parenthesis which is the maximum number of elements in
stack at run time.
Answer: d
Explanation: Postfix Expression is (6*(3-(2+4))) which results -18 as output.
10. Here is an infix expression: 4 + 3*(6*3-12). Suppose that we are using the usual stack algorithm to
convert the expression from infix to postfix notation. The maximum number of symbols that will appear on
the stack AT ONE TIME during the conversion of this expression?
a) 1
b) 2
c) 3
d) 4
Answer: d
Explanation: When we perform the conversion from infix to postfix expression +, *, (, * symbols are placed
inside the stack. A maximum of 4 symbols are identified during the entire conversion
Answer: c
Explanation: (((A+ B)*(C*D- E)*F) / G) is converted to postfix expression as
(AB+(*(C*D- E)*F )/ G)
(AB+CD*E-*F) / G
(AB+CD*E-*F * G/). Thus Postfix expression is AB+CD*E-*F*G/
2. The data structure required to check whether an expression contains a balanced parenthesis is?
a) Stack
b) Queue
c) Array
d) Tree
Answer: a
Explanation: The stack is a simple data structure in which elements are added and removed based on the
LIFO principle. Open parenthesis is pushed into the stack and a closed parenthesis pops out elements till the
top element of the stack is its corresponding open parenthesis. If the stack is empty, parenthesis is balanced
otherwise it is unbalanced.
3. What data structure would you mostly likely see in non recursive implementation of a recursive
algorithm?
a) Linked List
b) Stack
c) Queue
d) Tree
Answer: b
Explanation: In recursive algorithms, the order in which the recursive process comes back is the reverse of
the order in which it goes forward during execution. The compiler uses the stack data structure to implement
recursion. In the forwarding phase, the values of local variables, parameters and the return address are
pushed into the stack at each recursion level. In the backing-out phase, the stacked address is popped and
used to execute the rest of the code.
4. The process of accessing data stored in a serial access memory is similar to manipulating data on a
________
a) Heap
b) Binary Tree
c) Array
d) Stack
Answer: d
Explanation: In serial access memory data records are stored one after the other in which they are created
and are accessed sequentially. In stack data structure, elements are accessed sequentially. Stack data
structure resembles the serial access memory.
Answer: b
Explanation: Infix expression is (A*B)+(C/D)
AB*+(C/D)
AB*CD/+. Thus postfix expression is AB*CD/+.
advertisement
Answer: d
Explanation: The Stack data structure is used to convert infix expression to postfix expression. The purpose
of stack is to reverse the order of the operators in the expression. It also serves as a storage structure, as no
operator can be printed until both of its operands have appeared.
Answer: c
Explanation: Infix Expression is (A-B)/(C*D^E)
(-A/B)(C*D^E)
-A/B*C^DE. Thus prefix expression is -A/B*C^DE.
Answer: a
Explanation: The function Push(S,X) pushes the value X in the stack S. Top() function gives the value
which entered last. X entered into stack S at last.
9. The prefix form of an infix expression (p + q) – (r * t) is?
a) + pq – *rt
b) – +pqr * t
c) – +pq * rt
d) – + * pqrt
Answer: c
Explanation: Given Infix Expression is ((p+q)-(r*t))
(+pq)-(r*t)
(-+pq)(r*t)
-+pq*rt. Thus prefix expression is -+pq*rt.
Answer: b
Explanation: Stacks are used for the implementation of Recursion.
Answer: b
Explanation: The postfix expression is evaluated using stack. We will get the infix expression as
(5*(4+6))*(4+9/3). On solving the Infix Expression, we get
(5*(10))*(4+3)
= 50*7
= 350.
2. Convert the following infix expressions into its equivalent postfix expressions.
(A + B ⋀D)/(E – F)+G
a) (A B D ⋀ + E F – / G +)
b) (A B D +⋀ E F – / G +)
c) (A B D ⋀ + E F/- G +)
d) (A B D E F + ⋀ / – G +)
Answer: a
Explanation: The given infix expression is (A + B ⋀D)/(E – F)+G.
(A B D ^ + ) / (E – F) +G
(A B D ^ + E F – ) + G. ‘/’ is present in stack.
A B D ^ + E F – / G +. Thus Postfix Expression is A B D ^ + E F – / G +.
Answer: a
Explanation: The Infix Expression is x + y * z + (p * q + r) * s.
(x y z ) + (p * q + r) * s. ‘+’, ‘*’ are present in stack.
(x y z * + p q * r) * s. ‘+’ is present in stack.
x y z * + p q * r + s * +. Thus Postfix Expression is x y z * + p q * r + s * +.
4. Which of the following statement(s) about stack data structure is/are NOT correct?
a) Linked List are used for implementing Stacks
b) Top of the Stack always contain the new node
c) Stack is the FIFO data structure
d) Null link is present in the last node at the bottom of the stack
Answer: c
Explanation: Stack follows LIFO.
Push(1);
Pop();
Push(2);
Push(3);
Pop();
Push(4);
Pop();
Pop();
Push(5);
advertisement
After the completion of all operation, the number of elements present in stack is?
a) 1
b) 2
c) 3
d) 4
Answer: a
Explanation: Number of elements present in stack is equal to the difference between number of push
operations and number of pop operations. Number of elements is 5-4=1.
Answer: d
Explanation: Job Scheduling is not performed using stacks.
Answer: c
Explanation: The expression in which operator succeeds its operands is called postfix expression. The
expression in which operator precedes the operands is called prefix expression. If an operator is present
between two operands, then it is called infix expressions.
8. Assume that the operators +,-, X are left associative and ^ is right associative. The order of precedence
(from highest to lowest) is ^, X, +, -. The postfix expression for the infix expression a + b X c – d ^ e ^ f is?
a) abc X+ def ^^ –
b) abc X+ de^f^ –
c) ab+c Xd – e ^f^
d) -+aXbc^ ^def
Answer: b
Explanation: Given Infix Expression is a + b X c – d ^ e ^ f.
(a b c X +) (d ^ e ^ f). ‘–‘ is present in stack.
(a b c X + d e ^ f ^ -). Thus the final expression is (a b c X + d e ^ f ^ -).
9. If the elements “A”, “B”, “C” and “D” are placed in a stack and are deleted one at a time, what is the
order of removal?
a) ABCD
b) DCBA
c) DCAB
d) ABDC
Answer: b
Explanation: Stack follows LIFO(Last In First Out). So the removal order of elements are DCBA.
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
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
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.
advertisement
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
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
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.
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
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
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
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.
advertisement
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)
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)
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)
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)
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
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
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.
2. Linked lists are not suitable for the implementation of ___________
a) Insertion sort
b) Radix sort
c) Polynomial manipulation
d) Binary search
Answer: d
Explanation: It cannot be implemented using linked lists.
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.
advertisement
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
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?
void fun1(struct node* head)
{
if(head == NULL)
return;
fun1(head->next);
printf("%d ", head->data);
}
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
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.
1. The following function reverse() is supposed to reverse a singly linked list. There is one line missing at
the end of the function.
What should be added in place of “/*ADD A STATEMENT HERE*/”, so that the function correctly
reverses a linked list.
a) *head_ref = prev;
b) *head_ref = current;
c) *head_ref = next;
d) *head_ref = NULL;
Answer: a
Explanation: *head_ref = prev; At the end of while loop, the prev pointer points to the last node of original
linked list.
We need to change *head_ref so that the head pointer now starts pointing to the last node.
2. What is the output of following function for start pointing to first node of following linked list?
1->2->3->4->5->6
void fun(struct node* start)
{
if(start == NULL)
return;
printf("%d ", start->data);
if(start->next != NULL )
fun(start->next->next);
printf("%d ", start->data);
}
a) 1 4 6 6 4 1
b) 1 3 5 1 3 5
c) 1 2 3 5
d) 1 3 5 5 3 1
Answer: d
Explanation: fun() prints alternate nodes of the given Linked List, first from head to end, and then from end
to head.
If Linked List has even number of nodes, then skips the last node.
advertisement
3. The following C function takes a simply-linked list as an input argument. It modifies the list by moving
the last element to the front of the list and returns the modified list. Some part of the code is left blank.
Choose the correct alternative to replace the blank line.
Answer: d
Explanation: When while loop completes its execution, node ‘p’ refers to the last node whereas the ‘q’ node
refers to the node before ‘p’ in the linked list. q->next=NULL makes q as the last node. p->next=head places
p as the first node. the head must be modified to ‘p’ as ‘p’ is the starting node of the list (head=p). Thus the
sequence of steps are q->next=NULL, p->next=head, head=p.
4. The following C function takes a single-linked list of integers as a parameter and rearranges the elements
of the list. The function is called with the list containing the integers 1, 2, 3, 4, 5, 6, 7 in the given order.
What will be the contents of the list after the function completes execution?
struct node
{
int value;
struct node *next;
};
void rearrange(struct node *list)
{
struct node *p, * q;
int temp;
if ((!list) || !list->next)
return;
p = list;
q = list->next;
while(q)
{
temp = p->value;
p->value = q->value;
q->value = temp;
p = q->next;
q = p?p->next:0;
}
}
a) 1, 2, 3, 4, 5, 6, 7
b) 2, 1, 4, 3, 6, 5, 7
c) 1, 3, 2, 5, 4, 7, 6
d) 2, 3, 4, 5, 6, 7, 1
Answer: b
Explanation: The function rearrange() exchanges data of every node with its next node. It starts exchanging
data from the first node itself.
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
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
Answer: a
Explanation: Following are simple steps.
struct node *temp = X->next;
X->data = temp->data;
X->next = temp->next;
free(temp);
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
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
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
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.
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)
Answer: b
Explanation: To count the number of elements, you have to traverse through the entire list, hence complexity
is O(n).
4. Which of the following performs deletion of the last element in the list? Given below is the Node class.
class Node
{
protected Node next;
protected Object ele;
Node(Object e,Node n)
{
ele = e;
next = n;
}
public void setNext(Node n)
{
next = n;
}
public void setEle(Object e)
{
ele = e;
}
public Node getNext()
{
return next;
}
public Object getEle()
{
return ele;
}
}
class SLL
{
Node head;
int size;
SLL()
{
size = 0;
}
}
a)
b)
advertisement
public void removeLast()
{
if(size == 0)
return null;
Node cur;
Node temp;
cur = head;
while(cur != null)
{
temp = cur;
cur = cur.getNext();
}
temp.setNext(null);
return cur;
}
c)
Answer: a
Explanation: Since you have to traverse to the end of the list and delete the last node, you need two
reference pointers. ‘cur’ to traverse all the way and find the last node, and ‘temp’ is a trailing pointer to
‘cur’. Once you reach the end of the list, setNext of ‘temp’ to null, ‘cur’ is not being pointed to by any node,
and hence it is available for garbage collection.
Answer: c
Explanation: The for loop traverses through the list and then inserts a new node as cur.setNext(node);
Answer: a
Explanation: You need a temp variable to keep track of current node, hence the space complexity is O(1).
7. How would you delete a node in the singly linked list? The position to be deleted is given.
a)
b)
c)
d)
Answer: a
Explanation: Loop through the list to get into position one behind the actual position given.
temp.setNext(temp.getNext().getNext()) will delete the specified node.
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.
9. Which of the following piece of code has the functionality of counting the number of elements in the list?
a)
b)
c)
d)
Answer: a
Explanation: ‘cur’ pointer traverses through list and increments the size variable until the end of list is
reached.
b)
public void insertBegin(Node node)
{
head = node;
node.setNext(head);
size++;
}
c)
d)
Answer: a
Explanation: Set the ‘next’ pointer point to the head of the list and then make this new node as the head.
Answer: c
Explanation: When temp is equal to data, the position of data is returned.
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.
2. Given the Node class implementation, select one of the following that correctly inserts a node at the tail of
the list.
a)
b)
c)
advertisement
public void insertRear(int data)
{
Node node = new Node(data,tail.getPrev(),tail);
node.getPrev().setNext(tail);
tail.setPrev(node);
length++;
}
d)
Answer: a
Explanation: First create a new node whose ‘prev’ points to the node pointed to by the ‘prev’ of tail. The
‘next’ of the new node should point to tail. Set the ‘prev’ of tail to point to new node and the ‘prev’ of new
node to point to the new node.
4. Which of the following piece of code removes the node from a given position?
a)
b)
c)
d)
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
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)
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).
b)
c)
Answer: a
Explanation: The new node’s previous pointer will point to head and next pointer will point to the current
next of head.
8. Consider the following doubly linked list: head-1-2-3-4-5-tail. What will be the list after performing the
given sequence of operations?
a) head-0-1-2-3-4-5-6-tail
b) head-1-2-3-4-5-6-tail
c) head-6-1-2-3-4-5-0-tail
d) head-0-1-2-3-4-5-tail
Answer: c
Explanation: The given sequence of operations performs addition of nodes at the head and tail of the list.
a) Return the element at the tail of the list but do not remove it
b) Return the element at the tail of the list and remove it from the list
c) Return the last but one element from the list but do not remove it
d) Return the last but one element at the tail of the list and remove it from the list
Answer: b
Explanation: The previous and next pointers of the tail and the last but one element are manipulated, this
suggests that the last node is being removed from the list.
10. Consider the following doubly linked list: head-1-2-3-4-5-tail. What will be the list after performing the
given sequence of operations?
Node temp = new Node(6,head,head.getNext());
head.setNext(temp);
temp.getNext().setPrev(temp);
Node temp1 = tail.getPrev();
tail.setPrev(temp1.getPrev());
temp1.getPrev().setNext(tail);
a) head-6-1-2-3-4-5-tail
b) head-6-1-2-3-4-tail
c) head-1-2-3-4-5-6-tail
d) head-1-2-3-4-5-tail
Answer: b
Explanation: A new node is added to the head of the list and a node is deleted from the tail end of the list.
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).
2. How do you count the number of elements in the circular linked list?
a)
b)
c)
public int length(Node head)
{
int length = 0;
if( head == null)
return 0;
Node temp = head.getNext();
while(temp != head && temp != null)
{
temp = head.getNext();
length++;
}
return length;
}
d)
advertisement
public int length(Node head)
{
int length = 0;
if( head == null)
return 0;
Node temp = head.getNext();
while(temp != head && temp == null)
{
temp = head.getNext();
length++;
}
return length;
}
Answer: a
Explanation: If the head is null, it means that the list is empty. Otherwise, traverse the list until the head of
the list is reached.
3. What is the functionality of the following piece of code? Select the most appropriate.
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)
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.
6. Choose the code snippet which inserts a node to the head of the list?
a)
b)
c)
d)
Answer: a
Explanation: If the list is empty make the new node as ‘head’, otherwise traverse the list to the end and make
its ‘next’ pointer point to the new node, set the new node’s next point to the current head and make the new
node as the head.
7. What is the functionality of the following code? Choose the most appropriate answer.
Answer: d
Explanation: First traverse through the list to find the end node, then manipulate the ‘next’ pointer such that
it points to the current head’s next node, return the data stored in head and make this next node as the head.
8. What is the functionality of the following code? Choose the most appropriate answer.
Answer: b
Explanation: First traverse through the list to find the end node, also have a trailing pointer to find the
penultimate node, make this trailing pointer’s ‘next’ point to the head and return the data stored in the
‘temp’ node.
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
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. Which of the following real world scenarios would you associate with a stack data structure?
a) piling up of chairs one above the other
b) people standing in a line to be serviced at a counter
c) offer services based on the priority of the customer
d) tatkal Ticket Booking in IRCTC
Answer: a
Explanation: Stack follows Last In First Out (LIFO) policy. Piling up of chairs one above the other is based
on LIFO, people standing in a line is a queue and if the service is based on priority, then it can be associated
with a priority queue. Tatkal Ticket Booking Follows First in First Out Policy. People who click the book
now first will enter the booking page first.
2. What does the following function check for? (all necessary headers to be included and function is called
from main)
#define MAX 10
typedef struct stack
{
int top;
int item[MAX];
}stack;
int function(stack *s)
{
if(s->top == -1)
return 1;
else return 0;
}
a) full stack
b) invalid index
c) empty stack
d) infinite stack
Answer: c
Explanation: An empty stack is represented with the top-of-the-stack(‘top’ in this case) to be equal to -1.
Answer: c
Explanation: Removing items from an empty stack is termed as stack underflow.
advertisement
a) stack is full
b) 20
c) 0
d) -999
Answer: d
Explanation: The first call to pop() returns 10, whereas the second call to pop() would result in stack
underflow and the program returns -999.
5. What is the time complexity of pop() operation when the stack is implemented using an array?
a) O(1)
b) O(n)
c) O(logn)
d) O(nlogn)
Answer: a
Explanation: pop() accesses only one end of the structure, and hence constant time.
6. Which of the following array position will be occupied by a new element being pushed for a stack of size
N elements(capacity of stack > N)?
a) S[N-1]
b) S[N]
c) S[1]
d) S[0]
Answer: b
Explanation: Elements are pushed at the end, hence N.
7. What happens when you pop from an empty stack while implementing using the Stack ADT in Java?
a) Undefined error
b) Compiler displays a warning
c) EmptyStackException is thrown
d) NoStackException is thrown
Answer: c
Explanation: The Stack ADT throws an EmptyStackException if the stack is empty and a pop() operation is
tried on it.
Answer: d
Explanation: Every element from the given array ‘a’ is pushed into the stack, and then the elements are
popped out into the array ‘b’. Stack is a LIFO structure, this results in reversing the given array.
9. Array implementation of Stack is not dynamic, which of the following statements supports this argument?
a) space allocation for array is fixed and cannot be changed during run-time
b) user unable to give the input for stack operations
c) a runtime exception halts execution
d) improper program compilation
Answer: a
Explanation: You cannot modify the size of an array once the memory has been allocated, adding fewer
elements than the array size would cause wastage of space, and adding more elements than the array size at
run time would cause Stack Overflow.
10. Which of the following array element will return the top-of-the-stack-element for a stack of size N
elements(capacity of stack > N)?
a) S[N-1]
b) S[N]
c) S[N-2]
d) S[N+1]
Answer: a
Explanation: Array indexing start from 0, hence N-1 is the last index.
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)
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
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).
3. Given below is the Node class to perform basic list operations and a Stack class with a no arg constructor.
Select from the options the appropriate pop() operation that can be included in the Stack class. Also ‘first’ is
the top-of-the-stack.
class Node
{
protected Node next;
protected Object ele;
Node()
{
this(null,null);
}
Node(Object e,Node n)
{
ele=e;
next=n;
}
public void setNext(Node n)
{
next=n;
}
public void setEle(Object e)
{
ele=e;
}
public Node getNext()
{
return next;
}
public Object getEle()
{
return ele;
}
}
class Stack
{
Node first;
int size=0;
Stack()
{
first=null;
}
}
a)
b)
advertisement
public Object pop()
{
if(size == 0)
System.out.println("underflow");
else
{
Object o = first.getEle();
first = first.getNext().getNext();
size--;
return o;
}
}
c)
d)
Answer: a
Explanation: pop() should return the Object pointed to by the node ‘first’. The sequence of operations is,
first, get the element stored at node ‘first’ using getEle(), and second, make the node point to the next node
using getNext().
4. What does the following function do?
a) pop
b) delete the top-of-the-stack element
c) retrieve the top-of-the-stack element
d) push operation
Answer: c
Explanation: This code is only retrieving the top element, note that it is not equivalent to pop operation as
you are not setting the ‘next’ pointer point to the next node in sequence.
Answer: b
Explanation: An alias of the node ‘first’ is created which traverses through the list and displays the elements.
Answer: b
Explanation: Adding items to a full stack is termed as stack underflow.
7. Given below is the Node class to perform basic list operations and a Stack class with a no arg constructor.
Select from the options the appropriate push() operation that can be included in the Stack class. Also ‘first’
is the top-of-the-stack.
class Node
{
protected Node next;
protected Object ele;
Node()
{
this(null,null);
}
Node(Object e,Node n)
{
ele=e;
next=n;
}
public void setNext(Node n)
{
next=n;
}
public void setEle(Object e)
{
ele=e;
}
public Node getNext()
{
return next;
}
public Object getEle()
{
return ele;
}
}
class Stack
{
Node first;
int size=0;
Stack()
{
first=null;
}
}
a)
b)
c)
d)
Answer: a
Explanation: To push an element into the stack, first create a new node with the next pointer point to the
current top-of-the-stack node, then make this node as top-of-the-stack by assigning it to ‘first’.
push(20);
push(4);
top();
pop();
pop();
pop();
push(5);
top();
a) 20
b) 4
c) stack underflow
d) 5
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
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.
10. Minimum number of queues to implement stack is ___________
a) 3
b) 4
c) 1
d) 2
Answer: c
Explanation: Use one queue and one counter to count the number of elements in the queue.
Answer: b
Explanation: Queue follows First In First Out structure.
2. In a circular queue, how do you increment the rear end of the queue?
a) rear++
b) (rear+1) % CAPACITY
c) (rear % CAPACITY)+1
d) rear–
Answer: b
Explanation: Ensures rear takes the values from 0 to (CAPACITY-1).
3. What is the term for inserting into a full queue known as?
a) overflow
b) underflow
c) null pointer exception
d) program won’t be compiled
Answer: a
Explanation: Just as stack, inserting into a full queue is termed overflow.
Answer: d
Explanation: Enqueue operation is at the rear end, it takes O(1) time to insert a new item into the queue.
a) Dequeue
b) Enqueue
c) Return the front element
d) Return the last element
Answer: c
Explanation: q[front] gives the element at the front of the queue, since we are not moving the ‘front’ to the
next element,
it is not a dequeue operation.
advertisement
Answer: a
Explanation: In a linear queue, dequeue operation causes the starting elements of the array to be empty, and
there is no way you can use that space, while in a circular queue, you can effectively use that space. Priority
queue is used to delete the elements based on their priority. Higher priority elements will be deleted first
whereas lower priority elements will be deleted next. Queue data structure always follows FIFO principle.
7. Which of the following represents a dequeue operation? (count is the number of elements in the queue)
a)
b)
c)
d)
Answer: a
Explanation: Dequeue removes the first element from the queue, ‘front’ points to the front end of the queue
and returns the first element.
8. Which of the following best describes the growth of a linear queue at runtime? (Q is the original queue,
size() returns the number of elements in the queue)
a)
b)
c)
d)
Answer: a
Explanation: A common technique to expand the size of array at run time is simply to double the size.
Create a new array of double the previous size and copy all the elements, after copying do not forget to
assign front = 0 and rear = size()-1, as these are necessary to maintain the decorum of the queue operations.
a) 3 3
b) 3 6
c) 6 6
d) 10 6
Answer: a
Explanation: First enqueue 10 and 3 into the queue, followed by a dequeue(removes 10), followed by an
enqueue(6), At this point, 3 is at the front end of the queue and 6 at the rear end, hence a call to
frontElement() will return 3 which is displayed twice.
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
Answer: d
Explanation: Since front pointer is used for deletion, so worst time for the other two cases.
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
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
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
Answer: a
Explanation: All the nodes are collected in AVAIL list.
advertisement
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
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
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
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
Answer: a
Explanation: It can be done by both the methods.
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.
3. Select the appropriate code that inserts elements into the list based on the given key value.
(head and trail are dummy nodes to mark the end and beginning of the list, they do not contain any priority
or element)
a)
b)
advertisement
public void insert_key(int key,Object item)
{
if(key<0)
{
Systerm.our.println("invalid");
System.exit(0);
}
else
{
Node temp = new Node(key,item,null);
if(count == 0)
{
head.setNext(temp);
temp.setNext(trail);
}
else
{
Node dup = head.getNext();
Node cur = dup;
while((key>dup.getKey()) && (dup!=trail))
{
dup = dup.getNext();
cur = cur.getNext();
}
cur.setNext(temp);
temp.setNext(dup);
}
count++;
}
}
c)
d)
Answer: a
Explanation: Have two temporary pointers ‘dup’ and ‘cur’ with ‘cur’ trailing behind ‘dup’. Traverse through
the list until the given key is greater than some element with a lesser key, insert the new node ‘temp’ in that
position.
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)
Answer: c
Explanation: In the worst case, you might have to traverse the entire list.
Answer: c
Explanation: A pointer is made to point at the first element in the list and one more to point to the second
element, pointer manipulations are done such that the first element is no longer being pointed by any other
pointer, its value is returned.
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)
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
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.
2. Select the function which performs insertion at the front end of the dequeue?
a)
b)
public void function(Object item)
{
Node temp = new Node(item,null);
if(isEmpty())
{
temp.setNext(trail);
head.setNext(trail);
}
else
{
Node cur = head.getNext();
temp.setNext(cur);
head.setNext(temp);
}
size++;
}
c)
d)
advertisement
public void function(Object item)
{
Node temp = new Node(item,null);
if(isEmpty())
{
Node cur = head.getNext();
temp.setNext(cur);
cur.setNext(temp);
}
else
{
head.setNext(trail);
trail.setNext(temp);
}
size++;
}
Answer: a
Explanation: Create a new node, if the current list is empty, the ‘head’ points to this node and this new node
points to ‘trail’. Otherwise, ‘head’ points to the new node and this in turn points to the current first
element(head.getNext()).
3. What is the functionality of the following piece of code?
public void function(Object item)
{
Node temp=new Node(item,trail);
if(isEmpty())
{
head.setNext(temp);
temp.setNext(trail);
}
else
{
Node cur=head.getNext();
while(cur.getNext()!=trail)
{
cur=cur.getNext();
}
cur.setNext(temp);
}
size++;
}
Answer: b
Explanation: If the list is empty, this new node will point to ‘trail’ and will be pointed at by ‘head’.
Otherwise, traverse till the end of the list and insert the new node there.
Answer: d
Explanation: All of the mentioned can be implemented with a dequeue.
5. Which of the following can be used to delete an element from the front end of the queue?
a)
b)
c)
d)
Answer: b
Explanation: Have two pointers, one(temp) pointing to the first element and the other(cur) pointing to the
second element. Make the ‘head’ point to the second element, this removes all reference for ‘temp’.
6. Which of the following can be used to delete an element from the rear end of the queue?
a)
public Object deleteRear() throws emptyDEQException
{
if(isEmpty())
throw new emptyDEQException("Empty");
else
{
Node temp = head.getNext();
Node cur = temp;
while(temp.getNext() != trail)
{
temp = temp.getNext();
cur = cur.getNext();
}
Object e = temp.getEle();
cur.setNext(trail);
size--;
return e;
}
}
b)
c)
d)
Answer: c
Explanation: Traverse till the end of the list with a pointer ‘temp’ and another ‘cur’ which is trailing behind
temp, make ‘cur’ point to trail, this removes all reference for ‘temp’.
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)
Answer: c
Explanation: Since a singly linked list is used, first you have to traverse till the end, so the complexity is
O(n).
8. After performing these set of operations, what does the final list look contain?
InsertFront(10);
InsertFront(20);
InsertRear(30);
DeleteFront();
InsertRear(40);
InsertRear(10);
DeleteRear();
InsertRear(15);
display();
a) 10 30 10 15
b) 20 30 40 15
c) 20 30 40 10
d) 10 30 40 15
Answer: d
Explanation: A careful tracing of the given operation yields the result.
10
20 10
20 10 30
10 30
10 30 40
10 30 40 10
10 30 40
10 30 40 15
1. A Double-ended queue supports operations such as adding and removing items from both the sides of the
queue. They support four operations like addFront(adding item to top of the queue), addRear(adding item to
the bottom of the queue), removeFront(removing item from the top of the queue) and removeRear(removing
item from the bottom of the queue). You are given only stacks to implement this data structure. You can
implement only push and pop operations. What are the total number of stacks required for this operation?
(you can reuse the stack)
a) 1
b) 2
c) 3
d) 4
Answer: b
Explanation: The addFront and removeFront operations can be performed using one stack itself as push and
pop are supported (adding and removing element from top of the stack) but to perform addRear and
removeRear you need to pop each element from the current stack and push it into another stack, push or pop
the element as per the asked operation from this stack and in the end pop elements from this stack to the first
stack.
2. You are asked to perform a queue operation using a stack. Assume the size of the stack is some value ‘n’
and there are ‘m’ number of variables in this stack. The time complexity of performing deQueue operation is
(Using only stack operations like push and pop)(Tightly bound).
a) O(m)
b) O(n)
c) O(m*n)
d) Data is insufficient
Answer: a
Explanation: To perform deQueue operation you need to pop each element from the first stack and push it
into the second stack. In this case you need to pop ‘m’ times and need to perform push operations also ‘m’
times. Then you pop the first element from this second stack (constant time) and pass all the elements to the
first stack (as done in the beginning)(‘m-1’ times). Therfore the time complexity is O(m).
3. Consider you have an array of some random size. You need to perform dequeue operation. You can
perform it using stack operation (push and pop) or using queue operations itself (enQueue and Dequeue).
The output is guaranteed to be same. Find some differences?
a) They will have different time complexities
b) The memory used will not be different
c) There are chances that output might be different
d) No differences
Answer: a
Explanation: To perform operations such as Dequeue using stack operation you need to empty all the
elements from the current stack and push it into the next stack, resulting in a O(number of elements)
complexity whereas the time complexity of dequeue operation itself is O(1). And there is a need of a extra
stack. Therefore more memory is needed.
Answer: a
Explanation: By performing push(pop()) on all elements on the current stack to the next stack you get 2 3 4
5 << top.Push(6) and perform push(pop()) you’ll get back 6 5 4 3 2 << top. You have actually performed
enQueue operation using push and pop.
5. A double-ended queue supports operations like adding and removing items from both the sides of the
queue. They support four operations like addFront(adding item to top of the queue), addRear(adding item to
the bottom of the queue), removeFront(removing item from the top of the queue) and removeRear(removing
item from the bottom of the queue). You are given only stacks to implement this data structure. You can
implement only push and pop operations. What’s the time complexity of performing addFront and addRear?
(Assume ‘m’ to be the size of the stack and ‘n’ to be the number of elements)
a) O(m) and O(n)
b) O(1) and O(n)
c) O(n) and O(1)
d) O(n) and O(m)
Answer: b
Explanation: addFront is just a normal push operation. Push operation is of O(1). Whereas addRear is of
O(n) as it requires two push(pop()) operations of all elements of a stack.
advertisement
6. Why is implementation of stack operations on queues not feasible for a large dataset (Asssume the
number of elements in the stack to be n)?
a) Because of its time complexity O(n)
b) Because of its time complexity O(log(n))
c) Extra memory is not required
d) There are no problems
Answer: a
Explanation: To perform Queue operations such as enQueue and deQueue there is a need of emptying all the
elements of a current stack and pushing elements into the next stack and vice versa. Therfore it has a time
complexity of O(n) and the need of extra stack as well, may not be feasible for a large dataset.
7. Consider yourself to be in a planet where the computational power of chips to be slow. You have an array
of size 10.You want to perform enqueue some element into this array. But you can perform only push and
pop operations .Push and pop operation both take 1 sec respectively. The total time required to perform
enQueue operation is?
a) 20
b) 40
c) 42
d) 43
Answer: d
Explanation: First you have to empty all the elements of the current stack into the temporary stack, push the
required element and empty the elements of the temporary stack into the original stack. Therfore taking
10+10+1+11+11= 43 seconds.
8. You have two jars, one jar which has 10 rings and the other has none. They are placed one above the
other. You want to remove the last ring in the jar. And the second jar is weak and cannot be used to store
rings for a long time.
a) Empty the first jar by removing it one by one from the first jar and placing it into the second jar
b) Empty the first jar by removing it one by one from the first jar and placing it into the second jar and
empty the second jar by placing all the rings into the first jar one by one
c) There exists no possible way to do this
d) Break the jar and remove the last one
Answer: b
Explanation: This is similar to performing dequeue operation using push and pop only. Elements in the first
jar are taken out and placed in the second jar. After removing the last element from the first jar, remove all
the elements in the second jar and place them in the first jar.
9. Given only a single array of size 10 and no other memory is available. Which of the following operation
is not feasible to implement (Given only push and pop operation)?
a) Push
b) Pop
c) Enqueue
d) Returntop
Answer: c
Explanation: To perform Enqueue using just push and pop operations, there is a need of another array of
same size. But as there is no extra available memeory, the given operation is not feasible.
10. Given an array of size n, let’s assume an element is ‘touched’ if and only if some operation is performed
on it(for example, for performing a pop operation the top element is ‘touched’). Now you need to perform
Dequeue operation. Each element in the array is touched atleast?
a) Once
b) Twice
c) Thrice
d) Four times
Answer: d
Explanation: First each element from the first stack is popped, then pushed into the second stack, dequeue
operation is done on the top of the stack and later the each element of second stack is popped then pushed
into the first stack. Therfore each element is touched four times.
1. To implement a stack using queue(with only enqueue and dequeue operations), how many queues will
you need?
a) 1
b) 2
c) 3
d) 4
Answer: b
Explanation: Either the push or the pop has to be a costly operation, and the costlier operation requires two
queues.
2. Making the push operation costly, select the code snippet which implements the same.(let q1 and q2 be
two queues)
a)
public void push(int x)
{
if(empty())
{
q1.offer(x);
}
else{
if(q1.size()>0)
{
q2.offer(x);
int size = q1.size();
while(size>0)
{
q2.offer(q1.poll());
size--;
}
}
else if(q2.size()>0)
{
q1.offer(x);
int size = q2.size();
while(size>0)
{
q1.offer(q2.poll());
size--;
}
}
}
}
b)
c)
d)
Answer: a
Explanation: Stack follows LIFO principle, hence a new item added must be the first one to exit, but queue
follows FIFO principle, so when a new item is entered into the queue, it will be at the rear end of the queue.
If the queue is initially empty, then just add the new element, otherwise add the new element to the second
queue and dequeue all the elements from the second queue and enqueue it to the first one, in this way, the
new element added will be always in front of the queue. Since two queues are needed to realize this push
operation, it is considered to be costlier.
3. Making the push operation costly, select the code snippet which implements the pop operation.
a)
advertisement
public void pop()
{
if(q1.size()>0)
{
q2.poll();
}
else if(q2.size()>0)
{
q1.poll();
}
}
b)
c)
d)
Answer: b
Explanation: As the push operation is costly, it is evident that the required item is in the front of the queue,
so just dequeue the element from the queue.
4. Select the code snippet which returns the top of the stack.
a)
public int top()
{
if(q1.size()>0)
{
return q1.poll();
}
else if(q2.size()>0)
{
return q2.poll();
}
return 0;
}
b)
c)
d)
Answer: c
Explanation: Assuming its a push costly implementation, the top of the stack will be in the front end of the
queue, note that peek() just returns the front element, while poll() removes the front element from the queue.
5. Select the code snippet which return true if the stack is empty, false otherwise.
a)
public boolean empty()
{
return q2.isEmpty();
}
b)
c)
d)
Answer: b
Explanation: If both the queues are empty, then the stack also is empty.
6. Making the pop operation costly, select the code snippet which implements the same.
a)
public int pop()
{
int res=-999,count=0;
if(q1.size()>0)
{
count = q1.size();
while(count>0)
q2.offer(q1.poll());
res = q1.poll();
}
if(q2.size()>0)
{
count = q2.size();
while(count>0)
q1.offer(q2.poll());
res = q2.poll();
}
return res;
}
b)
c)
d)
Answer: c
Explanation: Here the pop operation is costly, hence we need two queues, other than the first element, all the
the elements from one queue are dequeued and enqueued to the second queue, hence only one element
remains in the first queue which is the item we want, so dequeue it and return the result.
7. What is the functionality of the following piece of code?
public void fun(int x)
{
q1.offer(x);
}
Answer: b
Explanation: offer() suggests that it is a push operation, but we see that it is performed with only one queue,
hence the pop operation is costlier.
Answer: b
Explanation: The first 4 1s from the right represent the number 15, 2 more bits are padded to make it 6 digits
and the leftmost bit is a 1 to represent that it is -15.
2. Which of the following code snippet is used to convert decimal to binary numbers?
a)
b)
c)
d)
Answer: a
Explanation: Take the modulus by 2 of the number and store in an array while halving the number during
each iteration and then display the contents of the array.
3. Which is the predefined method available in Java to convert decimal to binary numbers?
a) toBinaryInteger(int)
b) toBinaryValue(int)
c) toBinaryNumber(int)
d) toBinaryString(int)
Answer: d
Explanation: The method toBinaryString() takes an integer argument and is defined in java.lang package.
Usage is java.lang.Integer.toBinaryString(int) this returns the string representation of the unsigned integer
value.
advertisement
public void convertBinary(int num)
{
Stack<Integer> stack = new Stack<Integer>();
while (num != 0)
{
int digit = num / 2;
stack.push(digit);
num = num % 2;
}
System.out.print("\nBinary representation is:");
while (!(stack.isEmpty() ))
{
System.out.print(stack.pop());
}
}
b)
c)
d)
Answer: c
Explanation: Since each time you are halving the number, it can be related to that of a binary search
algorithm, hence the complexity is O(logn).
6. Write a piece of code which returns true if the string contains balanced parenthesis, false otherwise.
a)
b)
d)
Answer: a
Explanation: Whenever a ‘(‘ is encountered, push it into the stack, and when a ‘)’ is encountered check the
top of the stack to see if there is a matching ‘(‘, if not return false, continue this till the entire string is
processed and then return true.
7. What is the time complexity of the following code?
public boolean isBalanced(String exp)
{
int len = exp.length();
Stack<Integer> stk = new Stack<Integer>();
for(int i = 0; i < len; i++)
{
char ch = exp.charAt(i);
if (ch == '(')
stk.push(i);
else if (ch == ')')
{
if(stk.peek() == null)
{
return false;
}
stk.pop();
}
}
return true;
}
a) O(logn)
b) O(n)
c) O(1)
d) O(nlogn)
Answer: b
Explanation: All the characters in the string have to be processed, hence the complexity is O(n).
8. Which of the following program prints the index of every matching parenthesis?
a)
b)
c)
d)
1. How many stacks are required for applying evaluation of infix expression algorithm?
a) one
b) two
c) three
d) four
Answer: b
Explanation: Two stacks are required for evaluation of infix expression – one for operands and one for
operators.
2. How many passes does the evaluation of infix expression algorithm makes through the input?
a) One
b) Two
c) Three
d) Four
Answer: a
Explanation: Evaluation of infix expression algorithm is linear and makes only one pass through the input.
3. Identify the infix expression from the list of options given below.
a) a/b+(c-d)
b) abc*+d+ab+cd+*ce-f-
c) ab-c-
d) +ab
Answer: a
Explanation: a/b+(c-d) is an infix expression since the operators are placed in between the operands.
4. Which of the following statement is incorrect with respect to evaluation of infix expression algorithm?
a) Operand is pushed on to the stack
b) If the precedence of operator is higher, pop two operands and evaluate
c) If the precedence of operator is lower, pop two operands and evaluate
d) The result is pushed on to the operand stack
Answer: b
Explanation: If the precedence of the operator is higher than the stack operator, then it is pushed on to the
stack operator.
5. Evaluate the following statement using infix evaluation algorithm and choose the correct answer. 1+2*3-2
a) 3
b) 6
c) 5
d) 4
Answer: c
Explanation: According to precedence of operators, * is evaluated first. + and – have equal priorities. Hence,
1+6-2= 5.
advertisement
Answer: a
Explanation: During evaluation of infix expression, the operators with higher precedence are evaluated first,
followed by operators with lower precedence.
Answer: d
Explanation: The operator with the lowest precedence is #, preceded by +, / and then ^.
8. The system throws an error if parentheses are encountered in an infix expression evaluation algorithm.
a) True
b) False
Answer: b
Explanation: The algorithm holds good for infix expression with parentheses. The system does not throw
error.
Answer: b
Explanation: * and / have higher priority. Hence, they are evaluated first. Then, + is evaluated. Hence,
2+2=4.
10. Evaluate the following statement using infix evaluation algorithm and choose the correct answer. 4*2+3-
5/5
a) 10
b) 11
c) 16
d) 12
Answer: a
Explanation: 4*2 and 5/5 are evaluated first and then, 8+3-1 is evaluated and the result is obtained as 10.
11. Using the evaluation of infix expression, evaluate a^b+c and choose the correct answer. (a=2, b=2, c=2)
a) 12
b) 8
c) 10
d) 6
Answer: d
Explanation: ^ has the highest precedence. Hence, 2^2 is evaluated and then 4+2 gives 6.
12. Evaluate the following infix expression using algorithm and choose the correct answer. a+b*c-d/e^f
where a=1, b=2, c=3, d=4, e=2, f=2.
a) 6
b) 8
c) 9
d) 7
Answer: a
Explanation: ^ has the highest order of precedence. Hence, 2^2 is evaluated first, and then, 2*3 and 4/4 are
evaluated. Therefore, 1+6-1=6.
13. From the given expression tree, identify the infix expression, evaluate it and choose the correct result.
a) 5
b) 10
c) 12
d) 16
Answer: c
Explanation: From the given expression tree, the result of the infix expression is evaluated to be 12
Answer: b
Explanation: 2 stacks are required for evaluation of prefix expression, one for integers and one for
characters.
2. While evaluating a prefix expression, the string is read from?
a) left to right
b) right to left
c) center to right
d) center to left to right
Answer: b
Explanation: The string is read from right to left because a prefix string has operands to its right side.
Answer: a
Explanation: The associativity of ^ is right side while the rest of the operators like +,-,*,/ has its associativity
to its left.
Answer: c
Explanation: Three kinds of input are accepted by this algorithm- numbers, operators and new line
characters.
Answer: a
Explanation: Precedence is a very important factor in determining the order of evaluation. If two operators
have the same precedence, associativity comes into action.
advertisement
a) 2
b) 12
c) 10
d) 4
Answer: a
Explanation: The given prefix expression is evaluated using two stacks and the value is given by (2+2-1)*(4-
2)/(5-3+1)= 2.
7. An error is thrown if the character ‘\n’ is pushed in to the character stack.
a) true
b) false
Answer: b
Explanation: The input character ‘\n’ is accepted as a character by the evaluation of prefix expression
algorithm.
Answer: d
Explanation: Using the evaluation of prefix algorithm, +-9 2 7 is evaluated as 9-2+7=14.
Answer: b
Explanation: The given prefix expression is evaluated as ((1+2)*5)-4 = 11 while a=1, b=2, c=5, d=4.
10. In the given C snippet, find the statement number that has error.
a) 1
b) 9
c) 10
d) 11
Answer: c
Explanation: If the stack is not full then we are correctly incrementing the top of the stack by doing “++s-
>top” and storing the value of x in it. However, in the next statement “s++”, we are un-necessarily
incrementing the stack base pointer which will lead to memory corruption during the next push() operation.
Answer: b
Explanation: Reverse polish Notation is the other name for a postfix expression whereas Polish Notation,
Warsaw notation are the other names for a prefix expression.
Answer: b
Explanation: abc*+de-+ is a postfix expression. +ab is a prefix expression and others are infix expressions.
Answer: b
Explanation: Reverse Polish Notation is not the reverse of a polish notation. Though both NPN and RPN
read the expression from left to right, they follow different strategies.
Answer: a
Explanation: The time complexity of evaluation of infix, prefix and postfix expressions is O (N).
Answer: a
Explanation: In postfix expressions, the operators follow operands. In prefix expressions, the operands
follow operators.
advertisement
Answer: d
Explanation: Line at ticket counter is an application of queue whereas conversion of infix to postfix
expression, balancing symbols, line at ticket counter are stack applications.
8. While evaluating a postfix expression, when an operator is encountered, what is the correct operation to
be performed?
a) push it directly on to the stack
b) pop 2 operands, evaluate them and push the result on to the stack
c) pop the entire stack
d) ignore the operator
Answer: b
Explanation: When an operator is encountered, the first two operands are popped from the stack, they are
evaluated and the result is pushed into the stack.
Answer: a
Explanation: All prefix operators use values to their right and all postfix operators use values to their left.
10. What is the result of the given postfix expression? abc*+ where a=1, b=2, c=3.
a) 4
b) 5
c) 6
d) 7
Answer: d
Explanation: The infix expression is a+b*c. Evaluating it, we get 1+2*3=7.
Answer: a
Explanation: When an operator is encountered, the first two operands of the stack are popped, evaluated and
the result is pushed into the stack.
13. Evaluate the postfix expression ab + cd/- where a=5, b=4, c=9, d=3.
a) 23
b) 15
c) 6
d) 10
Answer: c
Explanation: The infix expression is (a+b)-c/d. Evaluating it, (5+4)-9/3 gives 6.
14. Evaluate and write the result for the following postfix expression
abc*+de*f+g*+ where a=1, b=2, c=3, d=4, e=5, f=6, g=2.
a) 61
b) 59
c) 60
d) 55
Answer: b
Explanation: The infix expression is a+b*c+(d*e+f)*g. Evaluating it, 1+2*3+(4*5+6)*2 gives 59.
15. For the given expression tree, write the correct postfix expression.
a) abc*+
b) abc+*
c) ab+c*
d) a+bc*
Answer: a
Explanation: Evaluating the given expression tree gives the infix expression a+b*c. Converting it to postfix,
we get, abc*+.
1. What data structure is used when converting an infix notation to prefix notation?
a) Stack
b) Queue
c) B-Trees
d) Linked-list
Answer: a
Explanation: First you reverse the given equation and carry out the algorithm of infix to postfix expression.
Here, the data structure used is stacks.
A+(B*C)
a) +A*CB
b) *B+AC
c) +A*BC
d) *A+CB
Answer: c
Explanation: Reverse the equation or scan the equation from right to left. Apply the infix-postfix algorithm.
The equation inside the bracket evaluates to CB* and outside the bracket evaluates to A+ therefore getting
CB*A+. Reversing this and we get +A*BC.
(A*B)+(C*D)
a) +*AB*CD
b) *+AB*CD
c) **AB+CD
d) +*BA*CD
Answer: a
Explanation: Reverse the equation or scan the equation from right to left. Apply the infix-postfix algorithm.
The equation inside the brackets evaluate to DC* and BA* respectively giving us DC*BA*+ in the end.
Reversing this we get the +*AB*CD.
advertisement
A+B*C^D
a) +A*B^CD
b) +A^B*CD
c) *A+B^CD
d) ^A*B+CD
Answer: a
Explanation: Reverse the equation or scan the equation from right to left. Apply the infix-prefix algorithm.
The preference order in ascending order are as follows +*^. Operators are pushed into the stack and popped
if its preference is greater than the one which is getting pushed. In the end all operators are popped. The
equation evaluates to DC^B*A+. Reversing this we get our following answer.
5. Out of the following operators (^, *, +, &, $), the one having highest priority is _________
a) +
b) $
c) ^
d) &
Answer: c
Explanation: According to the algorithm (infix-prefix), it follows that the exponentiation will have the
highest priority.
6. Out of the following operators (|, *, +, &, $), the one having lowest priority is ________
a) +
b) $
c) |
d) &
Answer: c
Explanation: According to the algorithm (infix-prefix), it follows that the logical OR will have the lowest
priority.
A^B^C^D
a) ^^^ABCD
b) ^A^B^CD
c) ABCD^^^
d) AB^C^D
Answer: a
Explanation: Reverse the equation or scan the equation from right to left. Apply the infix-prefix algorithm.
Here we have to remember that the exponentiation has order of associativity from right to left. Therefore the
stack goes on pushing ^. Therefore resulting in ^^^ABCD.
a+b-c/d&e|f
a) |&-+ab/cdef
b) &|-+ab/cdef
c) |&-ab+/cdef
d) |&-+/abcdef
Answer: a
Explanation: Reverse the equation or scan the equation from right to left. Apply the infix-prefix algorithm.
The preference order in ascending order are as follows |&+*/.
(a+(b/c)*(d^e)-f)
a) -+a*/^bcdef
b) -+a*/bc^def
c) -+a*b/c^def
d) -a+*/bc^def
Answer: b
Explanation: Reverse the equation or scan the equation from right to left. Apply the infix-prefix algorithm.
The preference order in ascending order are as follows +*/^. Brackets have the highest priority. The
equations inside the brackets are solved first.
10. What would be the Prefix notation and Postfix notation for the given equation?
A+B+C
Answer: a
Explanation: For prefix notation there is a need of reversing the giving equation and solving it as a normal
infix-postfix question. We see that it doesn’t result as same as normal infix-postfix conversion.
11. What would be the Prefix notation for the given equation?
a|b&c
a) a|&bc
b) &|abc
c) |a&bc
d) ab&|c
Answer: c
Explanation: The order of preference of operators is as follows (descending): & |.
The equation a|b&c will be parenthesized as (a|(b&c)) for evaluation.
Therefore the equation for prefix notation evaluates to |a&bc.
Answer: c
Explanation: When a left parenthesis is encountered, it is placed on to the operator stack. When the
corresponding right parenthesis is encountered, the stack is popped until the left parenthesis and remove
both the parenthesis.
Answer: a
Explanation: (a+b)*(c+d) is an infix expression. +ab is a prefix expression and ab+c* is a postfix expression.
Answer: b
Explanation: The time complexity of an infix to postfix expression conversion algorithm is mathematically
found to be O(N).
a+b*c+(d*e)
a) abc*+de*+
b) abc+*de*+
c) a+bc*de+*
d) abc*+(de)*+
Answer: a
Explanation: Using the infix to postfix expression conversion algorithm, the corresponding postfix
expression is found to be abc*+de*+.
advertisement
Answer: a
Explanation: Computers can easily process a postfix expression because a postfix expression keeps track of
precedence of operators.
a-b-c
a) -ab-c
b) ab – c –
c) – -abc
d) -ab-c
Answer: b
Explanation: The corresponding postfix expression for the given infix expression is found to be ab-c- and
not abc- -.
a/b^c-d
a) abc^/d-
b) ab/cd^-
c) ab/^cd-
d) abcd^/-
Answer: a
Explanation: Using the infix to postfix conversion algorithm, the corresponding postfix expression for the
infix expression is found to be abc^/d-.
10. Which of the following statement is incorrect with respect to infix to postfix conversion algorithm?
a) operand is always placed in the output
b) operator is placed in the stack when the stack operator has lower precedence
c) parenthesis are included in the output
d) higher and equal priority operators follow the same condition
Answer: c
Explanation: Parentheses are not included in the output. They are placed in the operator stack and then
discarded.
11. In infix to postfix conversion algorithm, the operators are associated from?
a) right to left
b) left to right
c) centre to left
d) centre to right
Answer: b
Explanation: In infix, prefix and postfix expressions, the operators are associated from left to right and not
right to left.
12. What is the corresponding postfix expression for the given infix expression?
a*(b+c)/d
a) ab*+cd/
b) ab+*cd/
c) abc*+/d
d) abc+*d/
Answer: d
Explanation: Using the infix to postfix conversion algorithm, the corresponding postfix expression is
obtained as abc+*d/.
13. What is the corresponding postfix expression for the given infix expression?
a+(b*c(d/e^f)*g)*h)
a) ab*cdef/^*g-h+
b) abcdef^/*g*h*+
c) abcd*^ed/g*-h*+
d) abc*de^fg/*-*h+
Answer: b
Explanation: Using the infix to postfix expression conversion algorithm using stack, the corresponding
postfix expression is found to be abcdef^/*g*h*+.
14. What is the correct postfix expression for the following expression?
a+b*(c^d-e)^(f+g*h)-i
a) abc^de-fg+*^*+i-
b) abcde^-fg*+*^h*+i-
c) abcd^e-fgh*+^*+i-
d) ab^-dc*+ef^gh*+i-
Answer: c
Explanation: The postfix expression for the given infix expression is found to be abcd^e-fgh*+^*+i- when
we use infix to postfix conversion algorithm.
15. From the given Expression tree, identify the correct postfix expression from the list of options.
a) ab*cd*+
b) ab*cd-+
c) abcd-*+
d) ab*+cd-
Answer: b
Explanation: From the given expression tree, the infix expression is found to be (a*b)+(c-d). Converting it to
postfix, we get, ab*cd-+.
- + 5 / 10 5 5
a) 2
b) 5
c) 10
d) 7
Answer: a
Explanation: The infix notation of the given prefix notation is 5+10/5-5 which gives us 2 as our answer.
/ / / / 16 4 2 1
a) 1
b) 4
c) 2
d) 8
Answer: a
Explanation: The infix notation to the given prefix notation is 16/4/2/1 which gives us 1 as our answer. The
infix notation is got from the prefix notation by traversing the equation from the right.
advertisement
+ 9 * 3 / 8 4
a) 14
b) 15
c) 18
d) 12
Answer: b
Explanation: The infix notation for the given prefix notation is (9+(3*(8/4))) which solves to 15. So 15 is
correct answer.
- + 1 2 * 3 / 6 2
a) 6
b) -6
c) 3
d) -3
Answer: b
Explanation: The infix notation for the given prefix notation is (1+2)-3*(6/2). The result of the given
equation is -6.
- * 1 5 / * / 6 3 6 2
a) 1
b) 0
c) -1
d) -2
Answer: c
Explanation: The infix notation for the given prefix notation is (1*5)-(6/3)*6/2. The result of the equation is
-1.
* / + 1 2 / 4 2 + 3 5
a) 12
b) 7.5
c) 9
d) 13.5
Answer: a
Explanation: The infix notation of the given prefix notation is ((1+2)/(4/2))*(3+5) which solves to (3/2)*8
which by solving gives us 12.
7. Given a prefix and a postfix notation what are the difference between them?
a) The postfix equation is solved starting from the left whereas the prefix notation is solved from the right
b) The postfix equation is solved starting from the right whereas the prefix notation is solved from the left
c) Both equations are solved starting from the same side(right)
d) Both equations are solved starting from the same side(left)
Answer: a
Explanation: The postfix notation is solved starting from left but whereas the prefix notation is reversed after
creating them, therefore it’s solved starting from right.
8. When converting the prefix notation into an infix notation, the first step to be followed is ________
a) Reverse the equation
b) Push the equation to the stack
c) Push the equation onto the queue
d) Push the equation to the stack or queue
Answer: a
Explanation: The steps that are followed are: the equation is reversed, pushed onto a stack, popped one by
one and solved. Therefore the first step is reversing the equation.
Answer: a
Explanation: The processes that are involved are reversing the equation (O(n)), pushing them all onto the
stack(O(n)), and popping them one by one and solving them (O(n)). Hence the answer is O(n) where n is the
length of the equation.
10. Given two processes (conversion of postfix equation to infix notation and conversion of prefix notation
to infix notation), which of the following is easier to implement?
a) Both are easy to implement
b) Conversion of postfix equation to infix equation is harder than converting a prefix notation to infix
notation
c) Conversion of postfix equation to infix equation is easier than converting a prefix notation to infix
notation
d) Insufficient data
Answer: c
Explanation: As the conversion of prefix notation to infix notation involves reversing the equation, the latter
is harder to implement than postfix to infix process.
1. Which of the following data structure is used to convert postfix expression to infix expression?
a) Stack
b) Queue
c) Linked List
d) Heap
Answer: a
Explanation: To convert the postfix expression into infix expression we need stack. We need stack to
maintain the intermediate infix expressions. We use stack to hold operands.
2. The postfix expression abc+de/*- is equivalent to which of the following infix expression?
a) abc+-de*/
b) (a+b)-d/e*c
c) a-(b+c)*(d/e)
d) abc+*-(d/e)
Answer: c
Explanation: Given postfix expression : abc+de/*-
infix ⇒ a(b+c)(d/e)*-
⇒ a(b+c)*(d/e)-
⇒ a-(b+c)*(d/e)
Hence, correct choice is a-(b+c)*(d/e).
3. The equivalent infix expression and value for the postfix form 1 2 + 3 * 4 5 * – will be ___________
a) 1 + 2 * 3 – 4 * 5 and -13
b) (2 + 1) * (3 – 4) * 5 and 13
c) 1 + 2 * (3 – 4) * 5 and -11
d) (1 + 2) * 3 – (4 * 5) and -11
Answer: d
Explanation: Given postfix expression : 1 2 + 3 * 4 5 * –
⇒ (1 + 2) 3 * 4 5 * –
⇒ ((1 + 2) * 3) 4 5 * –
⇒ ((1 + 2) * 3) (4 * 5) –
⇒ ((1 + 2) * 3) – (4 * 5)
So, the equivalent infix expression is (1 + 2) * 3 – (4 * 5) and it’s value is -11.
Answer: d
Explanation: Given postfix expression : 2 3 + 4 5 6 – – *
infix ⇒ (2 + 3)4 (5 – 6) – *
⇒ (2 + 3)*4 – (5 – 6)
Hence, value = (2 + 3) * (4 – (5 – 6)) = 5 *(4 – (-1)) = 5*5 = 25.
advertisement
Answer: d
Explanation: To convert from postfix to prefix, we first convert it to infix and then to prefix.
postfix : AB+CD-*
infix ⇒ (A+B) * (C-D)
So, prefix ⇒ +AB*-CD,
⇒ *+AB-CD.
Therefore, correct choice is *+AB-CD.
6. Consider the postfix expression 4 5 6 a b 7 8 a c, where a, b, c are operators. Operator a has higher
precedence over operators b and c. Operators b and c are right associative. Then, equivalent infix expression
is
a) 4 a 5 6 b 7 8 a c
b) 4 a 5 c 6 b 7 a 8
c) 4 b 5 a 6 c 7 a 8
d) 4 a 5 b 6 c 7 a 8
Answer: c
Explanation: Given postfix expression: 4 5 6 a b 7 8 a c
infix ⇒ 4 (5 a 6) b (7 a 8) c
⇒ (4 b (5 a 6)) (7 a 8) c
⇒ (4 b (5 a 6)) c (7 a 8)
So, the required infix expression is 4 b 5 a 6 c 7 a 8.
7. To convert the postfix expression into the infix expression we use stack and scan the postfix expression
from left to right.
a) True
b) False
Answer: a
Explanation: Stack is used to postfix expression to infix expression. And to convert we follow the following
steps: (i) Scan the expression from left to right. (ii) If operand is found, push it on stack.(iii) If operator is
found, the two operands are popped and the combined infix expression is formed and pushed onto the stack.
Answer: c
Explanation: The postfix expression is also known as the reverse polish expression. In postfix expressions,
the operators come after the operands. So, the correct expression is a b op and hence a b op is correct.
Answer: b
Explanation: Given postfix expression: 5 3 * 9 + 6 / 8 4 / +
Result = 5 3 * 9 + 6 / 8 4 / +
= (5 * 3) 9 + 6 / (8 / 4) +
= ((5 * 3) + 9) / 6 + ( 8 / 4) = ( 24 / 6) + 2 = 4 + 2 = 6.
Answer: d
Explanation: The Tower of Hanoi involves moving of disks ‘stacked’ at one peg to another peg with respect
to the size constraint. It is conveniently done using stacks and priority queues. Stack approach is widely used
to solve Tower of Hanoi.
2. Select the appropriate code for the recursive Tower of Hanoi problem.(n is the number of disks)
a)
b)
c)
d)
advertisement
public void solve(int n, String start, String auxiliary, String end)
{
if (n == 1)
{
System.out.println(start + " -> " + end);
}
else
{
solve(n - 1, start, end, auxiliary);
System.out.println(start + " -> " + end);
}
}
Answer: a
Explanation: First transfer all the diska to the auxiliary and then to the end peg, this is achieved by making
auxiliary peg as the end peg in the first recursive call, in the second recursive call, the auxiliary becomes the
start peg from where the disks are transferred to the end peg.
Answer: d
Explanation: A palindrome is a string that reads the same forward and backward, Madam, Dad and
Malayalam are palindromes where as Maadam is not a palindrome.
Answer: c
Explanation: Stack is a convenient option as it involves pushing and popping of characters.
c)
d)
Answer: a
Explanation: Push all the characters in the input string to a stack, now pop them and append to a new string
which is checked for equality with the original string.
6. What is the number of moves required to solve Tower of Hanoi problem for k disks?
a) 2k – 1
b) 2k + 1
c) 2k + 1
d) 2k – 1
Answer: d
Explanation: Tracing of the moves in the above ToH problem will prove this result, instead you can simply
add a count for each recursive call to check the number of moves.
b)
c)
d)
Answer: b
Explanation: Although, it is possible to reverse the string without using stack, it is done by looping through
the string from the end character by character.
In Java, it is also possible to use the StringBuilder and StringBuffer classes which have a built-in method
‘reverse’.
Note its similarity to PalindromeTest.
1. Reversing a word using stack can be used to find if the given word is a palindrome or not.
a) True
b) False
Answer: a
Explanation: This application of stack can also be used to find if the given word is a palindrome because, if
the reversed is same as that of the original word, the given word is a palindrome.
Answer: b
Explanation: Stack is the most appropriate data structure for reversing a word because stack follows LIFO
principle.
3. Operations required for reversing a word or a string using stack are push() and pop().
a) True
b) False
Answer: a
Explanation: Push operation inserts a character into the stack and pop operation pops the top of the stack.
Answer: c
Explanation: The time complexity of reversing a stack is mathematically found to be O (N) where N is the
input.
5. What will be the word obtained if the word “abbcabb” is reversed using a stack?
a) bbabbca
b) abbcabb
c) bbacbba
d) bbacabb
Answer: c
Explanation: The string “abbcabb” is pushed on to the stack. If the characters are popped one by one, the
word obtained will be bbacbba.
advertisement
Answer: a
Explanation: Only 1 stack is required for reversing a word using stack. In that stack, push and pop
operations are carried out.
a) pat
b) tap
c) atp
d) apt
Answer: b
Explanation: The word ‘pat’ is pushed on to the stack. When the characters of the stack are popped one by
one, the word ‘tap’ is obtained.
Push(a,s);
Push(b,s);
Pop(b);
Push(c,s);
a) abc
b) b
c) ac
d) acb
Answer: b
Explanation: The element ‘b’ is popped out of the stack. Hence the output of the following sequence of
operations will be ‘b’.
9. What are the set of functions that are to be executed to get the following output?
cat
a) push(c, s); push(a, s); push(t, s);
pop(s); pop(s); pop(s);
b) push(c,s); pop(s); push(a,s); pop(s);push(t,s);pop(s);
c) pop(c ); pop(a); pop(t);
d) push(c,s); push(a,s); pop(t);
Answer: b
Explanation: During push operation, the characters ‘c’, ’a’, ’t’ are inserted into the stack and popped
immediately after push.
10. How will your stack look like if the word ‘java’ is pushed?
a)
b)
c)
d)
Answer: a
Explanation: When a character is pushed, it stays on the top of the stack. While popping, the word occurs in
reverse order since stack follows LIFO principle.
11. Find the error (if any) in the following code snippet for pop operation.
Answer: c
Explanation: The statement printf(“%s”, stack[top++]) does a pop, but top gets incremented which is not
correct. The statement stack[top++] should be replaced with stack[top–] in order to pop an operand and
maintain stack properly.
main()
{
char str[]="san foundry";
int len = strlen(str);
int i;
for(i=0;i<len;i++)
push(str[i]); // pushes an element into stack
for(i=0;i<len;i++)
pop(); //pops an element from the stack
}
a) sanfoundry
b) san foundry
c) yrdnuof nas
d) foundry nas
Answer: c
Explanation: First, the string ‘san foundry’ is pushed one by one into the stack.
When it is popped, the output will be as ‘yrdnuof nas’.
Answer: a
Explanation: The time complexity of balancing parentheses algorithm is mathematically found to be O (N).
2. Which application of stack is used to ensure that the pair of parentheses is properly nested?
a) Balancing symbols
b) Reversing a stack
c) Conversion of an infix to postfix expression
d) Conversion of an infix to prefix expression
Answer: a
Explanation: Balancing symbols application ensures that the pair of parentheses are properly nested while
reversing stack reverses a stack.
Answer: b
Explanation: Any string is read by the compiler from left to right and not from right to left.
4. Which is the most appropriate data structure for applying balancing of symbols algorithm?
a) stack
b) queue
c) tree
d) graph
Answer: a
Explanation: Stack is the most appropriate data structure for balancing symbols algorithm because stack
follows LIFO principle (Last In First Out).
Answer: d
Explanation: The balancing symbols algorithm using stack only includes balancing parentheses, brackets
and braces and not any other symbols.
advertisement
6. Which of the following statement is incorrect with respect to balancing symbols algorithm?
a) {[()]}
b) ([ )]
c) {( )}
d) { [ ] }
Answer: b
Explanation: ([ )] is incorrect because’)’ occurs before the corresponding ‘]’ is encountered.
7. What should be done when an opening parentheses is read in a balancing symbols algorithm?
a) push it on to the stack
b) throw an error
c) ignore the parentheses
d) pop the stack
Answer: a
Explanation: When an opening bracket/braces/parentheses is encountered, it is pushed on to the stack. When
the corresponding end bracket/braces/parentheses is not found, throw an error.
Answer: c
Explanation: When the corresponding end bracket/braces/parentheses is not found, throw an error since they
don’t match.
Answer: b
Explanation: When the corresponding end bracket/braces/parentheses is encountered, the stack is popped.
When an opening bracket/braces/parentheses is encountered, it is pushed on to the stack.
10. An error is reported when the stack is not empty at the end.
a) True
b) False
Answer: a
Explanation: When the stack contains elements at the end, it means that the given string of parentheses is not
balanced.
11. Is the given statement ((A+B) + [C-D]] valid with respect to balancing of symbols?
a) True
b) False
Answer: b
Explanation: The given statement is invalid with respect to balancing of symbols because the last bracket
does not correspond to the opening braces.
12. How many passes does the balancing symbols algorithm makes through the input?
a) one
b) two
c) three
d) four
Answer: a
Explanation: The balancing symbols algorithm makes only one pass through the input since it is linear.
13. Which of the following statement is invalid with respect to balancing symbols?
a) [(A+B) + (C-D)]
b) [{A+B}-{C-[D+E]}]
c) ((A+B) + (C+D)
d) {(A+B) + [C+D]}
Answer: c
Explanation: ((A+B) + (C+D) is invalid because the last close brace is not found in the statement
Answer: b
Explanation: It compactly stores bits and exploits bit-level parallelism.
2. Which of the following bitwise operations will you use to set a particular bit to 1?
a) OR
b) AND
c) XOR
d) NOR
Answer: a
Explanation: 1 OR 1 = 1, 0 OR 1 = 1, any bit OR’ed with 1 gives 1.
3. Which of the following bitwise operations will you use to set a particular bit to 0?
a) OR
b) AND
c) XOR
d) NAND
Answer: b
Explanation: 1 AND 0 = 0, 0 AND 0 = 0, any bit AND with 0 gives 0.
4. Which of the following bitwise operations will you use to toggle a particular bit?
a) OR
b) AND
c) XOR
d) NOT
Answer: c
Explanation: 1 XOR 1 = 0, 0 XOR 1 = 1, note that NOT inverts all the bits, while XOR toggles only a
specified bit.
5. Which of the following is not an advantage of bit array?
a) Exploit bit level parallelism
b) Maximal use of data cache
c) Can be stored and manipulated in the register set for long periods of time
d) Accessing Individual Elements is easy
Answer: d
Explanation: Individual Elements are difficult to access and can’t be accessed in some programming
languages. If random access is more common than sequential access, they have to be compressed to
byte/word array. Exploit Bit parallelism, Maximal use of data cache and storage and manipulation for longer
time in register set are all advantages of bit array.
advertisement
Answer: d
Explanation: Bit arrays allow small arrays of bits to be stored and manipulated in the register set for long
periods of time with no memory accesses because of their ability to exploit bit-level parallelism, limit
memory access, and maximally use the data cache, they often outperform many other data structures on
practical data sets. This is an advantage of bit array. The rest are all disadvantages of bit array.
Answer: d
Explanation: Normal Arrays are used to implement vectors and matrices. Bit arrays have no prominent role.
Remaining all are applications of Bit Arrays.
Answer: a
Explanation: The BitSet class creates a special type of array that can hold bit values.
9. Which of the following bitwise operator will you use to invert all the bits in a bit array?
a) OR
b) NOT
c) XOR
d) NAND
Answer: b
Explanation: NOT operation is used to invert all the bits stored in a bit array.
Eg: NOT (10110010) = 01001101.
Answer: a
Explanation: A bit array stores the combinations of bit 0 and bit 1. Each bit in the bit array is independent.
Run Length encoding is a data compression technique in which data are stored as single value and number
of times that value repeated in the data. This compression reduces the space complexity in arrays. Bit arrays
without compression require more space. Thus, we will use Run-Length encoding in most of the cases to
compress data in bit arrays.
Answer: a
Explanation: Hamming/ population count involves finding the number of 1’s in the bit array. Population
count is used in data compression.
Answer: b
Explanation: Bit field contains the number of adjacent computer locations used to store the sequence of bits
to address a bit or groups of bits. Bit array is an array that stores combinations of bit 0 and bit 1. Thus, bit
fields and Bit arrays are different.
13. Which one of the following operations returns the first occurrence of bit 1 in bit arrays?
a) Find First Zero
b) Find First One
c) Counting lead Zeroes
d) Counting lead One
Answer: b
Explanation: Find First One operation returns the first occurrence of bit 1 in the bit array. Find First Zero
operation returns the first occurrence of bit 0 in the bit array. If the most significant bit in bit array is 1, then
count lead zeroes operation returns the number of zeroes present before the most significant bit. If the most
significant bit in bit array is 0, then the count lead one returns the number of ones present before the most
significant bit.
Answer: a
Explanation: It is a varying-size list data structure that allows items to be added or removed, it may use a
fixed sized array at the back end.
Answer: c
Explanation: Physical size, also called array capacity is the size of the underlying array, which is the
maximum size without relocation of data.
3. The number of items used by the dynamic array contents is its __________
a) Physical size
b) Capacity
c) Logical size
d) Random size
Answer: c
Explanation: The number of items used by the dynamic array contents is called logical size. Physical size is
the size of the underlying array, which is the maximum size without reallocation of data.
Answer: d
Explanation: ArrayList is used to implement dynamic arrays in Java.
Answer: a
Explanation: This is a non-generic way of creating an ArrayList.
advertisement
Answer: d
Explanation: Dynamic arrays share the advantage of arrays, added to it is the dynamic addition of elements
to the array. Memory can be leaked if it is not handled properly during allocation and deallocation. It is a
disadvantage.
8. What is the time complexity for inserting/deleting at the beginning of the array?
a) O(1)
b) O(n)
c) O(logn)
d) O(nlogn)
Answer: b
Explanation: All the other elements will have to be moved, hence O(n).
Answer: a
Explanation: Static arrays have fixed capacity. The capacity must be specified during memory allocation.
Dynamic arrays don’t require to specify their capacity during memory allocation. Dynamic arrays have fixed
physical size at backend and its capacity increases if required. Thus, Dynamic arrays overcome the limit of
static arrays.
10. The size of the dynamic array is deallocated if the array size is less than _________% of the backend
physical size.
a) 30
b) 40
c) 10
d) 20
Answer: a
Explanation: The size of the dynamic array is decreased/deallocated if the actual size of the array is less than
30% of the backend physical size. This is used to avoid memory wastage.
11. Both Dynamic array and Dynamically memory allocated array are same.
a) True
b) False
Answer: b
Explanation: Physical size of a Dynamic array is fixed with a larger value. Dynamically memory allocated
arrays are arrays whose memory is allocated at run time rather than at compile time. Dynamically memory
allocated arrays don’t have physical size at the backend. Thus, Dynamic arrays and Dynamically memory
allocated arrays are different.
12. In which of the following cases dynamic arrays are not preferred?
a) If the size of the array is unknown
b) If the size of the array changes after few iterations
c) If the memory reallocation takes more time i.e. expensive
d) If the array holds less number of elements
Answer: d
Explanation: Dynamic arrays are preferred when the size of the array is unknown during memory allocation
or the size changes after few iterations or the memory reallocation is expensive. If array holds less number
of elements, the physical size is reduced and reduction takes more time. In that case, we can use normal
arrays instead of dynamic arrays.
Answer: b
Explanation: The growth factor of dynamic arrays (Array List) in Java is 3/2.
The new array capacity is calculated as new_array_size = (old_array_size*3)/2+1.
14. In special case, the time complexity of inserting/deleting elements at the end of dynamic array is
__________
a) O (n)
b) O (n1/2)
c) O (log n)
d) O (1)
Answer: a
Explanation: In general, the time complexity of inserting or deleting elements at the end of dynamic array is
O (1). Elements are added at reserved space of dynamic array. If this reserved space is exceeded, then the
physical size of the dynamic array is reallocated and every element is copied from original array. This will
take O(n) time to add new element at the end of the array.
15. Which of the following arrays are used in the implementation of list data type in python?
a) Bit array
b) Dynamic arrays
c) Sparse arrays
d) Parallel arrays
Answer: b
Explanation: Dynamic arrays are used in the implementation of list data type in python. Sparse arrays are
used in the implementation of sparse matrix in Numpy module. All bit array operations are implemented in
bitarray module.
1. What are parallel arrays?
a) Arrays of the same size
b) Arrays allocated one after the other
c) Arrays of the same number of elements
d) Arrays allocated dynamically
Answer: c
Explanation: Different arrays can be of different data types but should contain same number of elements.
Elements at corresponding index belong to a record.
firstName = ['Joe','Bob','Frank','Hans']
lastName = ['Smith','Seger','Sinatra','Schultze']
heightInCM = [169,158,201,199]
for i in xrange(len(firstName)):
print "Name:",firstName[i], lastName[i]
print "Height in CM:,",heightInCM[i]
b)
firstName = ['Joe','Bob','Frank','Hans']
lastName = ['Smith','Seger']
heightInCM = [169,158]
for i in xrange(len(firstName)):
print "Name:",firstName[i], lastName[i]
print "Height in CM:,",heightInCM[i]
c)
advertisement
firstName = ['Joe','Bob']
lastName = ['Smith','Seger','Sinatra','Schultze']
heightInCM = [169,158]
for i in xrange(len(firstName)):
print "Name:",firstName[i], lastName[i]
print "Height in CM:,",heightInCM[i]
d)
firstName = ['Joe','Bob']
lastName = ['Smith','Seger' ,'Schultze']
heightInCM = [169,158]
for i in xrange(len(firstName)):
print "Name:",firstName[i], lastName[i]
print "Height in CM:,",heightInCM[i]
Answer: a
Explanation: All the arrays must have equal length, that is, contain same number of elements.
3. Which of the following is a disadvantage of parallel array over the traditional arrays?
a) When a language does not support records, parallel arrays can be used
b) Increased locality of reference
c) Ideal cache behaviour
d) Insertion and Deletion becomes tedious
Answer: d
Explanation: Insertion and deletion of elements require to move every element from their initial positions.
This will become tedious. For Record collection, locality of reference and Ideal Cache behaviour we can use
parallel arrays.
Answer: d
Explanation: Elements in the parallel array are accessed sequentially as one arrays holds the keys whereas
other holds the values. This sequential access generally improves Locality of Reference. It is an advantage.
Answer: d
Explanation: The array can be sorted in any way, numerical, alphabetical or any other way but the elements
are placed at equally spaced addresses.
6. To search for an element in a sorted array, which searching technique can be used?
a) Linear Search
b) Jump Search
c) Binary Search
d) Fibonacci Search
Answer: c
Explanation: Since the array is sorted, binary search is preferred as its time complexity is O(logn).
Answer: d
Explanation: Sorted arrays have widespread applications as all commercial computing involves large data
which is very useful if it is sorted. It makes best use of locality of reference and data cache. Linked lists are
used in Hash Tables not arrays.
8. What is the worst case time complexity of inserting an element into the sorted array?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)
Answer: c
Explanation: In the worst case, an element must added to the front of the array, which means that rest of the
elements have to be shifted, hence the worst case time complexity becomes O(n).
Answer: c
Explanation: They are set to a default value, usually 0 or null.
Answer: b
Explanation: It need not necessarily be zero, it could be any default value, usually zero or null.
Answer: b
Explanation: A naive implementation allocates space for the entire size of the array, whereas a sparse
array(linked list implementation) allocates space only for the non-default values.
4. Choose the code which performs the store operation in a sparse array.(Linked list implementation)
a)
b)
c)
advertisement
public void store(int index, Object val)
{
List cur = this;
List prev = null;
List node = new List(index);
node.val = val;
while (cur != null && cur.index < index)
{
cur = cur.next;
prev = cur;
}
if (cur == null)
{
prev.next = node;
} else
{
if (cur.index == index)
{
System.out.println("DUPLICATE");
return;
}
prev.next = node;
node.next = cur;
}
return;
}
d)
Answer: a
Explanation: Create a new node and traverse through the list until you reach the correct position, check for
duplicate and nullity of the list and then insert the node.
b)
c)
d)
Answer: b
Explanation: You travers through the array until the end is reached or the index is found and return the
element at that index, null otherwise.
6. Choose the appropriate code that counts the number of non-zero(non-null) elements in the sparse array.
a)
b)
c)
d)
7. Suppose the contents of an array A are, A = {1, null, null, null, null, 10};
What would be the size of the array considering it as a normal array and a sparse array?
a) 6 and 6
b) 6 and 2
c) 2 and 6
d) 2 and 2
Answer: b
Explanation: A normal array considers null also as an element, but in the sparse array only a non-zero or a
non-null element is considered.
Answer: a
Explanation: Sparsity of a matrix is the fraction of number of zero elements over the total number of zero
elements.
b)
c)
d)
Answer: a
Explanation: Each row in a sparse matrix acts as a sparse array, hence this row with the specified col_index
is the array and the specified position where the element is stored.
11. Which of the following is the disadvantage of sparse matrices over normal matrices?
a) Size
b) Speed
c) Easily compressible
d) Algorithm complexity
Answer: d
Explanation: As the sparse matrix contains zeroes we will compute operations only on non zero values. This
increases the complexity of algorithm as we need to identify index of zero elements first and during
computation we should not take those index. It is a disadvantage. Sparse matrix is easily compressible by
not storing the zero/null elements, they require less memory space, also only the non zero elements have to
be computed, hence computational speed increases.
Answer: c
Explanation: Suffix array is always sorted as it contains all the suffixes of a string in sorted order. Suffix
arrays are used to solve problems related to string, like string matching problems.
Answer: a
Explanation: The suffix array of the string statistics will be:
2 atistics
8 cs
7 ics
4 istics
9s
0 statistics
5 stics
1 tatistics
6 tics
3 tistics
In Suffix array, we only store the indices of suffixes. So, correct option is 2 8 7 4 9 0 5 1 6 3.
Answer: c
Explanation: A suffix tree is a trie, which contains all the suffixes of the given string as their keys and
positions in the string as their values. So, we can construct a suffix array by performing the depth-first
traversal of a suffix tree.
4. Suffix array is space efficient and faster than the suffix tree.
a) True
b) Fasle
Answer: b
Explanation: Suffix arrays are more space efficient than the suffix trees as they just store the original string
and an array of integer. But working with suffix tree is faster than that of the suffix array.
5. If comparison based sorting algorithm is used construct the suffix array, then what will be time required to
construct the suffix array?
a) O(nlogn)
b) O(n2)
c) O(n2logn)
d) O(n2) + O(logn)
Answer: c
Explanation: On average comparison based sorting algorithms require O(nlogn) comparisons. But
comparing a suffix takes O(n). So, overall time to construct the suffix array will be O(nlogn) * O(n) =
O(n2logn).
advertisement
Answer: d
Explanation: Correct choice is : 5 0 6 10 2 3 8 4 9 1 7.
Because the suffix array formed will be: 5 eering 0 engineering 6 ering 10 g 2 gineering 3 ineering 8 ing 4
neering 9 ng 1 ngineering 7 ring.
Answer: c
Explanation: Suffix tree can be created using an LCP array and a suffix array. If we are given a string of
length (n + 1) and its suffix array and LCP array, we can construct the suffix tree in linear time i.e in O(n)
time.
8. What is the time required to locate the occurrences of a pattern P of length m in a string of length n using
suffix array?
a) O(nm)
b) O(n2)
c) O(mnlogn)
d) O(mlogn)
Answer: d
Explanation: Suffix arrays are used to find the occurrences of a pattern in a string. Pattern of length m will
require m characters to compare, so using suffix array we can find occurrences of a pattern in the string of
length n in O(mlogn) time.
Answer: a
Explanation: Suffix array can be constructed in O(n2logn) time using sorting algorithms but it is possible to
build the suffix array in O(nlogn) time using prefix doubling.
10. Which of the following is/are advantages suffix array one suffix tree?
I. Lesser space requirement
II. Improved cache locality
III. Easy construction in linear time
a) Only I
b) All I, II and III
c) Only I and III
d) Only II and III
Answer: b
Explanation: Advantages of the suffix array over suffix tree are : (i) Lesser space requirement (ii) Improved
cache locality and (iii) Simple algorithms to construct suffix arrays in linear time.
Answer: a
Explanation: The order of the matrix is the number of rows X number of columns.
2. Which of the following property does not hold for matrix multiplication?
a) Associative
b) Distributive
c) Commutative
d) Additive Inverse
Answer: c
Explanation: In matrix multiplication, AB != BA
3. How do you allocate a matrix using a single pointer in C?(r and c are the number of rows and columns
respectively)
a) int *arr = malloc(r * c * sizeof(int));
b) int *arr = (int *)malloc(r * c * sizeof(int));
c) int *arr = (int *)malloc(r + c * sizeof(int));
d) int *arr = (int *)malloc(r * c * sizeof(arr));
Answer: b
Explanation: Total number of elements in the matrix will be r*c
4. Select the code snippet which performs matrix multiplication.(a and b are the two given matrices,
resultant marix is c)
a)
b)
advertisement
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
for (int k = 0; k < n; k++)
{
c[i][j] = c[i][j] * a[i][k] * b[k][j];
}
}
}
c)
d)
Answer: a
Explanation: The corresponding elements from the row and column are multiplied and a cumulative sum is
formed.
a) Normal of a matrix
b) Trace of a matrix
c) Square of a matrix
d) Transpose of a matrix
Answer: b
Explanation: Trace of a matrix is the sum of the principal diagonal elements.
Answer: b
Explanation: It starts with the first element and continues in the same row until the end of row is reached and
then proceeds with the next row. C follows row-major order.
Answer: d
Explanation: Numbers uses arrays(1-D) for sorting not matrices(2-D arrays). Solving linear equations is a
separate field in Mathematics involving matrices, Image processing stores the pixels in the form of matrices,
and the graphs are represented with the help of matrices to indicate the nodes and edges.
Answer: d
Explanation: Adjacency and Incidence Matrices are used to store vertices and edges of a graph. It is an
advantage to plot graphs easily using matrices. But Time complexity of a matrix is O(n2) and sometimes the
internal organization becomes tedious. They are all disadvantages of matrices.
10. Matrix A when multiplied with Matrix C gives the Identity matrix I, what is C?
a) Identity matrix
b) Inverse of A
c) Square of A
d) Transpose of A
Answer: b
Explanation: Any square matrix when multiplied with its inverse gives the identity matrix. Note that non
square matrices are not invertible.
Answer: c
Explanation: Sparse Matrix is a matrix in which most of the elements are Zero. Identity Matrix is a matrix in
which all principle diagonal elements are 1 and rest of the elements are Zero. Unit Matrix is also called
Identity Matrix. Zero Matrix is a matrix in which all the elements are Zero.
Answer: a
Explanation: Sparsity of a matrix is equal to 1 minus Density of the matrix. The Sparsity of matrix is defined
as the total number of Zero Valued elements divided total number of elements.
Answer: a
Explanation: Harry Markowitz coined the term Sparse Matrix. James Sylvester coined the term Matrix.
Chris Messina coined the term Hashtag and Arthur Cayley developed the algebraic aspects of a matrix.
4. Is O(n) the Worst case Time Complexity for addition of two Sparse Matrix?
a) True
b) False
Answer: a
Explanation: In Addition, the matrix is traversed linearly, hence it has the time complexity of O(n) where n
is the number of non-zero elements in the largest matrix amongst two.
advertisement
5. The matrix contains m rows and n columns. The matrix is called Sparse Matrix if ________
a) Total number of Zero elements > (m*n)/2
b) Total number of Zero elements = m + n
c) Total number of Zero elements = m/n
d) Total number of Zero elements = m-n
Answer: a
Explanation: For matrix to be Sparse Matrix, it should contain Zero elements more than the non-zero
elements. Total elements of the given matrix is m*n. So if Total number of Zero elements > (m*n)/2, then
the matrix is called Sparse Matrix.
Answer: d
Explanation: Heap is not used to represent Sparse Matrix while in Dictionary, rows and column numbers are
used as Keys and values as Matrix entries, Linked List is used with each node of Four fields (Row, Column,
Value, Next Node) (2D array is used to represent the Sparse Matrix with three fields (Row, Column, Value).
Answer: a
Explanation: A band matrix is a sparse matrix whose non zero elements are bounded to a diagonal band,
comprising the main diagonal and zero or more diagonals on either side.
Answer: b
Explanation: Since Symmetry Sparse Matrix arises as the adjacency matrix of the undirected graph. Hence it
can be stored efficiently as an adjacency list.
Answer: b
Explanation: The number of inversions in an array indicates how close or far the array is from being
completely sorted. The array is sorted if the number of inversions are 0.
Answer: a
Explanation: When an array is sorted then there cannot be any inversion in the array. As the necessary
condition for an inversion is arr[i]>arr[j] and i<j.
3. What is the condition for two elements arr[i] and arr[j] to form an inversion?
a) arr[i]<arr[j]
b) i < j
c) arr[i] < arr[j] and i < j
d) arr[i] > arr[j] and i < j
Answer: d
Explanation: For two elements to form an inversion the necessary condition is arr[i] > arr[j] and i < j. The
number of inversions in an array indicate how close or far the array is from being completely sorted.
Answer: b
Explanation: Number of inversions in an array are maximum when the given array is reverse sorted. As the
necessary condition for an inversion is arr[i]>arr[j] and i<j.
Answer: a
Explanation: Number of inversions in an array are minimum when the given array is sorted. As the
necessary condition for an inversion is arr[i]>arr[j] and i<j.
advertisement
Answer: d
Explanation: The necessary condition for an inversion is arr[i]>arr[j] and i<j. So there are 5 inversions in the
array.
Answer: b
Explanation: The necessary condition for an inversion is arr[i]>arr[j] and i<j. So there are 3 inversions in the
array. These are (5,4), (5,2), (4,2).
8. Choose the correct function from the following which determines the number of inversions in an array?
a)
b)
c)
d)
Answer: b
Explanation: To determine the number of inversions we apply a nested loop and compare the value of each
element with all the elements present after it. Then the count of number of inversions is counted and
returned to the main function.
9. What is the time complexity of the following code that determines the number of inversions in an array?
a) O(n)
b) O(n log n)
c) O(n2)
d) O(log n)
Answer: c
Explanation: The time complexity of the given code is O(n2). It is due to the presence of nested loop.
10. The time complexity of the code that determines the number of inversions in an array using merge sort is
lesser than that of the code that uses loops for the same purpose.
a) true
b) false
Answer: a
Explanation: The time complexity of the code that determines the number of inversions in an array using
merge sort is O(n log n) which is lesser than the time complexity taken by the code that uses loops.
11. What is the time complexity of the code that uses merge sort for determining the number of inversions in
an array?
a) O(n2)
b) O(n)
c) O(log n)
d) O(n log n)
Answer: d
Explanation: The code of merge sort is slightly modified in order to calculate the number of inversions in an
array. So the time complexity of merge sort remains unaffected and hence the time complexity is O(n log n).
12. What is the time complexity of the code that uses self balancing BST for determining the number of
inversions in an array?
a) O(n2)
b) O(n)
c) O(log n)
d) O(n log n)
Answer: d
Explanation: When a self balancing BST like an AVL tree is used to calculate the number of inversions in
an array then the time complexity is O(n log n) as AVL insert takes O(log n) time.
13. The time complexity of the code that determines the number of inversions in an array using self
balancing BST is lesser than that of the code that uses loops for the same purpose.
a) true
b) false
Answer: a
Explanation: The time complexity of the code that determines the number of inversions in an array using
self balancing BST is O(n log n) which is lesser than the time complexity taken by the code that uses loops.
14. What is the space complexity of the code that uses merge sort for determining the number of inversions
in an array?
a) O(n)
b) O(log n)
c) O(1)
d) O(n log n)
Answer: a
Explanation: The space complexity required by the code will be O(n). It is the same as the space complexity
of the code of standard merge sort.
Answer: b
Explanation: When the given array is rotated by 2 then the resulting array will be
Rotation 1: {2,3,4,5,1}
Rotation 2: {3,4,5,1,2}.
Thus, the final array is {3,4,5,1,2}.
#include <iostream>
using namespace std;
int main()
{
int arr[] = {1,2,3,4,5,6};
int n = sizeof(arr)/sizeof(arr[0]);
int d=4;
int temp[10];
for(int i=0;i<d;i++)
temp[i]=arr[i];
int j=0;
for(int i=d;i<n;i++,j++)
arr[j]=arr[i];
int k=0;
for(int i=n-d;i<n;i++,k++)
arr[i]=temp[k];
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
return 0;
}
a) 5 6 1 2 3 4
b) 6 5 4 3 1 2
c) 3 4 5 6 1 2
d) error
Answer: a
Explanation: The given code rotates the given array by 4. It does so by using an array temp[] which stores
the first d elements and then shift them to the end of the array. So the output will be 5 6 1 2 3 4.
#include <iostream>
using namespace std;
int main()
{
int arr[] = {1,2,3,4,5,6};
int n = sizeof(arr)/sizeof(arr[0]);
int d=4;
int temp[10];
for(int i=0;i<d;i++)
temp[i]=arr[i];
int j=0;
for(int i=d;i<n;i++,j++)
arr[j]=arr[i];
int k=0;
for(int i=n-d;i<n;i++,k++)
arr[i]=temp[k];
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
return 0;
}
a) O(d)
b) O(n)
c) O(n2)
d) O(n*d)
Answer: b
Explanation: The given code rotates an input array by d. The longest loop in the code takes n iterations so
the time complexity will be O(n).
advertisement
#include <iostream>
using namespace std;
int main()
{
int arr[] = {1,2,3,4,5,6};
int n = sizeof(arr)/sizeof(arr[0]);
int d=4;
int temp[10];
for(int i=0;i<d;i++)
temp[i]=arr[i];
int j=0;
for(int i=d;i<n;i++,j++)
arr[j]=arr[i];
int k=0;
for(int i=n-d;i<n;i++,k++)
arr[i]=temp[k];
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
return 0;
}
a) O(1)
b) O(n)
c) O(d)
d) O(n*d)
Answer: c
Explanation: The given code rotates an input array by d. It does so by using an auxiliary array temp[] which
stores first d elements of the original array. So the auxiliary space complexity will be O(d).
#include <bits/stdc++.h>
using namespace std;
void func1(int arr[], int n)
{
int k = arr[0], i;
for (i = 0; i < n - 1; i++)
arr[i] = arr[i + 1];
arr[i] = k;
}
void func(int arr[], int d, int n)
{
for (int i = 0; i < d; i++)
func1(arr, n);
}
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
func(arr, 3, n);
printArray(arr, n);
return 0;
}
a) 4 5 1 2 3
b) 3 4 5 1 2
c) 5 4 3 1 2
d) error
Answer: a
Explanation: The given code rotates the input array by 3. It does so by rotating the elements one by one until
the desired rotation is achieved. So the output will be 4 5 1 2 3.
#include <bits/stdc++.h>
using namespace std;
void func1(int arr[], int n)
{
int k = arr[0], i;
for (i = 0; i < n - 1; i++)
arr[i] = arr[i + 1];
arr[i] = k;
}
void func(int arr[], int d, int n)
{
for (int i = 0; i < d; i++)
func1(arr, n);
}
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int d = 3;
func(arr, d, n);
printArray(arr, n);
return 0;
}
a) O(n*d)
b) O(n)
c) O(d)
d) O(n2)
Answer: a
Explanation: The given code rotates the input array by d. It does so by rotating the elements one by one until
the desired rotation is achieved. Each element takes O(n) time for rotation and there are d such elements in
the array. So the time complexity would be O(n*d).
#include <bits/stdc++.h>
using namespace std;
void func1(int arr[], int n)
{
int k = arr[0], i;
for (i = 0; i < n - 1; i++)
arr[i] = arr[i + 1];
arr[i] = k;
}
void func(int arr[], int d, int n)
{
for (int i = 0; i < d; i++)
func1(arr, n);
}
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int d = 3;
func(arr, d, n);
printArray(arr, n);
return 0;
}
a) O(1)
b) O(n)
c) O(d)
d) O(n*d)
Answer: a
Explanation: The given code rotates the input array by d. It does so by rotating the elements one by one until
the desired rotation is achieved. It does not require any auxiliary array for this purpose. So the auxiliary
space complexity will be O(1).
8. To rotate an array by using the algorithm of rotating its elements one by one is an in place algorithm.
a) true
b) false
Answer: a
Explanation: The auxiliary space requirement of the mentioned algorithm is O(1). So it qualifies to be an in
place algorithm.
#include <bits/stdc++.h>
using namespace std;
void func1(int arr[], int left, int right)
{
while (left < right)
{
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
void func(int arr[], int d, int n)
{
func1(arr, 0, d-1);
func1(arr, d, n-1);
func1(arr, 0, n-1);
}
void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
}
int main()
{
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]);
int d = 2;
func(arr, d, n);
printArray(arr, n);
return 0;
}
a) 3 2 1 4 5
b) 3 4 5 1 2
c) 5 4 3 2 1
d) error
Answer: b
Explanation: The given code rotates the input array by 2. It does so by applying a reversal algorithm to
different segments of the array. First d elements and the rest of the array is reversed individually. Then the
whole array is reversed which gives us the desired rotated array. So the output will be 3 4 5 1 2.
10. What will be the auxiliary space complexity of the code to rotate an array by using the reversal algorithm
(d = number of rotations)?
a) O(1)
b) O(n)
c) O(d)
d) O(n*d)
Answer: a
Explanation: The reversal algorithm for rotating an array does not require any auxiliary space. So the
auxiliary space complexity will be O(1).
11. Which of the following is the predefined function for array reversal in C++?
a) rotate()
b) arr_rotate()
c) array_rotate()
d) rot()
Answer: a
Explanation: The predefined function for rotating an array is rotate() in C++. It is defined under the library
algorithm and requires 3 arguments.
12. How many arguments are required by the predefined function rotate() in C++?
a) 1
b) 2
c) 3
d) 4
Answer: c
Explanation: The predefined function for rotating an array is rotate() in C++ which comes under the library
called an algorithm. It requires 3 arguments.
13. Predefined function rotate() in C++ is available under which header file?
a) math
b) stdio
c) stdlib
d) algorithm
Answer: d
Explanation: The predefined function for rotating an array is rotate() in C++ which comes under the library
called algorithm. It requires 3 arguments the first being the pointer to the starting index of the array and the
last being the pointer to the last index of the array. The middle argument is the pointer to the element that
becomes the first element in the rotated array.
14. Which of the following algorithm to rotate an array has the maximum time complexity?
a) rotate elements one by one
b) juggling algorithm
c) reversal algorithm
d) using a temporary array
Answer: a
Explanation: The maximum time complexity is required by the algorithm that rotates elements one by one. It
requires O(n*d) time.
15. What is the time complexity of the juggling algorithm to rotate an array?
a) O(1)
b) O(n)
c) O(d)
d) O(n*d)
Answer: b
Explanation: Time complexity of juggling algorithm is O(n). Its auxiliary space complexity is O(1).
16. Reversal algorithm and juggling algorithm for array rotation have the same time complexity.
a) True
b) False
Answer: a
Explanation: Time complexity of juggling algorithm is O(n) which like that of reversal algorithm. They also
have the same space complexity.
1. What will be the resulting array after reversing arr[]={3,5,4,2}?
a) 2,3,5,4
b) 4,2,3,5
c) 5,4,2,3
d) 2,4,5,3
Answer: d
Explanation: The resulting array upon reversing after reversal is arr[]={2,4,5,3}. We can implement an
algorithm for this purpose in various possible ways.
2. How many swaps are required for reversing an array having n elements where n is an odd number?
a) (n-1) / 2
b) n/2
c) (n/2) – 1
d) (n+1)/2
Answer: a
Explanation: The number of swaps required for an odd element and an even element array is different
because in an odd element array the position of the middle element does not need to be changed. So the
number of swaps will be (n-1) / 2.
3. How many swaps are required for reversing an array having n elements where n is an even number?
a) (n-1) / 2
b) n/2
c) (n/2) – 1
d) (n+1)/2
Answer: b
Explanation: The number of swaps required for an odd element and an even element array is different
because in an odd element array the position of the middle element does not need to be changed. So number
of swaps required will be n/2.
#include <bits/stdc++.h>
using namespace std;
void func(int arr[], int left, int right)
{
while (left < right)
{
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
}
int main()
{
int arr[] = {1,4,3,5};
int n = sizeof(arr) / sizeof(arr[0]);
func(arr, 0, n-1);
printArray(arr, n);
return 0;
}
a) 5 1 4 3
b) 3 5 1 4
c) 5 3 4 1
d) error
Answer: c
Explanation: The given code reverses the input array and then prints the resulting array. So the output of the
given code will be 5 3 4 1.
advertisement
#include <bits/stdc++.h>
using namespace std;
void func(int arr[], int left, int right)
{
while (left < right)
{
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
}
int main()
{
int arr[] = {1,4,3,5};
int n = sizeof(arr) / sizeof(arr[0]);
func(arr, 0, n-1);
printArray(arr, n);
return 0;
}
a) O(n)
b) O(log n)
c) O(1)
d) O(n log n)
Answer: a
Explanation: The given code reverses the input array and then prints the resulting array. So the time
complexity of the given code will linearly vary with the number of elements in the array and thus the time
complexity will be O(n).
6. What will be the auxiliary space requirement of the following code?
#include <bits/stdc++.h>
using namespace std;
void func(int arr[], int left, int right)
{
while (left < right)
{
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
}
int main()
{
int arr[] = {1,4,3,5};
int n = sizeof(arr) / sizeof(arr[0]);
func(arr, 0, n-1);
printArray(arr, n);
return 0;
}
a) O(1)
b) O(n)
c) O(log n)
d) O(n log n)
Answer: a
Explanation: The given code reverses the input array and then prints the resulting array. The given code does
not use any extra array to complete this task thus the auxiliary space requirement is O(1).
#include <bits/stdc++.h>
using namespace std;
void func(int arr[], int left, int right)
{
if (left >= right)
return;
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
func(arr, left + 1, right - 1);
}
void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
}
int main()
{
int arr[] = {1,2,3,4};
int n = sizeof(arr) / sizeof(arr[0]);
func(arr, 0, n-1);
printArray(arr, n);
return 0;
}
a) 1 2 3 4
b) 4 3 2 1
c) 1 4 2 3
d) 4 1 2 3
Answer: b
Explanation: The given code reverses the original array and prints the resulting array. Recursive function is
used to reverse the array.
#include <bits/stdc++.h>
using namespace std;
void func(int arr[], int left, int right)
{
if (left >= right)
return;
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
func(arr, left + 1, right - 1);
}
void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
}
int main()
{
int arr[] = {1,2,3,4};
int n = sizeof(arr) / sizeof(arr[0]);
func(arr, 0, n-1);
printArray(arr, n);
return 0;
}
a) O(1)
b) O(n)
c) O(log n)
d) O(n log n)
Answer: b
Explanation: The given code reverses the original array and prints the resulting array. The number of swaps
is proportional to the number of elements in the array so it requires a time complexity of O(n).
a) 3 2 1 4 5
b) 5 4 3 2 1
c) 1 2 5 4 3
d) error
Answer: a
Explanation: The given code reverses only a specified segment of the input array. As the value of k is given
to be 3 in the code thus only the first three elements of the array will be reversed.
#include <bits/stdc++.h>
using namespace std;
void func(int a[], int n, int k)
{
if (k <= n)
{
for (int i = 0; i < k/2; i++)
swap(a[i], a[k-i-1]);
}
}
int main()
{
int a[] = {1, 2, 3, 4, 5};
int n = sizeof(a) / sizeof(int), k = 3;
func(a, n, k);
for (int i = 0; i < n; ++i)
cout << a[i]<<" ";
return 0;
}
a) O(k)
b) O(n)
c) O(k log k)
d) O(n log n)
Answer: a
Explanation: The given code reverses only a specified segment of the input array. This segment is decided
by the value of k so the time complexity of the code will be O(k).
11. When array reversal and rotation is applied to the same array then the output produced will also be the
same every time.
a) true
b) false
Answer: b
Explanation: Array rotation and array reversal are different operations and thus they give different outputs
when applied to the same array.
12. Which of the following is the predefined function for array reversal in C++ ?
a) reverse()
b) arr_reverse()
c) array_reverse()
d) rev()
Answer: a
Explanation: The predefined function for reversing an array is reverse() in C++. It is defined under the
library algorithm and requires 2 arguments.
13. Which of the following is the predefined function for array reversal in javascript?
a) reverse()
b) arr_reverse()
c) array_reverse()
d) rev()
Answer: a
Explanation: The predefined function for reversing an array is reverse() in javascript. It does not requires
any argument.
14. Predefined function reverse() in C++ is available under which header file?
a) math
b) stdio
c) stdlib
d) algorithm
Answer: d
Explanation: The predefined function for reversing an array is reverse() in C++ which comes under the
library called an algorithm. It requires 2 arguments the first being the pointer to the starting index of the
array and the second being the pointer to the last index of the arra
1. What will be the minimum number of jumps required to reach the end of the array arr[] = {1,3,6,3,6,8,5}?
a) 1
b) 2
c) 3
d) not possible to reach the end
Answer: c
Explanation: Each element of the array represents the maximum number of steps that can be taken forward
from that element. If the first element is 0 then it is not possible to reach the end.
2. What will be the minimum number of jumps required to reach the end of the array arr[]
={0,1,3,6,3,6,8,5}?
a) 1
b) 2
c) 3
d) not possible to reach the end
Answer: d
Explanation: Each element of the array represents the maximum number of steps that can be taken forward
from that element. So as the first element here is 0 so we cannot move any further from the first element.
Thus, it is not possible to reach the end of the array.
#include <bits/stdc++.h>
using namespace std;
int func(int arr[], int s, int e)
{
if (s == e)
return 0;
if (arr[s] == 0)
return INT_MAX;
int min = INT_MAX;
for (int i = s + 1; i <= e && i <= s + arr[s]; i++)
{
int jumps = func(arr, i, e);
if(jumps != INT_MAX && jumps + 1 < min)
min = jumps + 1;
}
return min;
}
int main()
{
int arr[] = {1, 3, 6, 3, 8, 5};
int n = sizeof(arr)/sizeof(arr[0]);
cout << func(arr, 0, n-1);
return 0;
}
a) 1
b) 2
c) 3
d) error
Answer: c
Explanation: The given code finds the minimum number of steps required to reach the end of the array by
using recursion. So the output will be 3.
advertisement
a) 1
b) 2
c) 3
d) error
Answer: c
Explanation: The given code finds the minimum number of steps required to reach the end of the array by
using dynamic programming. So the output will be 3.
#include <bits/stdc++.h>
using namespace std;
int min(int x, int y)
{ return (x < y)? x: y; }
int func(int arr[], int n)
{
int *jump = new int[n];
int i, j;
if (n == 0 || arr[0] == 0)
return INT_MAX;
jump[0] = 0;
for (i = 1; i < n; i++)
{
jump[i] = INT_MAX;
for (j = 0; j < i; j++)
{
if (i <= j + arr[j] && jumps[j] != INT_MAX)
{
jump[i] = min(jump[i], jump[j] + 1);
break;
}
}
}
return jump[n-1];
}
int main()
{
int arr[] = {1, 3, 6, 1, 9,7};
int size = sizeof(arr)/sizeof(int);
cout<< func(arr,size);
return 0;
}
a) O(n log n)
b) O(n)
c) O(n1/2)
d) O(n2)
Answer: d
Explanation: The given code finds the minimum number of steps required to reach the end of an array by
using dynamic programming. As there is a nested loop in the code so the time complexity will be O(n2).
6. What will be the minimum number of jumps required to reach the end of the array arr[] =
{1,2,0,0,3,6,8,5}?
a) 1
b) 2
c) 3
d) not possible to reach the end
Answer: d
Explanation: Each element of the array represents the maximum number of steps that can be taken forward
from that element. So we cannot move any further after reaching the second element hence it is impossible
to reach the end of the array.
7. It is not possible to find the minimum number of steps to reach the end of an array in linear time.
a) true
b) false
Answer: b
Explanation: It is possible to find the minimum number of steps to reach the end of an array in O(n) time
complexity. So it is the fastest possible method of finding the minimum number of steps to reach the end of
an array.
8. In how many different ways we can reach the end of the array arr[]={1,3,5,8,9}?
a) 1
b) 2
c) 3
d) 4
Answer: d
Explanation: There are 4 possible ways in which we can reach the end of the array. The possible paths are –
1->3->5->8->9, 1->3->5->9, 1->3->8->9, 1->3->9.
#include <bits/stdc++.h>
using namespace std;
void func(int arr[], int n)
{
int count[n];
memset(count, 0, sizeof(count));
for (int i=n-2; i>=0; i--)
{
if (arr[i] >= n - i - 1)
count[i]++;
for (int j=i+1; j < n-1 && j <= arr[i] + i; j++)
if (count[j] != -1)
count[i] += count[j];
if (count[i] == 0)
count[i] = -1;
}
for (int i=0; i<n; i++)
cout << count[i] << " ";
}
int main()
{
int arr[] = {1, 3, 5, 8, 9};
int n = sizeof(arr) / sizeof(arr[0]);
func(arr, n);
return 0;
}
a) 3
b) 4
c) 4 4 2 1 0
d) 4 2 2 0 1
Answer: c
Explanation: The given code finds the number of possible ways to reach the end of an array from each
element. So the output will be 4 4 2 1 0.
10. What will be the worst case time complexity of the following code?
#include <bits/stdc++.h>
using namespace std;
void func(int arr[], int n)
{
int count[n];
memset(count, 0, sizeof(count));
for (int i=n-2; i>=0; i--)
{
if (arr[i] >= n - i - 1)
count[i]++;
for (int j=i+1; j < n-1 && j <= arr[i] + i; j++)
if (count[j] != -1)
count[i] += count[j];
if (count[i] == 0)
count[i] = -1;
}
for (int i=0; i<n; i++)
cout << count[i] << " ";
}
int main()
{
int arr[] = {1, 3, 5, 8, 9};
int n = sizeof(arr) / sizeof(arr[0]);
func(arr, n);
return 0;
}
a) O(n1/2)
b) O(n)
c) O(n3/2)
d) O(n2)
Answer: d
Explanation: The given code finds the number of possible ways to reach the end of an array from each
element. By observing the nested loop in the code we can say that the worst case time complexity will be
O(n2).
11. : It is not possible to reach the end of an array if starting element of the array is 0.
a) true
b) false
Answer: a
Explanation: If the first element of an array is 0 then it is not possible to reach the end. However, if 0 is
present at other positions then we may/may not be able to reach the end.
12. What is the minimum possible time complexity to find the number of steps to reach the end of an array?
a) O(n)
b) O(n2)
c) O(n3/2)
d) O(1)
Answer: a
Explanation: The minimum possible time complexity to reach the end of an array is O(n). So a linear time
complexity is possible.
Answer: b
Explanation: It is a datastructure, which can make search in sorted linked list faster in the same way as
binary search tree and sorted array (using binary search) are faster.
Answer: a
Explanation: Let us call the nodes 20, 30, 40 as top lines and the nodes between them as normal lines. the
advantage of skip lists is we can skip all the elements between the top line elements as required.
Answer: d
Explanation: Skip lists have the same asymptotic time complexity as balanced binary search tree. For a
Balanced Binary Search Tree, we skip almost half of the nodes after one comparison with root element. The
same thing done in the skip lists. Hence skip lists are similar to balanced Binary search trees.
4. What is the time complexity improvement of skip lists from linked lists in insertion and deletion?
a) O(n) to O(logn) where n is number of elements
b) O(n) to O(1) where n is number of elements
c) no change
d) O(n) to O(n2) where n is number of elements
Answer: a
Explanation: In Skip list we skip some of the elements by adding more layers. In this the skip list resembles
balanced binary search trees. Thus we can change the time complexity from O (n) to O (logn)
5. To which datastructure are skip lists similar to in terms of time complexities in worst and best cases?
a) balanced binary search trees
b) binary search trees
c) binary trees
d) linked lists
Answer: a
Explanation: Skip lists are similar to any randomly built binary search tree. a BST is balanced because to
avoid skew tree formations in case of sequential input and hence achieve O(logn) in all 3 cases. now skip
lists can gurantee that O(logn) complexity for any input.
advertisement
6. The nodes in a skip list may have many forward references. their number is determined
a) probabilistically
b) randomly
c) sequentially
d) orthogonally
Answer: a
Explanation: The number of forward references are determined probabilistically, that is why skip list is a
probabilistic algorithm.
Answer: a
Explanation: To achieve above operations augment with few additional stuff like partial counts.
8. How to maintain multi-level skip list properties when insertions and deletions are done?
a) design each level of a multi-level skip list with varied probabilities
b) that cannot be maintained
c) rebalancing of lists
d) reconstruction
Answer: a
Explanation: For example consider a 2 level skip list. the level-2 skip list can skip one node on a average
and at some places may skip 2 nodes, depending on probabilities. this ensures O(logn).
Answer: a
Explanation: Skip list behaves as a balanced tree with high probability and can be commented as such
because nodes with different heights are mixed up evenly.
10. What is indexed skip list?
a) it stores width of link in place of element
b) it stores index values
c) array based linked list
d) indexed tree
Answer: a
Explanation: The width is defined as number of bottom layer links that are being traversed by each of higher
layer elements. e.g: for a level-2 skip lists, all level-1 nodes have 1 as width, for level-2 width will be 2.
Answer: d
Explanation: Linear search in a linked list has time complexity O(n). To improve the efficiency of the linear
search the self organizing list is used. A self-organizing list improves the efficiency of linear search by
moving more frequently accessed elements towards the head of the list.
2. Which of the following is true about the Move-To-Front Method for rearranging nodes?
a) node with highest access count is moved to head of the list
b) requires extra storage
c) may over-reward infrequently accessed nodes
d) requires a counter for each node
Answer: c
Explanation: In Move-To-front Method the element which is searched is moved to the head of the list. And
if a node is searched even once, it is moved to the head of the list and given maximum priority even if it is
not going to be accessed frequently in the future. Such a situation is referred to as over-rewarding.
Answer: a
Explanation: In Transpose method, if any node is searched, it is swapped with the node in front unless it is
the head of the list. So, in Transpose method searched node is swapped with its predecessor.
4. The worst case running time of a linear search on the self organizing list is ____
a) O(1)
b) O(logn)
c) O(n)
d) O(n2)
Answer: c
Explanation: Worst case occurs when the element is located at the very end of list. So n comparisons must
be made to the locate element. So the worst case running time of linear search on self organizing list is O(n).
5. Which of the following data structure is preferred to have lesser search time when the list size is small?
a) search tree
b) sorted list
c) self organizing list
d) linked list
Answer: c
Explanation: Self-organizing list is easy and simple to implement than search tree and it requires no
additional space. So using self organizing list is preferred when list size is small.
advertisement
6. In _____________ method, whenever a node is accessed, it might move to the head of the list if its
number of accesses becomes greater than the records preceding it.
a) least recently used
b) count
c) traspose
d) exchange
Answer: b
Explanation: In the count method, the number of times a node was accessed is counted and is stored in a
counter variable associated with each node. Then the nodes are arranged in descending order based on their
access counts. And the node with highest access count is head of the list.
Answer: c
Explanation: Self organizing list allows fast sequential search and it is simple to implement and requires no
extra storage. Self-organizing list is used to implement the symbol table.
8. Which of the following method performs poorly when elements are accessed in sequential order?
a) count method
b) move to front method
c) transpose meth
d) ordering method
Answer: b
Explanation: Move-to-front method performs poorly when the elements are accessed in sequential order,
especially if that sequential order is then repeated multiple times.
Answer: a
Explanation: The self-organizing list rearranges the nodes based on the access probabilities of the nodes. So
the required elements can be located efficiently. Therefore, self-organizing list is mainly used to improve the
average access time.
10. Which of the following is not the rearranging method used to implement self-organizing lists?
a) count method
b) move to front method
c) ordering method
d) least frequently used
Answer: d
Explanation: Least frequently used is a buffer replacement policy, while other three are methods to reorder
the nodes in the self-organizing lists based on their access probability.
Answer: a
Explanation: Why we use bitwise XOR operation is to decrease storage requirements for doubly linked lists.
Answer: a
Explanation: Every node stores the XOR of addresses.
3. What does first and last nodes of a xor linked lists contain ? (let address of first and last be A and B)
a) NULL xor A and B xor NULL
b) NULL and NULL
c) A and B
d) NULL xor A and B
Answer: a
Explanation: NULL xor A and B xor NULL.
Answer: d
Explanation: XOR linked list stores the address of previous and next nodes by performing XOR operations.
It requires single pointer to store both XOR address of next and previous nodes. Thus it reduces space. It is
an advantage. But the main disadvantages are debugging tools cannot follow XOR chain, previous node
address must be remembered to get next nodes and pointers are not defined accurately.
Answer: d
Explanation: The important properties of XOR lists are X⊕X=0, X⊕0=X and (X⊕Y)⊕Z = X⊕(Y⊕Z).
advertisement
Answer: b
Explanation: Xor lists requires same time for most of the operations as arrays would require.
7. What’s wrong with this code which returns xor of two nodes address ?
Answer: b
Explanation: It must be typecasted– return (struct node*)((int) (a) (int) (b));
8. Given 10,8,6,7,9
swap the above numbers such that finally you got 6,7,8,9,10
so now reverse 10
9,7,6,8,10
now reverse 9
8,6,7,9,10
7,6,8,9,10
6,7,8,9,10
at this point 6 is ahead so no more reversing can be done so stop.
To implement above algorithm which datastructure is better and why ?
a) linked list. because we can swap elements easily
b) arrays. because we can swap elements easily
c) xor linked list. because there is no overhead of pointers and so memory is saved
d) doubly linked list. because you can traverse back and forth
Answer: c
Explanation: XOR linked lists are used to reduce the memory by storing the XOR values of address instead
of actual address in pointers.
9. Consider the following pseudocode of insertion in XOR list and write the approximate code snippet of it.
a)
b)
c)
d)
Answer: a
Explanation: They code for the english is
node* next = XOR ((*head_ref)->npx, NULL);
(*head_ref)->npx = XOR (new_node, next);
10. In the above question would using arrays and swaping of elements in place of xor linked list would have
been more efficient?
a) no not all
b) yes arrays would have been better than xor lists
c) both would be same in efficiency
d) can’t say
Answer: b
Explanation: The locality of a normal array is faster in memory and moreover one has to traverse n-nodes to
reach the target to reverse in case of xor linked list.
Answer: b
Explanation: Their property is meant for dynamic allocations.
Answer: a
Explanation: Gc and new most widely known.
Answer: b
Explanation: Sort trees can also be used in impelementing free lists which remaincomplex.
4. What are different ways of implementing free lists and which is simple among them?
a) best fit, first fit, worst fit, simple-first fit
b) best fit, first fit, worst fit, simple-best fit
c) best fit, first fit, worst fit, simple-worst fit
d) best fit simple-best fit
Answer: a
Explanation: The simplest form of memory management system can be called as first-fit. a device or system
maintains a single list of free memory locations. When request to memory is sent, the list is searched and the
first block that is large enough is returned.
Answer: b
Explanation: When an allocation request is received, the list that holds blocks that are just large enough to
satisfy the request are considered, and an open location is returned. If no free blocks that are smaller than
two times the size that are requested are available, a larger block is split in two to satisfy the requirements.
advertisement
6. How does implicit free lists(garbage collection) works in adding memory to free list ?
a) whichever comes last will be added to free list
b) whichever comes first will be added to free list
c) certain blocks cannot be used if there are no pointers to them and hence they can be freed
d) makes a probabilistic guess
Answer: c
Explanation: When no pointers pointing a block that means it is useless to be in memory.
7. What are the disadvantages in implementing buddy system algorithm for free lists?
a) internal fragmentation
b) it takes so much space
c) we no more have the hole lists in order of memory address, so it is difficult to detect if 2 holes remain
adjacent in memory and shall be merged into one hole
d) both a and c are correct
Answer: d
Explanation: Internal fragmentation is an issue to be dealt and it takes so much space.
8. Assume there is a free list which contains nodes and is filled with a value if it is already assigned and the
value will be the size of requested block else will be 0.
z = startpoint;
while ((z < end) && \\ didn't reach end
(*z <= len)) \\ too small to satisfy request
{
assign this block
}
Answer: a
Explanation: As z is start point and now from beginning we are moving and checking if we reached end and
then checking size naively assigning the first block which is bigger than required size hence it is first fit.
9. How are free blocks linked together mostly and in what addressing order?
a) circular linked list and increasing addressing order
b) linked list and decreasing addressing order
c) linked list and in no addressing order
d) none of the mentioned
Answer: a
Explanation: A common way is circular linked list and address are arranged in increasing order because
merging would be easier which is actually a problem in buddy memory allocation.
10. Accessing free list very frequently for wide range of addresses can lead to
a) paging
b) segmentation fault
c) memory errors
d) cache problems
Answer: a
Explanation: Paging in/out of disk will be caused.
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
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
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
Answer: a
Explanation: Floor of w-1/2 because we can’t miss a node.
advertisement
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
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;
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
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?
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
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
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
arra
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
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.
advertisement
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
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
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
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
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
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.
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.
advertisement
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.
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.
10. The average depth of a binary tree is given as?
a) O(N)
b) O(√N)
c) O(N2)
d) O(log N)
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
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
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
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.
15. Construct a binary tree using the following data.
The preorder traversal of a binary tree is 1, 2, 5, 3, 4. The inorder traversal of the same binary tree is 2, 5, 1,
4, 3.
a)
b)
c)
d)
Answer: d
Explanation: Here,
Preorder Traversal is 1, 2, 5, 3, 4
Inorder Traversal is 2, 5
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
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
Answer: c
Explanation: Post order traversal follows LRN(Left-Right-Node).
b)
c)
advertisement
public void preorder(Tree root)
{
System.out.println(root.data);
preorder(root.right);
preorder(root.left);
}
d)
Answer: a
Explanation: Pre-order traversal follows NLR(Node-Left-Right).
4. Select the code snippet which performs post-order traversal.
a)
public void postorder(Tree root)
{
System.out.println(root.data);
postorder(root.left);
postorder(root.right);
}
b)
c)
d)
b)
c)
d)
Answer: c
Explanation: Add the root to the stack first, then continously check for the right and left children of the top-
of-the-stack.
6. Select the code snippet that performs post-order traversal iteratively.
a)
public void postorder(Tree root)
{
if (root == null)
return;
Stack<Tree> stk = new Stack<Tree>();
Tree node = root;
while (!stk.isEmpty() || node != null)
{
while (node != null)
{
if (node.right != null)
stk.add(node.left);
stk.add(node);
node = node.right;
}
node = stk.pop();
if (node.right != null && !stk.isEmpty() && node.right == stk.peek())
{
Trees nodeRight = stk.pop();
stk.push(node);
node = nodeRight;
} else
{
System.out.print(node.data + " ");
node = null;
}
}
}
b)
c)
d)
Answer: b
Explanation: The left and right children are added first to the stack, followed by the node, which is then
popped. Post-order follows LRN policy.
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)
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
Answer: b
Explanation: The inorder sequence is B, E, A, D, C and Preorder sequence is A, B, E, C, D. The tree
constructed with the inorder and preorder sequence is
The levelorder traversal (BFS traversal) is A, B, C, E, D.
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
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
1. In postorder traversal of binary tree right subtree is traversed before visiting root.
a) True
b) False
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
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
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
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
Answer: b
Explanation: A binary tree can uniquely be created by post-order and in-order traversals.
advertisement
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
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
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
Answer: a
Explanation: The tree generated by using given pre-order and in-order traversal is
10. For a binary tree the first node visited in in-order and post-order traversal is same.
a) True
b) False
Answer: b
Explanation: Consider a binary tree,
Its in-order traversal – 13 14 16 19
Its post-order traversal- 14 13 19 16. Here the first node visited is not same.
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
Answer: c
Explanation: In postorder traversal the left subtree is traversed first and then the right subtree and then the
current node. So, the postu
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
Answer: a
Explanation: In-order traversal follows LNR(Left-Node-Right).
2. For the tree below, write the level-order traversal.
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
Answer: b
Explanation: Level order traversal follows a breadth first search approach.
b)
advertisement
public void inorder(Tree root)
{
inorder(root.left);
System.out.println(root.data);
inorder(root.right);
}
c)
d)
b)
c)
d)
Answer: a
Explanation: Firstly add the root node to the queue. Then for all the remaining nodes, pop the front end of
the queue and print it, add the left and right children of the popped node to the queue.
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)
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
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
Answer: d
Explanation: In a binary sea
1. The number of edges from the root to the node is called __________ of the tree.
a) Height
b) Depth
c) Length
d) Width
Answer: b
Explanation: The number of edges from the root to the node is called depth of the tree.
2. The number of edges from the node to the deepest leaf is called _________ of the tree.
a) Height
b) Depth
c) Length
d) Width
Answer: a
Explanation: The number of edges from the node to the deepest leaf is called height of the tree.
Answer: a
Explanation: A full binary tree is a tree in which each node has exactly 0 or 2 children.
Answer: c
Explanation: A binary tree, which is completely filled, with the possible exception of the bottom level,
which is filled from left to right is called complete binary tree. A Tree in which each node has exactly zero
or two children is called full binary tree. A Tree in which the degree of each node is 2 except leaf nodes is
called perfect binary tree.
5. What is the average case time complexity for finding the height of the binary tree?
a) h = O(loglogn)
b) h = O(nlogn)
c) h = O(n)
d) h = O(log n)
Answer: d
Explanation: The nodes are either a part of left sub tree or the right sub tree, so we don’t have to traverse all
the nodes, this means the complexity is lesser than n, in the average case, assuming the nodes are spread
evenly, the time complexity becomes O(logn).
advertisement
Answer: d
Explanation: Undo/Redo operations in a notepad is an application of stack. Hierarchical structure, Faster
search, Router algorithms are advantages of trees.
7. In a full binary tree if number of internal nodes is I, then number of leaves L are?
a) L = 2*I
b) L = I + 1
c) L = I – 1
d) L = 2*I – 1
Answer: b
Explanation: Number of Leaf nodes in full binary tree is equal to 1 + Number of Internal Nodes i.e L = I + 1
8. In a full binary tree if number of internal nodes is I, then number of nodes N are?
a) N = 2*I
b) N = I + 1
c) N = I – 1
d) N = 2*I + 1
Answer: d
Explanation: Relation between number of internal nodes(I) and nodes(N) is N = 2*I+1.
9. In a full binary tree if there are L leaves, then total number of nodes N are?
a) N = 2*L
b) N = L + 1
c) N = L – 1
d) N = 2*L – 1
Answer: d
Explanation: The relation between number of nodes(N) and leaves(L) is N=2*L-1.
Answer: d
Explanation: In a binary tree, there are atmost 2k nodes in level k and 2k-1 total number of nodes. Number of
levels is at least ceil(log(N+1)).
11. Construct a binary tree by using postorder and inorder sequences given below.
Inorder: N, M, P, O, Q
Postorder: N, P, Q, O, M
a)
b)
c)
d)
Answer: d
Explanation: Here,
Postorder Traversal: N, P, Q, O, M
Inorder Traversal: N, M, P, O, Q
Root node of tree is the last visiting node in Postorder traversal. Thus, Root Node = ‘M’.
The partial tree constructed is:
The second last node in postorder traversal is O. Thus, node P becomes left child of node O and node Q
becomes right child of node Q. Thus, the final tree is:
12. Construct a binary search tree by using postorder sequence given below.
Postorder: 2, 4, 3, 7, 9, 8, 5.
a)
b)
c)
d)
Answer: b
Explanation: Postorder sequence is 2, 4, 3, 7, 9, 8, 5.
Inorder sequence is the ascending order of nodes in Binary search tree. Thus, Inorder sequence is 2, 3, 4, 5,
7, 8, 9. The tree constructed using Postorder and Inorder sequence is
13. Construct a binary tree using inorder and level order traversal given below.
Inorder Traversal: 3, 4, 2, 1, 5, 8, 9
Level Order Traversal: 1, 4, 5, 9, 8, 2, 3
a)
b)
c)
d)
Answer: a
Explanation: Inorder Traversal: 3, 4, 2, 1, 5, 8, 9
Level Order Traversal: 1, 4, 5, 9, 8, 2, 3
In level order traversal fi
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.
c)
d)
advertisement
public Tree search(Tree root, int key)
{
if( root == null)
{
return root;
}
if( root.key < key )
{
return search(root.right.right,key);
}
else
return search(root.left.left,key);
}
Answer: a
Explanation: As we know that the left child is lesser than the parent, if the root’s key is greater than the
given key, we look only into the left sub-tree, similarly for right sub-tree.
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
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
Answer: c
Explanation: In a postorder traversal, first the left child is visited, then the right child and finally the parent.
a) Preorder traversal
b) Inorder traversal
c) Postorder traversal
d) Level order traversal
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)
Answer: a
Explanation: Since all the elements lesser than a given node will be towards the left, iterating to the leftmost
leaf of the root will give the minimum element in a binary search tree.
7. How will you find the maximum element in a binary search tree?
a)
b)
c)
d)
Answer: c
Explanation: Since all the elements greater than a given node are towards the right, iterating through the tree
to the rightmost leaf of the root will give the maximum element in a binary search tree.
8. What are the worst case and average case complexities of a binary search tree?
a) O(n), O(n)
b) O(logn), O(logn)
c) O(logn), O(n)
d) O(n), O(logn)
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)
d)
Answer: c
Explanation: The property of a binary search tree is that the lesser elements are to the left and greater
elements are to the right, we use this property here and iterate through the tree such that we reach a point
where the 2 elements are on 2 different sides of the node, this becomes the least common ancestor of the 2
given elements.
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
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.
b)
c)
d)
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 will be the height of a balanced full binary tree with 8 leaves?
a) 8
b) 5
c) 6
d) 4
Answer: d
Explanation: A balanced full binary tree with l leaves has height h, where h = log2l + 1.
So, the height of a balanced full binary tree with 8 leaves = log28 + 1 = 3 + 1 = 4.
Answer: c
Explanation: For a node in a binary tree, the difference between the heights of its left subtree and right
subtree is known as balance factor of the node.
3. Figure below is a balanced binary tree. If a node inserted as child of the node R, how many nodes will
become unbalanced?
a) 2
b) 1
c) 3
d) 0
Answer: b
Explanation: Only the node P will become unbalanced, with balance factor +2.
4. A binary tree is balanced if the difference between left and right subtree of every node is not more than
____
a) 1
b) 3
c) 2
d) 0
Answer: a
Explanation: In a balanced binary tree the heights of two subtrees of every node never differ by more than 1.
5. Which of the following tree data structures is not a balanced binary tree?
a) AVL tree
b) Red-black tree
c) Splay tree
d) B-tree
Answer: d
Explanation: All the tree data structures given in options are balanced, but B-tree can have more than two
children.
advertisement
a)
b)
c)
d)
Answer: b
Explanation: In Some tree diagrams, the root of tree has balance factor +2, so the tree is not balanced. If
every node in the tree is balanced, then it’s a balanced tree.
7. Balanced binary tree with n items allows the lookup of an item in ____ worst-case time.
a) O(log n)
b) O(nlog 2)
c) O(n)
d) O(1)
Answer: a
Explanation: Searching an item in balanced binary is fast and worst-case time complexity of the search is
O(log n).
8. Which of the following data structures can be efficiently implemented using height balanced binary
search tree?
a) sets
b) priority queue
c) heap
d) both sets and priority queue
Answer: d
Explanation: Height-Balanced binary search tree can provide an efficient implementation of sets, priority
queues.
9. Two balanced binary trees are given with m and n elements respectively. They can be merged into a
balanced binary search tree in ____ time.
a) O(m+n)
b) O(mn)
c) O(m)
d) O(mlog n)
Answer: a
Explanation: First we store the in-order traversals of both the trees in two separate arrays and then we can
merge these sorted sequences in O(m+n) time. And then we construct the balanced tree from this final sorted
array.
10. Which of the following is an advantage of balanced binary search tree, like AVL tree, compared to
binary heap?
a) insertion takes less time
b) deletion takes less time
c) searching takes less time
d) construction of the tree takes less time than binary heap
Answer: a
Explanation: Insertion and deletion, in both the binary heap and balanced binary search tree takes O(log n).
But searching in balanced binary search tree requires O(log n) while binary heap takes O(n). Construction of
balanced binary search tree takes O(nlog n) time while binary heap takes O(n).
Answer: a
Explanation: AVL tree is more balanced than a Red-black tree because AVL tree has less height than Red-
black tree given that both trees have the same number of elements.
12. The figure shown below is a balanced binary tree. If node P is deleted, which of the following nodes will
get unbalanced?
a) U
b) M
c) H
d) A
Answer: a
Explanation: Node U will get unbalanced if node P is deleted, because it’s balance factor will become -2.
1. Which of the following is not the self balancing binary search tree?
a) AVL Tree
b) 2-3-4 Tree
c) Red – Black Tree
d) Splay Tree
Answer: b
Explanation: 2-3-4 Tree is balanced search trees. But it is not a binary tree. So, it is not a self balancing
binary tree. AVL tree, Red-Black Tree and Splay tree are self balancing binary search tree.
2. The binary tree sort implemented using a self – balancing binary search tree takes ______ time is worst
case.
a) O(n log n)
b) O(n)
c) O(n2)
d) O(log n)
Answer: a
Explanation: The worst case running time of the binary tree sort is O(n2). But, the worst case running time
can be improved to the O(n log n) using a self – balancing binary search tree.
3. An AVL tree is a self – balancing binary search tree, in which the heights of the two child sub trees of any
node differ by _________
a) At least one
b) At most one
c) Two
d) At most two
Answer: b
Explanation: In an AVL tree, the difference between heights of the two child sub trees of any node is at most
one. If the height differs by more than one, AVL tree performs rotations to balance the tree.
Answer: d
Explanation: Associative arrays can be implemented using a self balancing binary search tree as the worst-
case time performance of self – balancing binary search trees is O(log n).
5. Self – balancing binary search trees have a much better average-case time complexity than hash tables.
a) True
b) False
Answer: b
Explanation: For lookup, insertion and deletion hash table take O(1) time in average-case while self –
balancing binary search trees takes O(log n). Therefore, hash tables perform better in average-case.
advertisement
Answer: c
Explanation: An AA tree, which is a variation of red-black tree, is a self – balancing binary search tree. 2-3
is B-tree of order 3 and Treat is a randomized binary search tree. A threaded binary tree is not a balanced
tree.
8. In which of the following self – balancing binary search tree the recently accessed element can be
accessed quickly?
a) AVL tree
b) AA tree
c) Splay tree
d) Red – Black tree
Answer: c
Explanation: In a Splay tree, the recently accessed element can be accessed quickly. In Splay tree, the
frequently accessed nodes are moved towards the root so they are quick to access again.
9. The minimum height of self balancing binary search tree with n nodes is _____
a) log2(n)
b) n
c) 2n + 1
d) 2n – 1
Answer: a
Explanation: Self – balancing binary trees adjust the height by performing transformations on the tree at key
insertion times, in order to keep the height proportional to log2(n).
10. Binary tree sort implemented using a self balancing binary search tree takes O(n log n) time in the worst
case but still it is slower than merge sort.
a) True
b) False
Answer: a
Explanation: The worst case performance of binary tree sort is O(n log n) when it is implemented using a
self balancing binary search tree. Self balancing binary search trees perform transformations to balan
Answer: d
Explanation: Treap, also known as random binary search tree, Random binary tree and Uniform spanning
tree are all random tree. Random tree is a tree formed by a random process of addition and deletion of nodes.
AVL tree is a self – balanced binary search tree.
Answer: a
Explanation: The randomized binary search tree is formed by the stochastic process. The stochastic process
or also called random process is a mathematical tool or object including random variables.
3. How many randomized binary search trees can be formed by the numbers (1, 3, 2)?
a) 2
b) 3
c) 6
d) 5
Answer: d
Explanation: As there are 3 numbers (1, 3, 2) so total of 6 combinations can be formed using three numbers
but Since (2, 1, 3) and (2, 3, 1) are same so in total there are 5 randomized binary search tree that can be
formed.
Answer: d
Explanation: The expected value of depth of a node that is for a node a, the expected value of length of path
from root to node a is found to be at most 2 log n + O(1).
5. What is the longest length path for a node x in random binary search tree for the insertion process?
a) log x
b) x2
c) x!
d) 4.311 log x
Answer: d
Explanation: Although it is difficult to find the length of the longest path in randomized binary search tree,
but it has been found that the longest length is around 4.311 log x.
advertisement
6. What is the range of β in finding the length of the longest path in a randomized binary search tree?
a) (-1, 0)
b) (1, 0)
c) (0, 5)
d) (0, 1)
Answer: d
Explanation: The longest path in a randomized binary search tree, but it has been found that the longest
length is around 4.311 log x for node x. This is also equal to 1/β log x where β lies in the range (0, 1).
Answer: b
Explanation: In a random mathematical model, the expected value of number of leaves in a randomized
binary search tree is found to be exactly (n + 1)/3 using probability.
Answer: a
Explanation: Treap is a type of data structure which is a combination of binary tree and heap. It is an
example of a randomized binary search tree. It stores value in pairs.
Answer: d
Explanation: Catalan number is a sequence of natural number that is used in counting problem. Hence it is
found that the selecting off a tree uniformly at random is reciprocal of Catalan number.
Answer: a
Explanation: Beta distrib
Answer: b
Explanation: AA Trees are implemented using levels instead of colors to overcome the disadvantages of
Red-Black trees.
Answer: a
Explanation: A left horizontal link is removed by right rotation. A right horizontal link is removed by left
rotation.
Answer: b
Explanation: A skew removes a left horizontal link by right rotation and a split removes a right horizontal
link by left rotation.
Answer: b
Explanation: In an AA-tree, skew is processed first followed by a split.
advertisement
Answer: c
Explanation: An AA-Tree needs to consider only two shapes unlike a red-black tree which needs to consider
seven shapes of transformation.
7. What is the prime condition of AA-tree which makes it simpler than a red-black tree?
a) Only right children can be red
b) Only left children can be red
c) Right children should strictly be black
d) There should be no left children
Answer: a
Explanation: The prime condition of AA-Tree is that only the right children can be red to eliminate possible
restructuring cases.
8. Which of the following trees is similar to that of an AA-Tree?
a) Splay Tree
b) B+ Tree
c) AVL Tree
d) Red-Black Tree
Answer: d
Explanation: AA- Tree is a small variation of Red-Black tree. AA-Trees overcome the complexity faced in
performing insertion and deletion in Red-Black Trees.
Answer: b
Explanation: The worst case analysis of an AA-Tree is mathematically found to be O(log N).
Answer: a
Explanation: AA- trees make more rotations than a red-black tree since only two shapes are considered for
an AA-Tree whereas seven shapes are considered in Red-Black trees.
Answer: a
Explanation: AA-tree is invented by Arne Anderson. Daniel Sleator invented Splay Tree. Rudolf Bayer
invented a Red-Black tree. Jon Louis Bentley invented K-d tree.
12. What should be the condition for the level of a left node?
a) It should be less than or equal to that of its parent
b) It should be greater than that of its parent
c) It should be strictly less than that of its parent
d) The level should be equal to one
Answer: c
Explanation: The level of a left node should be strictly less than that of its parent. The level of a right node is
less than or equal to that of its parent.
13. Of the following rules that are followed by an AA-tree, which of the following is incorrect?
1- Only right children can be red
2- Procedures are coded recursively
3- Instead of storing colors, the level of a node is stored
4- There should not be any left children
a) 1
b) 2
c) 3
d) 4
Answer: d
Explanation: In an AA-Tree, both left and right children can be present. The only condition is that only right
children can be red.
a) left rotation
b) right rotation
c) insertion
d) deletion
Answer: b
Explanation: B is initially the right child of X. It is then rotated right side and now, B is the left child of P.
15. Comparing the speed of execution of Red-Black trees and AA-trees, which one has the faster search
time?
a) AA-tree
b) Red-Black tree
c) Both have an equal search time
d) It depends
Answer: a
Explanation: Since an AA-tree tends
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
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.
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
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.
advertisement
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
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
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).
Does the above code can check if a binary search tree is an AVL tree?
a) yes
b) no
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)
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 num
Answer: c
Explanation: A tree with heap property (parent is either small or big than children) and when traversed in
inorder yields the given input sequence. refer below diagram question for clarity.
2. Is the below tree representation of 50,100,400,300,280 correct way to represent cartesian tree?
a) true
b) false
Answer: a
Explanation: A tree with heap property (parent is either small or big than children) and when traversed in
inorder yields the given input sequence is called as a cartesian tree. as the above figure satisies both the
properties. note that even min heap tree can be generated. the above is a max heap tree.
3. Which of the below statements are true?
i. Cartesian tree is not a height balanced tree
ii. Cartesian tree of a sequence of unique numbers can be unique generated
a) both statements are true
b) only i. is true
c) only ii. is true
d) both are false
Answer: a
Explanation: A height balanced cartesian tree is not possible as seen in above question. also any time a
unique sequnce possess a unique cartesian tree, this can be proven through induction.
Answer: a
Explanation: It can sort a set which requires only some sorting or displacements. for example consider 78,
79, 80, 82, 81, 83, In this only 81 and 82 must be swaped to make it a complete sorted set, in this case
cartesian sort comes to the rescue.
5. Consider a sequence of numbers to have repetitions, how a cartesian tree can be constructed in such
situations without violating any rules?
a) use any tie-breaking rule between repeated elements
b) cartesian tree is impossible when repetitions are present
c) construct a max heap in such cases
d) construct a min heap in such cases
Answer: a
Explanation: Consider any of the tie breaking rules, for example the element which appears first can be
taken as small among the same elements and then apply cartesian tree rules.
advertisement
Answer: b
Explanation: The above given steps are for sorting a cartesian tree. cartesian sort is benificial in case of
partially sorted set of elements. a cartesian sort can be considered as a selection or heap sort maintaing a
priority queue.
7. Cartesian trees are most suitable for?
a) searching
b) finding nth element
c) minimum range query and lowest common ancestors
d) self balancing a tree
Answer: c
Explanation: In a cartesian tree minimum value can be found by finding lowest common ancestor for the
extreme elements. consider 11,9,19,16 the lowest element is 9 and is a lowest common ancestor for 11 and
16. and by applying few techniques cartesian tree can be used to even find lowest common ancestors
efficiently.
these can be done in constant time. tree can be constructed in linear time (this is the most efficient time for
any tree construction) and takes space as many elements are there.
Answer: a
Explanation: A cartesian tree, if feeded with a sorted sequence will generate a straight path (or in tree
terminology a skew tree). moreover a cartesian tree basing on same values from the search keys doesnot
work well. so a cartesian tree with priority value in addition to search key is called treap.
Answer: a
Explanation: Range minmum query is finding the minimum element in a given subarray of an array.
Constant time is achieved by storing the Cartesian trees for all the blocks in the array. Rmq’s are used in
string matchings, computing lowest common ancestor and longest common prefix of a sring.
Answer: d
Explanation: This can be solved efficiently using treap which is a modification of cartesian tree. an attribute
like “boolean reverse”
1. What is a weight balanced tree?
a) A binary tree that stores the sizes of subtrees in nodes
b) A binary tree with an additional attribute of weight
c) A height balanced binary tree
d) A normal binary tree
Answer: a
Explanation: Unlike AVL and redblack trees which uses height and color as book keeping information,
weight balanced trees use the size of subtrees.
Answer: a
Explanation: They are a type of self balancing trees which are mostly used in storing key-value pairs, which
is mostly used in functional programming languages. they are very useful to maintain big set of ordered
objects.
Answer: a
Explanation: As a weight balanced tree stores height of the subtrees, we need to use size as an additional
attribute to every node. also value(for mappings) may be an optional attribute.
Answer: a
Explanation: Size of a node k is size[k] = size[k.left] + 1 + size[k.right] and based on this the weight will be
given as weight[k] = size[k] + 1.
5. What is the condition for a tree to be weight balanced. where a is factor and n is a node?
a) weight[n.left] >= a*weight[n] and weight[n.right] >= a*weight[n].
b) weight[n.left] >= a*weight[n.right] and weight[n.right] >= a*weight[n].
c) weight[n.left] >= a*weight[n.left] and weight[n.right] >= a*weight[n].
d) weight[n] is a non zero
Answer: a
Explanation: The tree is said to be a-balanced if the condition is satisfied. and ‘a’ value will be determined
during tree formation. large value of ‘a’ is more effective.
advertisement
6. What are the operations that can be performed on weight balanced tree?
a) all basic operations and set intersection, set union and subset test
b) all basic operations
c) set intersection, set union and subset test
d) only insertion and deletion
Answer: a
Explanation: The speciality of a weight balanced tree is a part from basic operations we can perform
collective operations like set intersection, which helps in rapid prototyping in functional programming
languages.
7. Consider a weight balanced tree such that, the number of nodes in the left sub tree is at least half and at
most twice the number of nodes in the right sub tree. The maximum possible height (number of nodes on the
path from the root to the farthest leaf) of such a tree on k nodes can be described as
a) log2 n
b) log4/3 n
c) log3 n
d) log3/2 n
Answer: d
Explanation: Total number of nodes can be described by the recurrence T(n) = T((n-1)/3)) + T(2(n-1)/3) + 1
T(1) = 1. height of the tree will be H(n) = H(2/3(n-1)) + 1, H(1). drawing a recurrence tree and the cost at
each level is 1 and the height will be log(3/2)n.
8. Why the below pseudo code where x is a value, wt is weight factor and t is root node can’t insert?
a) when x>t. element Rotate-with-left-child should take place and vice versa
b) the logic is incorrect
c) the condition for rotating children is wrong
d) insertion cannot be performed in weight balanced trees
Answer: a
Explanation: The rotations of children must be interchanged in the code.
9. What does the below definations convey?
i. A binary tree is balanced if for every node it is gonna hold that the number of inner nodes in the left
subtree and the number of inner nodes in the right subtree differ by at most 1.
ii. A binary tree is balanced if for any two leaves the difference of the depth is at most 1.
a) weight balanced and height balanced tree definations
b) height balanced and weight balanced tree definations
c) definations of weight balanced tree
d) definations of height balanced tree
Answer: a
Explanation: They are the definations of weight and height balanceness. height balanced trees wont convey
weight balanceness but opposite can be true.
10. Elements in a tree can be indexed by its position under the ordering of the keys and the ordinal position
of an element can be determined, both with good efficiency.
a) true
b) false
Answer: a
Explanation: In a weight b
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
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.
3. Cosider the below formations of red-black tree.
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
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
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
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
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.
Answer: a
Explanation: Top tree is a type of data structure which is based on unrooted dynamic binary tree and is used
to solve path related problems. It allows an algorithm called divide and conquer.
2. For how many vertices in a set, is top tree defined for underlying tree?
a) 3
b) 4
c) 5
d) 2
Answer: d
Explanation: Top tree is defined for a set having a maximum of 2 vertices for its underlying tree. Those sets
having at maximum 2 vertices is called External Boundary Vertices.
Answer: a
Explanation: There are at least 2 edges present in path cluster. Cluster in data structure is defined as the
subtree that is connect having maximum of 2 vertices known as Boundary Vertices.
Answer: a
Explanation: If a cluster has no edges and contains only one vertex known as boundary vertex then, it is
known as leaf cluster. So a leaf cluster doesn’t contain any edges. It is also known as Point cluster.
Answer: b
Explanation: A cluster containing only single edge is known as Edge cluster. So there are in total 1 edge
present in edge cluster. Cluster in data structure is defined as the subtree that is connect having maximum of
2 vertices known as Boundary Vertices.
advertisement
6. Which data structure is used to maintain a dynamic forest using a link or cut operation?
a) Top Tree
b) Array
c) Linked List
d) Stack
Answer: a
Explanation: Top tree data structure is used to maintain a dynamic forest using link or cut operations. Top
tree is a type of data structure which is based on unrooted dynamic binary tree and is used to solve path
related problems.
7. If A ꓵ B (A and B are two clusters) is a singleton set then it is a Merge able cluster.
a) True
b) False
Answer: a
Explanation: If A ꓵ B is a singleton set where A and B are two clusters, that is there are only one node that
is common between the clusters then they are known as Merge able cluster.
8. Is Top tree used for maintaining Dynamic set of trees called forest.
a) True
b) False
Answer: a
Explanation: Top tree data structure is used to maintain a dynamic forest using link or cut operations. Top
tree is a type of data structure which is based on unrooted dynamic binary tree and is used to solve path
related problems.
Answer: a
Explanation: Generally, trees have weight on its edges. Also there is one to one correspondence of the edges
with the top trees. Therefore, top trees can be initialized in O (n) time.
10. How many top trees are there in a tree with single vertex?
a) 0
b) 1
c) 2
d) 3
Answer: a
Explanation: Tree having a single vertex has no clusters of tree present in the structure. Therefore, there are
empty top trees in a tree having a single vertex. Trees with one node are single node.
Answer: d
Explanation: Top tree can be considered as a binary tree if the nodes form a cluster, leaves act as an edge
and the root of the top tree acts as a tree itself. Then the top tree is called binary tree.
12. Which of the dynamic operations are used in Top Tree data structure implementation?
a) Link
b) Cut
c) Expose
d) All of the mentioned
Answer: d
Explanation: Link returns a single tree having different vertices from top trees. Cut removes the edge from
the top tree. Expose is used to implement queries on top trees. Hence all of the options are used as dynamic
operations.
13. Which of the following are used as an internal operation in Top tree?
a) Merge
b) Cut
c) Expose
d) Link
Answer: a
Explanation: Link returns a single tree having different vertices from top trees. Cut removes the edge from
the top tree. Expose is used to implement queries on top trees. While merge is an internal operation used to
merge two clusters and return as a parent cluster.
14. What is the time complexity for maintaining a dynamic set of weighted trees?
a) O (n)
b) O (n2)
c) O (log n)
d) O (n!)
Answer: c
Explanation: A lot of applications have been implemented using Top tree interface. Maintaining a dynamic
set of weighted trees is on
Answer: a
Explanation: Splay trees are height balanced, self adjusting BST’s.
Answer: b
Explanation: This is a property of splay tree that ensures faster access. we push the most recently used nodes
to top which leads to faster access to recently used values.
Answer: c
Explanation: Whenever you insert an element or remove or read an element that will be pushed or stored at
the top which facilitates easier access or recently used stuff.
Answer: a
Explanation: We go with amortized time complexity when we feel that not all operations are worst and some
can be efficiently done. in splay trees not all splay operations will lead to O(logn) worst case complexity.
Answer: b
Explanation: Splay trees mainly work using splay operations. wheneve we insert, delete and search for a
node we splay the respective nodes to root. we have zig-zag and zig-zig operations.
advertisement
Answer: a
Explanation: Splay trees can be used for faster access to recently accessed items and hence used for cache
implementations.
7. When we have red-black trees and AVL trees that can perform most of operations in logarithmic times,
then what is the need for splay trees?
a) no there is no special usage
b) In real time it is estimated that 80% access is only to 20% data, hence most used ones must be easily
available
c) redblack and avl are not upto mark
d) they are just another type of self balancing binary search trees
Answer: b
Explanation: May be the stats showing 80-20% may be not accurate, but in real time that is the widely
spread scenario seen. If you are into this type of situation, you must choose implementing splay trees.
a) true
b) false
Answer: a
Explanation: There is a zig-zag and right operation(zig) which gives the right hand side tree. refer splay
operations for insertion in splay tree.
Tree_node function(Tree_node x)
{
Tree_node y = x.left;
x.left = y.right;
y.right = x;
return y;
}
Answer: a
Explanation: When a right rotation is done the parent of the rotating node becomes it’s right node and it’s
child becomes it’s left child.
Answer: a
Explanation: This will be the case after accessing all n elements in non-decreasing order. Since the height of
a tree correspo
Answer: a
Explanation: The average case and worst case space complexity of a treap is mathematically found to be
O(N).
Answer: b
Explanation: A treap is a combination of a tree and a heap. The structure of a treap is determined by the fact
that it is heap-ordered.
Answer: b
Explanation: A treap is the simplest of all binary search trees. Each node is given a numeric priority and
implementation is non recursive.
Answer: b
Explanation: A node’s priority should satisfy heap order. That is, any node’s priority should be at least as
large as its parent.
advertisement
6. Several other operations like union set difference and intersection can be done in treaps.
a) True
b) False
Answer: a
Explanation: Other than insertion, deletion and search operations, several operations like union, intersection
and set difference can be done in treaps.
Answer: c
Explanation: The average case and worst case analysis of a treap are mathematically found to be O(log N).
Answer: a
Explanation: A root node has the lowest priority in a treap since the node’s priority is based on heap order.
Answer: d
Explanation: The priority of a null node is set to be infinity in a treap so that during deletion, priority of that
particular node is set to infinity, rotated and freed.
10. Who invented treaps?
a) Cecilia and Raimund
b) Arne Andersson
c) Donald Shell
d) Harris and Ross
Answer: a
Explanation: Cecilia and Raimund invented Treaps. Arne Andersson invented AA – Trees. Donald Shell
invented s
Answer: d
Explanation: This type of tree traversal will not use stack or queue.
Answer: a
Explanation: As there are majority of pointers with null value going wasted we use threaded binary trees.
Answer: a
Explanation: It contains additional 2 pointers over normal binary tree node structure.
Answer: a
Explanation: If preorder or postorder is used then the respective predecessor and successor info is stored.
5. Which of the following tree traversals work if the null left pointer pointing to the predecessor and null
right pointer pointing to the successor in a binary tree?
a) inorder, postorder, preorder traversals
b) inorder
c) postorder
d) preorder
Answer: a
Explanation: In threaded binary trees, the null left pointer points to the predecessor and the right null pointer
point to the successor. In threaded binary trees, we can use in-order, preorder and postorder traversals to
visit every node in the tree.
advertisement
Answer: a
Explanation: They are properties of double and single threaded binary trees respectively.
7. What is wrong with below code for inorder traversal of inorder threaded binary tree:
inordertraversal(threadedtreenode root):
threadedtreenode q = inorderpredecessor(root)
while(q!=root):
q=inorderpredecessor(q)
print q.data
Answer: a
Explanation: Property of inorder threaded binary tree is left node with inorder predecessor and right node
with inorder successor information are stored.
Answer: a
Explanation: The nodes extreme left and right are pointing to nothing which could be also used efficiently.
1. Who developed the concept of tango tree?
a) Erik Demaine
b) Mihai Patrascu
c) John Lacono
d) All of the mentioned
Answer: d
Explanation: Erik Demaine is a well-known professor of Computer Science at MIT. John Lacono is an
American computer scientist specialized in data structure and algorithm while Mihai Patrascu was a
Romanian- American computer scientist. All of them together developed the concept of Tango tree.
Answer: c
Explanation: Tango tree is an example of binary search tree which was developed by four famous scientists
Erik Demaine, Mihai Patrascu, John Lacono and Harmon in the year 2004.
Answer: b
Explanation: Tango is a popular couple dance or partner dance that was originated in the 1880s somewhere
between Argentina and Uruguay. Buenos Aires is a capital city off Argentina. Hence they named after
Buenos Aires.
4. Which type of binary search tree or algorithm does tango tree use?
a) Online
b) Offline
c) Static
d) Dynamic
Answer: d
Explanation: Tango tree is an online binary search tree whose time complexity is O (log (log n)) when
compared to the time complexity of offline binary search tree model. Online algorithm processes input or
data provided piece by piece.
5. What is the time complexity of for achieving competitive ratio by tango tree?
a) O (log n)
b) O (n2)
c) O (n!)
d) O (log (log n))
Answer: d
Explanation: Tango tree is an online binary search tree whose time complexity is O (log (log n)) when
compared to the time complexity of offline binary search tree model. Online algorithm processes input or
data provided piece by piece.
advertisement
6. Which type of binary search tree is imitated for construction of tango tree?
a) Complete Binary Search Tree
b) Perfect Binary Search Tree
c) Balanced Binary Search Tree
d) Degenerate Binary Search Tree
Answer: a
Explanation: Tango tree is constructed by simulating a complete binary search tree. This tree is also known
as Reference tree, that contains all the elements of the tree. Also, the reference tree is never showed in actual
implementation.
7. Which special balanced binary search tree is used to store the nodes of auxiliary tree?
a) Red – Black Tree
b) Red – Brown Tree
c) Red – Yellow Tree
d) Red – Tango Tree
Answer: a
Explanation: The path starting from the root and following the path of preferred child node till the end of
leaf node is known as preferred path. Nodes are stored in Red – Black tree for the representation of the
preferred path.
Answer: a
Explanation: Partitioning method is used by tango tree which partitions a binary search tree into small sets
of paths and then storing them to auxiliary trees. Hence tango tree is represented as a tree of trees.
Answer: a
Explanation: If the top node of one of the reference tree amongst the two, is the is the child of the bottom
node of the other reference tree, then the join operation can be carried out to join the two auxiliary trees.
11. Which operation is used to break a preferred path into two sets of parts at a particular node?
a) Differentiate
b) Cut
c) Integrate
d) Join
Answer: b
Explanation: A preferred path is broken into two parts. One of them is known as top part while other is
known as bottom part. To break a preferred path into two sets, cut operation is used at a particular node.
12. What is the upper bound for a tango tree if k is a number of interleaves?
a) k+2 O (log (log n))
b) k O (log n)
c) K2 O (log n)
d) k+1 O (log (log n))
Answer: d
Explanation: Upper bound is found to analyze the work done by a tango tree on a given set of sequences. In
order to connect to the tango tree, the upper bound is found to be k+1 O (log (log n)).
13. What is the time complexity for searching k+1 auxiliary trees?
a) k+2 O (log (log n))
b) k+1 O (log n)
c) K+2 O (log n)
d) k+1 O (log (log n))
Answer: d
Explanation: Since each search operation in the auxiliary tree takes O (log (log n)) time as auxiliary tree size
is bounded by the height of the reference tree that is log n. So for k+1 auxiliary trees, total search time is
k+1 O (log (log n)).
14. What is the time complexity for the update cost on auxiliary trees?
a) O (log (log n))
b) k-1 O (log n)
c) K2 O (log n)
d) k+1 O (log (log n))
Answer: d
Explanation: The update cost also is bounded by the upper bound. We perform one cut as well as one join
operation for the auxiliary tree, so the total update cost for the auxiliary tree is found to be k+1 O (log (log
n)).
Answer: b
Explanation: Splay tree is a self – adjusting binary search tree. It performs basic operations on the tree like
insertion, dele
Answer: a
Explanation: Array is a linear data structure. Strings are a collection and sequence of codes, alphabets or
characters. Linked List is a linear data structure having a node containing data input and the address of the
next node. The cord is also known as the rope data structure.
Answer: d
Explanation: Rope is a special binary tree in which the end nodes contain the string and its length. The array
is a linear data structure. Linked List is a linear data structure having a node containing data input and the
address of the next node. The queue is a data structure working on the principle of FIFO.
3. What is the time complexity for finding the node at x position where n is the length of the rope?
a) O (log n)
b) O (n!)
c) O (n2)
d) O (1)
Answer: a
Explanation: In order to find the node at x position in a rope data structure where N is the length of the rope,
we start a recursive search from the root node. So the time complexity for worst case is found to be O (log
N).
4. What is the time complexity for creating a new node and then performing concatenation in the rope data
structure?
a) O (log n)
b) O (n!)
c) O (n2)
d) O (1)
Answer: d
Explanation: In order to perform the concatenation on the rope data structure, one can create two nodes S1
and S2 and then performing the operation in constant time that is the time complexity is O (1).
5. What is the time complexity for splitting the string into two new string in the rope data structure?
a) O (n2)
b) O (n!)
c) O (log n)
d) O (1)
Answer: c
Explanation: In order to perform the splitting on the rope data structure, one can split the given string into
two new string S1 and S2 in O (log n) time. So, the time complexity for worst case is O (log n).
advertisement
6. Which type of binary tree does rope require to perform basic operations?
a) Unbalanced
b) Balanced
c) Complete
d) Full
Answer: b
Explanation: To perform the basic operations on a rope data structure like insertion, deletion, concatenation
and splitting, the rope should be a balanced tree. After performing the operations one should again re-
balance the tree.
7. What is the time complexity for inserting the string and forming a new string in the rope data structure?
a) O (log n)
b) O (n!)
c) O (n2)
d) O (1)
Answer: a
Explanation: In order to perform the insertion on the rope data structure, one can insert the given string at
any position x to form a new string in O (log n) time. So, the time complexity for worst case is O (log n).
This can be done by one split operation and two concatenation operations.
Answer: a
Explanation: In order to perform the insertion on the rope data structure, the time complexity is O (log n). In
order to perform the deletion on the rope data structure, the time complexity for worst case is O (log n).
While for arrays the time complexity is O (n).
9. What is the time complexity for deleting the string to form a new string in the rope data structure?
a) O (n2)
b) O (n!)
c) O (log n)
d) O (1)
Answer: c
Explanation: In order to perform the deletion on the rope data structure, one can delete the given string at
any position x to form a new string in O (log n) time. So, the time complexity for worst case is O (log n).
This can be done by two split operations and one concatenation operation.
10. Is it possible to perform a split operation on a string in the rope if the split point is in the middle of the
string.
a) True
b) False
Answer: a
Explanation: In order to perform the splitting on the rope data structure, one can split the given string into
two new string S1 and S2 in O (log n) time. So, the time complexity for worst case is O (log n). The split
1. Which of the following is the most widely used external memory data structure?
a) AVL tree
b) B-tree
c) Red-black tree
d) Both AVL tree and Red-black tree
Answer: b
Explanation: In external memory, the data is transferred in form of blocks. These blocks have data valued
and pointers. And B-tree can hold both the data values and pointers. So B-tree is used as an external memory
data structure.
2. B-tree of order n is a order-n multiway tree in which each non-root node contains __________
a) at most (n – 1)/2 keys
b) exact (n – 1)/2 keys
c) at least 2n keys
d) at least (n – 1)/2 keys
Answer: d
Explanation: A non-root node in a B-tree of order n contains at least (n – 1)/2 keys. And contains a
maximum of (n – 1) keys and n sons.
Answer: a
Explanation: A B-tree of order m of height h will have the maximum number of keys when all nodes are
completely filled. So, the B-tree will have n = (mh+1 – 1) keys in this situation. So, required number of
maximum keys = 43+1 – 1 = 256 – 1 = 255.
4. Five node splitting operations occurred when an entry is inserted into a B-tree. Then how many nodes are
written?
a) 14
b) 7
c) 11
d) 5
Answer: c
Explanation: If s splits occur in a B-tree, 2s + 1 nodes are written (2 halves of each split and the parent of the
last node split). So, if 5 splits occurred, then 2 * 5 + 1, i.e. 11 nodes are written.
5. B-tree and AVL tree have the same worst case time complexity for insertion and deletion.
a) True
b) False
Answer: a
Explanation: Both the B-tree and the AVL tree have O(log n) as worst case time complexity for insertion
and deletion.
advertisement
6. 2-3-4 trees are B-trees of order 4. They are an isometric of _____ trees.
a) AVL
b) AA
c) 2-3
d) Red-Black
Answer: d
Explanation: 2-3-4 trees are isometric of Red-Black trees. It means that, for every 2-3-4 tree, there exists a
Red-Black tree with data elements in the same order.
7. Figure shown below is B-tree of order 5. What is the result of deleting 130 from the tree?
a)
b)
c)
d)
Answer: c
Explanation: Each non-root in a B-tree of order 5 must contain at least 2 keys. Here, when the key 130 is
deleted the node gets underflowed i.e. number of keys in the node drops below 2. So we combine the node
with key 110 with it’s brother node having keys 144 and 156. And this combined node will also contain the
separator key from parent i.e. key 140, leaving the root with two keys 110 and 160.
8. What is the best case height of a B-tree of order n and which has k keys?
a) logn (k+1) – 1
b) nk
c) logk (n+1) – 1
d) klogn
Answer: a
Explanation: B-tree of order n and with height k has best case height h, where h = logn (k+1) – 1. The best
case occurs when all the nodes are completely filled with keys.
9. Compression techniques can be used on the keys to reduce both space and time requirements in a B-tree.
a) True
b) False
Answer: a
Explanation: The front compression and the rear compression are techniques used to reduce space and time
requirements in B-tree. The compression enables to retain more keys in a node so that the number of nodes
needed can be reduced.
Answer: a
Explanation: The average probability of the split is 1/(⌈m / 2⌉ – 1), where m is the order of B-tree. So, if m
larger, the proba
1. In a B+ tree, both the internal nodes and the leaves have keys.
a) True
b) False
Answer: b
Explanation: In a B+ -tree, only the leaves have keys, and these keys are replicated in non-leaf nodes for
defining the path for locating individual records.
2. Which of the following is true?
a) B + tree allows only the rapid random access
b) B + tree allows only the rapid sequential access
c) B + tree allows rapid random access as well as rapid sequential access
d) B + tree allows rapid random access and slower sequential access
Answer: c
Explanation: The B+ -tree being a variation of B-tree allows rapid random access. In a B+ -tree the leaves
are linked together, so it also provides rapid sequential access.
3. A B+ tree can contain a maximum of 7 pointers in a node. What is the minimum number of keys in
leaves?
a) 6
b) 3
c) 4
d) 7
Answer: b
Explanation: Maximum number of pointers in a node is 7, i.e. the order of the B+ -tree is 7. In a B+ tree of
order n each leaf node contains at most n – 1 key and at least ⌈(n − 1)/2⌉ keys. Therefore, a minimum
number of keys each leaf can have = ⌈(7 – 1)/2⌉ = 3.
Answer: a
Explanation: A B+ -tree always grows upwards. And In a B+tree – i)The path from the root to every leaf
node is of the same length, so the tree is balanced. ii) Leaves are linked, so allow sequential searching. iii)
An index is built with a single key per block of data rather than with one key per data record, so it is
shallower than B-tree.
5. A B+ -tree of order 3 is generated by inserting 89, 9 and 8. The generated B+ -tree is __________
a)
b)
c)
d)
Answer: b
Explanation:
advertisement
6. Statement 1: When a node is split during insertion, the middle key is promoted to the parent as well as
retained in right half-node.
Statement 2: When a key is deleted from the leaf, it is also deleted from the non-leaf nodes of the tree.
a) Statement 1 is true but statement 2 is false
b) Statement 2 is true but statement 1 is false
c) Both the statements are true
d) Both the statements are false
Answer: a
Explanation: During the split, the middle key is retained in the right half node and also promoted to parent
node. When a key is deleted from the leaf, it is retained in non-leaves, because it can be still a valid
separator between keys in nodes below.
Answer: d
Explanation: In a B+ -tree finding the next recored (successor) involves accessing an additional leaf at most.
So, the efficiency of finding the next record is O(1).
8. What is the maximum number of keys that a B+ -tree of order 3 and of height 3 have?
a) 3
b) 80
c) 27
d) 26
Answer: d
Explanation: A B+ tree of order n and height h can have at most nh – 1 keys. Therefore maximum number of
keys = 33 -1 = 27 -1 = 26.
Answer: c
Explanation: A B+ -tree has larger fanout and therefore have a depth smaller than that of corresponding B-
tree.
10. Which one of the following data structures are preferred in database-system implementation?
a) AVL tree
b) B-tree
c) B+ -tree
d) Splay tree
Answer: c
Explanation: The
Answer: a
Explanation: The 2-3 trees is a balanced tree. It is a specific form the B – tree. It is B – tree of order 3, where
every node can have two child subtrees and one key or 3 child subtrees and two keys.
2. Which of the following is the 2-3 tree?
a)
b)
c)
d)
Answer: c
Explanation: Tree should have two subtrees at node2, but it should not have three elements. The node with
elements 11 and 15 should have three child subtrees.
Answer: d
Explanation: The number of elements in a 2-3 tree with height h is between 2h – 1 and 3h – 1. Therefore, the
2-3 tree with n elements will have the height between log3(n + 1) and log2(n + 1).
4. Which of the following the BST is isometric with the 2-3 tree?
a) Splay tree
b) AA tree
c) Heap
d) Red – Black tree
Answer: b
Explanation: AA tree is isometric of the 2-3 trees. In an AA tree, we store each node a level, which is the
height of the corresponding 2-3 tree node. So, we can convert a 2-3 tree to an AA tree.
5. The figure shown below is a 2-3 tree. What is the result of deleting 110 from the tree?
a)
b)
c)
d)
Answer: c
Explanation: When 110 is deleted the respective node becomes empty, so the 2-3 tree properties get
violated. Hence, the element from its sibling node, 93 is moved to the root and root node element 100 is fed
to the empty node. So, the resultant 2-3 tree will be,
advertisement
6. Which of the following data structure can provide efficient searching of the elements?
a) unordered lists
b) binary search tree
c) treap
d) 2-3 tree
Answer: d
Explanation: The average case time for lookup in a binary search tree, treap and 2-3 tree is O(log n) and in
unordered lists it is O(n). But in the worst case, only the 2-3 trees perform lookup efficiently as it takes
O(log n), while others take O(n).
Answer: a
Explanation: LLRB (Left Leaning Red Black tree)is the data structure which is used to implement the 2-3
tree with very basic code. The LLRB is like the 2-3 tree where each node has one key and two links. In
LLRB the 3-node is implemented as two 2-nodes connected by the red link that leans left. Thus, LLRB
maintains 1-1 correspondence with 2–3 tree.
Answer: c
Explanation: In a 2-3 tree, leaves are at the same level. And 2-3 trees are perfectly balanced as every path
from root node to the null link is of equal length. In 2-3 tree in-order traversal yields elements in sorted
order.
Answer: b
Explanation: Insertion in AVL tree and 2-3 tree requires searching for proper position for insertion and
transformations for balancing the tree. In both, the trees searching takes O(log n) time, but rebalancing in
AVL tree takes O(log n), while the 2-3 tree takes O(1). So, 2-3 tree provides better insertions.
Answer: a
Explanation: Search is more efficient in the 2-3 tree than in BST. 2-3 tree is a balanced tree and performs
efficient insertion and deletion and it is shallower than BST. But, 2-3 tree requires more storage than the
BST.
1. How many child nodes does each node of Ternary Tree contain?
a) 4
b) 6
c) 5
d) 3
Answer: d
Explanation: Each node of Ternary tree contains at most 3 nodes. So Ternary tree can have 1, 2 or 3 child
nodes but not more than that.
2. Which of the following is the name of the node having child nodes?
a) Brother
b) Sister
c) Mother
d) Parent
Answer: d
Explanation: Parent node is the node having child nodes and child nodes may contain references to their
parents. Parent node is a node connected by a directed edge to its child.
Answer: c
Explanation: Depth is defined as the length of the path from root to the node. So the depth of root node in
ternary tree is 0.
Answer: d
Explanation: Height of ternary tree is defined as the length of path from root to deepest node in tree.
Therefore, height off root node in ternary tree is 0.
5. Which node is the root node of the following ternary tree?
a) A
b) B
c) C
d) D
Answer: a
Explanation: Node A is called the root node of the above ternary tree while the Node B, Node C, Node D are
called Leaf node.
advertisement
a) A
b) B
c) D
d) G
Answer: d
Explanation: Leaf node is any node that does not contain any children. Since Node G is the node without
any children, So G is called Leaf Node. While Node A is root node and Node B, Node C, Node D is parent
node of their children.
a) 1
b) 5
c) 2
d) 3
Answer: c
Explanation: Since Node 2 has two children Node 5 and Node 6, So Node 2 is the parent node of Node 6.
While Node 1 is root node and Node 3 and Node 5 are Leaf node.
8. Is parent node of Node 3 and root node of the given ternary tree same?
a) True
b) False
Answer: a
Explanation: Since Root node of the ternary tree is Node 1 and also Node 1 has three children that is Node 2,
Node 3, Node 4. So parent node of Node 3 and the root node of the ternary tree are same.
9. Which node is the child node of Node D in the following ternary tree?
a) A
b) C
c) G
d) H
Answer: d
Explanation: The Child node is the node that has a directed path from its parent node. Since Node D has a
direct path to Node H, So Node H is the Child node.
10. Which node is the child node of the Node D in the following ternary tree?
a) A
b) C
c) B
d) No child node
Answer: d
Explanation: Since Node D is the Leaf node of the above ternary tree and leaf node has no child node. So
there is no child node for Node D in the above ternary tree.
a) 0
b) 1
c) 2
d) 3
Answer: c
Explanation: Depth of the node is the length of the path from root to the node. Here, length of path from root
to Node G is 2. So depth of Node G is 2.
a) 0
b) 1
c) 2
d) 3
Answer: c
Explanation: Height of the tree is defined as the length of the path from root node to the deepest node of the
tree. Here deepest nodes are 5,6,7 which are at length 2. So the height of the ternary tree is 2.
13. Which nodes are the siblings of Node B of given ternary tree?
a) E
b) C
c) F
d) Both E and F
Answer: d
Explanation: Siblings are the nodes that share same parent. Since both the Node E and Node F have same
parent Node B, So the sibling of
1. How many extra nodes are there in Full ternary tree than a complete ternary tree?
a) 1
b) 2
c) 3
d) Both have same number of nodes
Answer: d
Explanation: Every Full ternary tree is also a complete ternary tree. Therefore, both have same number of
nodes.
a) True
b) False
Answer: b
Explanation: Node B, Node C are the siblings of Node D while Node A is the parent node of Node D.
a) 3
b) 2
c) 6
d) 4
Answer: c
Explanation: Size of the ternary tree is defined as the total number of nodes present in the tree. Since there
are total of 6 nodes in the ternary tree. So the size of the ternary tree is 6.
4. Who is the ancestor of Node G?
a) C
b) F
c) H
d) A
Answer: a
Explanation: Ancestor node is a node that comes in between the path from the node to the root. Since Node
C comes between node G and root, so Node C is called the ancestor node.
advertisement
a) A
b) E
c) F
d) Both E and F
Answer: d
Explanation: Descendant node is a node which has a direct path from ancestor node. Since both E and F are
connected to B, so Node E and Node F are the descendants of Node B.
a) 1
b) 2
c) 3
d) 4
Answer: d
Explanation: Size of node is defined as the total number of descendants of that node including itself. So, size
of Node A is 4.
7. Can leaf node be called child node in a ternary tree?
a) True
b) False
Answer: a
Explanation: Leaf node is a node that has no child. Since Leaf node will always be the node on the last level
of ternary tree, so it can be called child node of given parent node in ternary tree.
8. Can child node be always called Leaf node in the ternary tree?
a) True
b) False
Answer: b
Explanation: Leaf node is any node that does not contain any children. Child node may or may not contain
more nodes. Child node will only be called leaf Node if the node has no child node.
Answer: b
Explanation: Ternary tree is used to implement ternary search tree and ternary heap. While AVL Tree, hash
Table, dictionary are different types of Data Structures.
1. How many child nodes does each node of K-ary Tree contain?
a) 2
b) 3
c) more than k
d) at most k
Answer: d
Explanation: Each node of K-ary tree contains at most k nodes. While tree with 2 nodes is called Binary tree
and tree with 3 nodes is called Ternary tree.
2. Which of the following is the name of the node having child nodes?
a) Brother
b) Sister
c) Mother
d) Parent
Answer: d
Explanation: Parent node is the node having child nodes and child nodes may contain references to their
parents. Parent node is a node connected by a directed edge to its child.
Answer: c
Explanation: Depth is defined as the length of the path from root to the node. So the depth of root node in K-
ary tree is 0.
Answer: d
Explanation: Height of K-ary tree is defined as the length of path from root to deepest node in tree.
Therefore, height of root node in K-ary tree is 0.
a) A
b) B
c) C
d) D
Answer: a
Explanation: Node A is called the root node of the above K-ary tree while the Node B, Node C, Node D are
called Leaf node.
advertisement
a) A
b) B
c) D
d) F
Answer: d
Explanation: Leaf node is any node that does not contain any children. Since Node F is the node without any
children, So F is called Leaf Node. While Node A is root node and Node B, Node C, Node D is parent node
of their children.
7. Which node is the parent node of Node 5?
a) 1
b) 5
c) 2
d) 3
Answer: c
Explanation: Since Node 2 has two children Node 5 and Node 6, So Node 2 is the parent node of Node 5.
While Node 1 is root node and Node 3 and Node 5 are Leaf node.
8. Is parent node of Node 4 and root node of the given K-ary tree same?
a) True
b) False
Answer: a
Explanation: Since Root node of the ternary tree is Node 1 and also Node 1 has three children that is Node 2,
Node 3, Node 4. So parent node of Node 4 and the root node of the ternary tree are same.
9. Which node is the child node of Node C in the following K-ary tree?
a) A
b) C
c) G
d) H
Answer: c
Explanation: The Child node is the node that has a directed path from its parent node. Since Node C has a
direct path to Node G, So Node G is the Child node.
10. Which node is the child node of the Node B in the following K-ary tree?
a) A
b) C
c) B
d) No child node
Answer: d
Explanation: Since Node B is the Leaf node of the above ternary tree and leaf node has no child node. So
there is no child node for Node B in the above K-ary tree.
a) 0
b) 1
c) 2
d) 3
Answer: c
Explanation: Depth of the node is the length of the path from root to the node. Here, length of path from root
to Node F is 2. So depth of Node F is 2.
a) 0
b) 1
c) 2
d) 3
Answer: c
Explanation: Height of the tree is defined as the length of the path from root node to the deepest node of the
tree. Here deepest nodes are 5,6,7 which are at length 2. So the height of the K-ary tree is 2.
a) 3
b) 2
c) 6
d) 4
Answer: c
Explanation: Size of the K-ary tree is defined as the total number of nodes present in the tree. Since there are
total of 6 nodes in the K-ary tree. So the size of the K-ary tree is 6.
a) D
b) F
c) H
d) A
Answer: a
Explanation: Ancestor node is a node that comes in between the path from the node to the root. Since Node
D comes between node H and root, so Node D is called the ancestor node.
Answer: d
Explanation: Descendant node is a node which has a direct path from ancestor node. Since Node G is
connected to C, so Node G is the descendant of Node C.
a) 1
b) 2
c) 3
d) 4
Answer: a
Explanation: Size of node is defined as the total number of descendants of that node including itself. So, size
of Node B is 1.
Answer: a
Explanation: Leaf node is a node that has no child. Since Leaf node will always be the node on the last level
of k-ary tree, so it can be called child node of given parent node in K-ary tree.
advertisement
6. Can child node be always called Leaf node in the K-ary tree?
a) True
b) False
Answer: b
Explanation: Leaf node is any node that does not contain any children. Child node may or may not contain
more nodes. Child node will only be called leaf Node if the node has no child node.
7. What is the upper bound for maximum leaves in K-ary tree with height h?
a) K*h
b) K^h
c) K+h
d) K-h
Answer: b
Explanation: In the K-ary tree having height h, the upper bound for having maximum number of leaves is
k^h.
Answer: b
Explanation: Height of a K-ary tree does not include the root node. So the height of the K-ary tree is without
root node is 0.
9. Which one of the following is the correct formulae to find the parent node at index I?
a) (I-1)/K
b) (I+1)/K
c) (I*1)/K
d) (I-2)/K
Answer: a
Explanation: The parent node for the node of index I in a K-ary tree is given by (I-1)/K.
10. Which nodes are the siblings of Node D of given ternary tree?
a) E
b) C
c) F
d) H
Answer: d
Explanation: Siblings are the nodes that share same parent. Since both the Node H is parent Node D, So the
sibling of Node D is Node H.
11. How many extra nodes are there in Full K-ary tree than complete K-ary tree?
a) 1
b) 2
c) 3
d) Both have same number of nodes
Answer: d
Explanation: Every Full K-ary tree is also a complete K-ary tree. Therefore, both have same number of
nodes.
12. Is Node A sibling of Node B in the given K-ary tree?
a) True
b) False
Answer: b
Explanation: Node D, Node C are the siblings of Node B while Node A is the parent node of Node B
1. What is the other name or Van Emde Boas Tree data structure?
a) Van Emde Boas Array
b) Van Emde Boas Stack
c) Van Emde Boas Priority Queue
d) Van Emde Boas Heap
Answer: c
Explanation: The Van Emde Boas Tree data structure is also popularly known as Van Emde Boas Priority
Queue. This data structure implements the array associatively for the given integer keys. It was formulated
by Peter Van Emde Boas.
2. Who Invented The vEB also known as Van Emde Boas Tree?
a) Peter Van Emde Boas
b) Samuel F. B. Morse
c) Friedrich Clemens Gerke
d) Alexander Morse
Answer: d
Explanation: The Van Emde Boas Tree data structure is also popularly known as Van Emde Boas Priority
Queue. This data structure implements the array associatively for the given integer keys. It was formulated
by Peter Van Emde Boas.
3. What is the time complexity for storing the maximum number of elements in Van Emde Boas tree if M is
the maximum number of elements?
a) O (log M)
b) O (M!)
c) O (M)
d) O (1)
Answer: c
Explanation: In order to store the maximum number of elements in Van Emde Boas data structure where M
is the maximum number of elements, the tree has great efficiency for storing them. So the time complexity
for worst case is found to be O (M).
4. Does Van Emde Boas data structure perform all operation in O (log (log M)) time where M = 2m.
a) True
b) False
Answer: a
Explanation: All the operations performed on the Van Emde Boas tree with an associative array like
Insertion, Deletion, Searching and many more can be performed in O (log (log M)) time where M = 2m.
5. What is the time complexity for searching a key or integer in Van Emde Boas data structure?
a) O (log M!)
b) O (M!)
c) O (M2)
d) O (log (log M))
Answer: d
Explanation: In order to search a key or integer in the Van Emde Boas data structure, the operation can be
performed on an associative array. Hence, the time complexity for searching a key or integer in Van Emde
Boas data structure is O (log (log M)).
advertisement
6. Which type of tree does Van Emde Boas require to perform basic operations?
a) Unbalanced
b) Balanced
c) Complete
d) Non – Binary
Answer: d
Explanation: The Van Emde Boas Tree data structure is also popularly known as Van Emde Boas Priority
Queue. This data structure implements the array associatively for the given integer keys. It was formulated
by Peter Van Emde Boas. It is a non – binary type of tree.
7. What is the time complexity for inserting a key or integer in Van Emde Boas data structure?
a) O (log M!)
b) O (M!)
c) O (M2)
d) O (log (log M))
Answer: a
Explanation: In order to insert a key or integer in the Van Emde Boas data structure, the operation can be
performed on an associative array. Hence, the time complexity for inserting a key or integer in Van Emde
Boas data structure is O (log (log M)).
Answer: d
Explanation: The Van Emde Boas Tree data structure is also popularly known as Van Emde Boas Priority
Queue. This data structure implements the array associatively for the given integer keys. It was formulated
by Peter Van Emde Boas in 1975.
9. What is the time complexity for deleting a key or integer in Van Emde Boas data structure?
a) O (log M!)
b) O (log (log M))
c) O (M!)
d) O (M2)
Answer: b
Explanation: In order to delete a key or integer in the Van Emde Boas data structure, the operation can be
performed on an associative array. Hence, the time complexity for deleting a key or integer in Van Emde
Boas data structure is O (log (log M)).
10. Can operation like Find Next and Find Previous be implemented.
a) True
b) False
Answer: a
Explanation: Since the Van Emde Boas data structure follows an associative array abstract data type to
perform different operations. Hence, an operation like Find Next and Find Previous be implemented.
11. What is the time complexity for finding a maximum and minimum integer in Van Emde Boas data
structure?
a) O (log M!)
b) O (M!)
c) O (1)
d) O (log (log M))
Answer: c
Explanation: In order to find a maximum or minimum integer in the Van Emde Boas data structure, the
operation can be performed on an associative array. Hence, the time complexity for finding a maximum or
minimum integer in Van Emde Boas data structure is O (1).
12. On which abstract data type does van Emde Boas tree performs the operation?
a) Tree
b) Linked List
c) Heap
d) Associative Array
Answer: d
Explanation: The Van Emde Boas Tree data structure is also popularly known as Van Emde Boas Priority
Queue. This data structure implements an abstract data type called associative array for the given integer
keys.
13. Which operation find the value associated with a given key?
a) Insert
b) Find Next
c) Look up
d) Delete
Answer: b
Explanation: This data structure implements an abstract data type called associative array for the given
integer keys. Hence, to find the value associated with a given key, Look Up operation is performed.
Answer: c
Explanation: An equivalent relationship will satisfy three properties – reflexive, symmetric and transitive.
Answer: b
Explanation: A symmetric property in an equivalence relation is defined as x R y if and only y R x.
Answer: a
Explanation: Electrical connectivity is reflexive, symmetric and also transitive. Hence, electrical
connectivity is an equivalence relation.
Answer: d
Explanation: The worst case efficiency for a path compression algorithm is mathematically found to be O(M
log N).
Answer: c
Explanation: Path compression algorithm is performed during find operation and is independent of the
strategy used to perform unions.
advertisement
6. What is the definition for Ackermann’s function?
a) A(1,i) = i+1 for i>=1
b) A(i,j) = i+j for i>=j
c) A(i,j) = i+j for i = j
d) A(1,i) = i+1 for i<1
Answer: a
Explanation: The Ackermann’s function is defined as A(1,i) = i+1 for i>=1. This form in text grows faster
and the inverse is slower.
7. ___________ is one of the earliest forms of a self-adjustment strategy used in splay trees, skew heaps.
a) Union by rank
b) Equivalence function
c) Dynamic function
d) Path compression
Answer: d
Explanation: Path compression is one of the earliest forms of self-adjustment used in extremely important
strategies using theoretical explanations.
8. What is the depth of any tree if the union operation is performed by height?
a) O(N)
b) O(log N)
c) O(N log N)
d) O(M log N)
Answer: b
Explanation: If the Unions are performed by height, the depth of any tree is calculated to be O(log N).
9. When executing a sequence of Unions, a node of rank r must have at least 2r descendants.
a) true
b) false
Answer: a
Explanation: By the induction hypothesis, each tree has at least 2r – 1 descendants, giving a total of 2r and
establishing the lemma.
Answer: c
Explanation: Each node of a rank r is the root of a subtree of at least 2r. Therefore, there are at most N/2r
disjoint subtrees.
11. What is the worst-case running time of unions done by size and path compression?
a) O(N)
b) O(logN)
c) O(N logN)
d) O(M logN)
Answer: d
Explanation: The worst case running time of a union operation done by size and path compression is
mathematically found to be O(M logN).
12. In the Union/Find algorithm, the ranks of the nodes on a path will increase monotonically from?
a) leaf to root
b) root to node
c) root to leaf
d) left subtree to right subtree
Answer: a
Explanation: One of the lemmas state that, in the Union/Find algorithm, the ranks of the nodes on a path will
increase monotonically from leaf to root.
13. How many strategies are followed to solve a dynamic equivalence problem?
a) 1
b) 2
c) 3
d) 4
Answer: b
Explanation: There are two strategies involved to solve a dynamic equivalence problem- executing find
instruction in worst-case time and executing union instruction in worst-case time.
14. What is the total time spent for N-1 merges in a dynamic equivalence problem?
a) O(N)
b) O(log N)
c) O(N log N)
d) O(M log N)
Answer: c
Explanation: The total time spent for N-1 merges in a dynamic equivalence problem is mathematically
found to be O(N log N).
15. What is the condition for an equivalence relation if two cities are related within a country?
a) the two cities should have a one-way connection
b) the two cities should have a two-way connection
c) the two cities should be in different countries
d) no equivalence relation will exist between two cities
Answer: b
Explanation: If th
Answer: c
Explanation: Bin data structure allows us to have efficient region queries. A frequency of bin is increased by
one each time a data point falls into a bin.
Answer: a
Explanation: Bin is an example of a range query data structure. It is because it efficiently answers any
number of queries on any subset of the input.
3. What is the worst case time complexity of query operation(n is the no. of candidates)?
a) O(1)
b) O(n)
c) O(log n)
d) O(n log n)
Answer: b
Explanation: The worst case in a bin query occurs when all the candidates are concentrated in one bin. So in
this case the time complexity is O(n).
4. What is the worst case time complexity of delete operation(n is the no. of candidates)?
a) O(1)
b) O(n)
c) O(log n)
d) O(n log n)
Answer: b
Explanation: The worst case in a bin delete operation occurs when all the candidates are concentrated in one
bin. So in this case the time complexity is O(n).
5. What is the worst case time complexity of insertion operation(n =no. of candidates)?
a) O(1)
b) O(n)
c) O(log n)
d) O(n log n)
Answer: a
Explanation: The worst case in a bin insert operation occurs when all the candidates are concentrated in one
bin. So in this case the time complexity is O(1).
advertisement
7. What will be the time complexity of query operation if all the candidates are evenly spaced so that each
bin has constant no. of candidates? (k = number of bins query rectangle intersects)
a) O(1)
b) O(k)
c) O(k2)
d) O(log k)
Answer: b
Explanation: The process of query becomes faster in a case when the number of candidates are equally
distributed among the bins. In such a case the query operation becomes O(k).
8. What will be the time complexity of delete operation if all the candidates are evenly spaced so that each
bin has constant no. of candidates? (m = number of bins intersecting candidate intersects)
a) O(1)
b) O(m)
c) O(m2)
d) O(log m)
Answer: b
Explanation: The process of deletion becomes faster in a case when the number of candidates are equally
distributed among the bins. In such a case the query operation becomes O(m). It is practically slower than
insertion in this case.
9. What will be the time complexity of insertion operation if all the candidates are evenly spaced so that
each bin has constant no. of candidates? (m = number of bins intersecting candidate intersects)
a) O(1)
b) O(m)
c) O(m2)
d) O(log m)
Answer: b
Explanation: The process of insertion becomes faster in the case when the number of candidates are equally
distributed among the bins. In such a case the query operation becomes O(m). It is practically faster than
deletion in this case.
Answer: c
Explanation: Efficiency of bin depends upon the location and size of query and candidates. It is similar to
that of a hash table.
11. Bigger the query rectangle the better is the query efficiency.
a) true
b) false
Answer: b
Explanation: Efficiency of bin depends upon the location and size of query and candidates. Also, the smaller
is the query rectan
Answer: b
Explanation: A perfectly balanced 2-d tree can be constructed in O(N log N) time. This value is computed
mathematically.
2. Insertion into a 2-d tree is a trivial extension of insertion into a binary search tree.
a) true
b) false
Answer: a
Explanation: Insertion of elements in a 2-d tree is similar to that of a binary search tree. Hence, it is a trivial
extension of the binary search tree.
Answer: b
Explanation: In a two- dimensional k-d tree (i.e.) 2-d tree, the root is arbitrarily chosen to be an odd level
and it applies to all 2-d trees.
4. Which of the following is the simplest data structure that supports range searching?
a) Heaps
b) binary search trees
c) AA-trees
d) K-d trees
Answer: d
Explanation: K-d trees are the simplest data structure that supports range searching and also it achieves the
respectable running time.
6. What will be the correct sequence of insertion for the following k-d tree?
a) (30,40),(5,25),(70,70),(10,12),(50,30),(35,45)
b) (40,30),(5,25),(12,10),(70,70),(30,50),(45,35)
c) (30,40),(5,25),(10,12),(70,70),(50,30),(35,45)
d) (40,30),(25,5),(12,10),(70,70),(50,30),(45,35)
Answer: c
Explanation: The correct sequence of insertion of the above given tree is (30,40),(5,25),(10,12),(70,70),
(50,30),(35,45). The insertion is given by, first left, then right.
Answer: b
Explanation: Each level in a k-d tree is made of dimensions and cutting. Cutting and dimensions are used for
insertion, deletion and searching purposes.
Answer: a
Explanation: The worst case analysis of finding the nearest neighbour in a k-d tree is mathematically found
to be O(N).
9. What is the run time of finding the nearest neighbour in a k-d tree?
a) O(2+ log N)
b) O( log N)
c) O(2d log N)
d) O( N log N)
Answer: c
Explanation: The run time of finding the nearest neighbour in a kd tree is given as O(2d log N) where 2d is
the time taken to search the neighbourhood.
10. How many prime concepts are available in nearest neighbour search in a kd tree?
a) 1
b) 2
c) 3
d) 4
Answer: c
Explanation: Three important concepts are available in finding the nearest neighbour. They are partial
results, pruning, traversal order.
Answer: a
Explanation: Pruning is eliminating irrelevant trees. Partial results are keeping best results and updating.
Traversal is visiting all the nodes of a tree.
Answer: b
Explanation: Several range queries are possible on a k-d tree. One of the range queries is known as a partial
match query.
13. What is the time taken for a range query for a perfectly balanced tree?
a) O(N)
b) O(log N)
c) O(√N+M)
d) O(√N)
Answer: c
Explanation: For a perfectly balanced k-d tree, the range query could take O(√N+M) in the worst case to
report M matches.
14. The 2d search tree has the simple property that branching on odd levels is done with respect to the first
key.
a) True
b) False
Answer: a
Explanation: Branching on odd levels is done with respect to the first key and branching on even levels is
done with respect to the second key in a 2-d tree.
Answer: b
Explanation: Jon Bentley found k-d trees. Rudolf Bayer found red black trees. Arne Andersson found AA-
trees.
Answer: b
Explanation: The leaves of an expression tree always contain the result of a given expression (i.e.) operands.
Answer: a
Explanation: It is possible for a node to have at least one child, as is the case with the unary minus operator.
Answer: b
Explanation: The nodes other than leaves always contain only operators. There cannot be any operand in
those nodes.
Answer: c
Explanation: The expression tree is a binary tree. It contains operands at leaf nodes and remaining nodes are
filled with operators. The operands and the operators can be arranged in any order (ascending, descending).
5. The expression obtained by recursively producing a left expression, followed by an operator, followed by
recursively producing a right expression is called?
a) prefix expression
b) infix expression
c) postfix expression
d) paranthesized expression
Answer: b
Explanation: It is an infix expression because the format of an infix expression is given by operand-operator-
operand.
advertisement
Answer: d
Explanation: The average depth of a binary expression tree is mathematically found to be O(√N).
Answer: b
Explanation: All infix, prefix and postfix expressions can be made into an expression tree using appropriate
algorithms.
Answer: a
Explanation: A postfix expression is converted into an expression tree by reading one symbol at a time and
constructing a tree respectively.
9. ++a*bc*+defg is an?
a) postfix expression
b) infix expression
c) prefix expression
d) invalid expression
Answer: c
Explanation: It is a prefix expression obtained from a preorder traversal since it is of the form operator-
operand-operand.
Answer: d
Explanation: In Binary trees, nodes are created by calling malloc and they are deleted by calling free.
11. What is the postfix expression for the following expression tree?
a) abcde++**
b) ab+cde+**
c) abc+de+**
d) abcd+*e+*
Answer: b
Explanation: If the given expression tree is evaluated, the postfix expression ab+cde+** is obtained.
Answer: a
Explanation: When an operand is encountered, create one node trees and push it on to the stack. When an
operator is encountered
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
Answer: c
Explanation: This is one of the property of max-heap that root node must have key greater than its children.
2. Heap exhibits the property of a binary tree?
a) True
b) False
Answer: a
Explanation: Yes, because the leaf nodes are present at height h or h-1, which is a property of complete
binary tree.
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)
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
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
100 with node of value 2. And thus 2 becomes root. And it will remain to be at root after all the possible
operations. So the value at root will be 2.
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
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)
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 ele
Answer: b
Explanation: The space complexity of searching an element in heap is O (n). Heap consists of n elements
and we need to compare every element. Here no addition or deletion of elements takes place. Hence space
complexity is O (n).
2. What is the best case complexity in building a heap?
a) O(nlogn)
b) O(n2)
c) O(n*longn *logn)
d) O(n)
Answer: d
Explanation: The best case complexity occurs in bottom-up construction when we have a sortes array given.
3. Given the code, choose the correct option that is consistent with the code. (Here A is the heap)
build(A,i)
left-> 2*i
right->2*i +1
temp- > i
if(left<= heap_length[A] ans A[left] >A[temp])
temp -> left
if (right = heap_length[A] and A[right] > A[temp])
temp->right
if temp!= i
swap(A[i],A[temp])
build(A,temp)
Answer: a
Explanation: Since in every condition we are comparing the current value is less than the parent of that
node. So this is build function of Max heap.
advertisement
Answer: c
Explanation: For any node child nodes are located at either 2*i, 2*i +1 So the parent node could be found by
taking the floor of the half of child node.
a) o(n)
b) O(logn)
c) O(1)
d) O(n logn)
Answer: c
Explanation: Deletion in a min-heap is in O(1) time.
6. Given an array of element 5, 7, 9, 1, 3, 10, 8, 4. Which of the following are the correct sequences of
elements after inserting all the elements in a min-heap?
a) 1,3,4,5,7,8,9,10
b) 1,4,3,9,8,5,7,10
c) 1,3,4,5,8,7,9,10
d) 1,3,7,4,8,5,9,10
Answer: a
Explanation: Building a min-heap the result will a sorted array so the 1, 3, 4, 5, 7, 8, 9, 10 is correct. If we
change the implementation strategy 1, 4, 3, 8, 9, 5, 7, 10 is also correct. (First filling the right child rather
than left child first).
7. For construction of a binary heap with property that parent node has value less than child node. In
reference to that which line is incorrect. Line indexed from 1.
1. add(int k)
2. {
3. heap_size++;
4. int i = heap_size - 1;
5. harr[i] = k;
6. while (i != 0 && harr[parent(i)] < harr[i])
7. {
8. swap(&harr[i], &harr[parent(i)]);
9. i = parent(i);
10. }
11. }
a) Line – 3
b) Line – 5
c) Line – 6
d) Line – 7
Answer: c
Explanation: The condition under while condition is wrong for a (min) binary heap The correct condition
should be while(i!=0 && harr[parent(i)] > harr[i]). Otherwise the constructed heap will be a max-binary
heap.
Answer: b
Explanation: This is the property of a weak heap.
2. Left child of parent node has value lesser than the parent node.
a) True
b) False
Answer: b
Explanation: Weak heap has no left child.
Answer: c
Explanation: Relaxed heap is just another name of weak heap.
4. What is the worst case time in searching minimum value in weak -heap?
a) O(log n)
b) O(n)
c) O(n logn)
d) O(1)
Answer: d
Explanation: Weak heap is an array based form that supports the operation of finding a minimum in O(1).
5. The total comparisons in finding both smallest and largest elements are
a) 2*n +2
b) n + ((n+1)/2) -2
c) n+logn
d) n2
Answer: b
Explanation: The total comparisons in finding smallest and largest elements is n + ((n+1)/2) – 2.
advertisement
insert(int n)
{
if(buffer_size()< maxi_biffer_size())
buffer_aar[ind]==n;
else
move_to_heap(buffer,buffer+maxi_buffer_size())
}
a) O(logn)
b) amortized O(1)
c) O(n)
d) O (n*logn)
Answer: b
Explanation: Use a buffer array to store a fixed number of elements when the buffer is full the content of
buffer is moved to heap.As a result the complexity
is amotized O(1).
7. Does there exist a heap with seven distinct elements so that the Inorder traversal gives the element in
sorted order.
a) Yes
b) No
Answer: b
Explanation: No, The inorder traversal will not give elements in sorted order. As heap is implemented as
either min-heap or max-heap, the root will be have highest or lowest value than remaining values of the
nodes. So this traversal will not give a sorted list.
Answer: c
Explanation: A complete binary tree is also a heap so by the property of binary tree the leaf nodes will be
must at height h o
1. The main distinguishable characterstic of a binomial heap from a binary heap is that
a) it allows union operations very efficiently
b) it does not allow union operations that could easily be implemented in binary heap
c) the heap structure is not similar to complete binary tree
d) the location of child node is not fixed i.e child nodes could be at level (h-2) or (h-3), where h is height of
heap and h>4
Answer: a
Explanation: The main use of binomial heap is to unify two different heap efficiently.
Answer: a
Explanation: At each depth there is a binomial tree in a binomial heap.
3. In a binomial heap the root value is greater than left child and less than right child.
a) True
b) False
Answer: b
Explanation: Binomial tree used in making binomial heap follows min heap property.
4. Given the pseudo code, state whether the function for merging of two heap is correct or not?
mergeTree(p,q)
if p.root.value <= q.root.value
return p.addTree(q)
else
return q.addTree(p)
a) True
b) False
Answer: a
Explanation: Binomial heap has a property that root value is less than both the child node’s value. So the
given function of merging two different heap is correct.
advertisement
Answer: b
Explanation: This could be easily verified by looking at the structure of a binomial heap.
Answer: c
Explanation: Decreasing a node value may result in violating the min property. As a result be there would be
exchange in the value of parent and child which at max goes up to height of the heap.
int myfun(heap_arr[])
{
int mini=INF;
for(int i=0;i<tot_node;i++)
mini=min(mini,heap_arr)
return mini;
}
Answer: c
Explanation: The function return minimum value in the heap_Array which is equal to the root value of the
heap.
Answer: c
Explanation: With proper implementation using link list find_min and find_max operation can be done in
O(1), while the remaining takes O(logn) time.
9. The Statement “Fibonacci heap has better amortized running time in compare to a binomial heap”.
a) True
b) False
Answer: a
Explanation: Overall complexity of insertion, merging, deleting is in order of O((a+b)logn) For Fibonacci
the complexity reduces to O(a+ blogn).
10. Given a heap of n nodes.The maximum number of tree for building the heap is.
a) n
b) n-1
c) n/2
d) logn
Answer: a
Explanation: Each node could be seen as a tree with only one node and as a result maximum subtree in the
heap is equal to number of nodes in the heap.
11. Choose the option with function having same complexity for a fibonacci heap.
a) Insertion, Union
b) Insertion, Deletion
c) extract_min, insertion
d) Union, delete
Answer: a
Explanation: For a fibonacci heap insertion, union take O(1) while remaining take O(logn) time.
12. What is wrong with the following code of insertion in fibonacci heap.
Choose the correct option
FIB-INSERT(H, x)
degree[x]= 0
p[x]= NIL
child[x] =NIL
left[x] =x
right[x] =x
mark[x] =FALSE
concatenate the root list containing x with root list H
if min[H] = NIL or key[x] > key[min[H]]
then min[H]= x
n[H]= n[H] + 1
a) Line -11
b) Line -3
c) Line 9
d) Line 7
Answer: c
Explanation: The main characterstics of a fibonacci heap is violated since min[H] must conatin one with
smallest value.
13. What will be the order of new heap created after union of heap H1 and H2 when created by the
following code.Initially both are of the order n.
FIB_UNION(H1,H2)
{
H =MAKE_HEAP()
min[H]= min[H1]
concatenate the root list of H2 with the root list of H
if (min[H1] = NIL) or (min[H2]!= NIL and min[H2] < min[H1])
then min[H] = min[H2]
n[H]= n[H1] + n[H2]
free the objects H1 and H2
return H
}
a) n+1
b) n+n/2
c) nlogn
d) 2*n
Answer: a
Explanation: Union of tw
Answer: a
Explanation: A d-heap is similar to that of a binary heap except that binary heaps have two children and d-
heaps have d children.
Answer: a
Explanation: d-heap is much shallower than a binary heap with respect to performance efficiency of insert
and delete operations.
Answer: d
Explanation: Unlike find operation, which cannot be performed in a d-heap, the task of merging two d-heaps
is very difficult.
Answer: c
Explanation: The run time efficiency of an insertion algorithm in a d-heap is found to be O(logd N) where d
is the number of children.
advertisement
Answer: b
Explanation: Since, the delete-min operation is more expensive and the heap is shallow, the minimum of d
elements can be found using d-1 comparisons.
Answer: b
Explanation: The two basic operations performed in a d-heap are insert and delete-min operations.
a) d-heap
b) binary heap
c) leftist heap
d) skew heap
Answer: a
Explanation: The given heap is a d-heap since it looks like a binary heap with d- children. Here, d=3.
10. Multiplication and division to find children and parents cannot be implemented in a d-heap.
a) true
b) false
Answer: b
Explanation: Multiplication and division for finding children and parents can be implemented in a d-heap
but d should be a power of 2.
Answer: d
Explanation: The other operations that can be performed in a d-heap are increasekey, decreasekey, buildheap
and delete.
Answer: d
Explanation: d-ary heap is a priority queue based data structure that is a generalization of binary heaps.
1. What is the smallest element of the given minimum ternary heap?
a) 1
b) 10
c) 18
d) 20
Answer: a
Explanation: Ternary heap is a type of data structure in the field of computer science. It is a part of the Heap
data structure family. Minimum ternary heap has the smallest element as its root node. The parent node is all
either equal or less than children node in a minimum ternary heap.
a) 31
b) 10
c) 18
d) 20
Answer: a
Explanation: Ternary heap is a type of data structure in the field of computer science. It is a part of the Heap
data structure family. Maximum ternary heap has the highest element as its root node. The parent node is all
either equal or greater than children node in a maximum ternary heap.
3. What is the child of smallest element of the given minimum ternary heap?
a) 1
b) 10
c) 22
d) 24
Answer: b
Explanation: Minimum ternary heap has the smallest element as its root node. The parent node is all either
equal or less than children node in a minimum ternary heap. In the above minimum ternary heap, the
smallest element is 1 and its children are 10, 18, 20.
4. What are the siblings of smallest element of the given maximum ternary heap?
a) 31
b) 12
c) 18
d) 22
Answer: c
Explanation: Maximum ternary heap has the highest element as its root node. The parent node is all either
equal or greater than children node in a maximum ternary heap. The smallest element in the maximum
ternary heap is 10 and its siblings are 18, 20.
a) 1
b) 10
c) 2
d) 24
Answer: a
Explanation: Minimum ternary heap has the smallest element as its root node. The parent node is all either
equal or less than children node in a minimum ternary heap. Height is the total length from the root node to
the leaf node. So the height of the minimum ternary heap is 1.
advertisement
6. What is the ancestor of the leaf node in a given minimum ternary heap?
a) 1
b) 10
c) 18
d) 20
Answer: a
Explanation: Minimum ternary heap has the smallest element as its root node. The parent node is all either
equal or less than children node in a minimum ternary heap. Ancestor is the node falling on the path from
that node to the root node. So here ancestor of all leaf nodes is 1.
Answer: d
Explanation: Ternary heap is a type of data structure in the field of computer science. It is a part of the Heap
data structure family. So, it should hold all the properties of Heap that is all the levels of the heap has to be
filled from left to right.
Answer: a
Explanation: Ternary heap is a type of data structure in the field of computer science. It is a part of the Heap
data structure family. So, it should hold all the properties of Heap that is all the levels of the heap has to be
filled from left to right.
Answer: a
Explanation: Ternary heap is a type of data structure in the field of computer science. It is a part of the Heap
data structure family. So, the process of building a ternary heap is known as Heapify.
Answer: c
Explanation: Ternary heap is a type of data structure in the field of computer science. It is a part of the Heap
data structure family. It is a priority queue type of data structure that follows all the property of heap.
Answer: a
Explanation: Priority queue is an abstract data type. It is also the extension of the Queue data structure
where all the elements have been assigned some priority and on the basis of this priority, the elements are
dequeued from the structure.
Answer: d
Explanation: Ternary heap is a type of data structure in the field of computer science. It is a part of the Heap
data structure family. So, it follows all the property of heap. Therefore, all the nodes in the ternary heap have
3 nodes.
Answer: c
Explanation: Ternary heap is a type of data structure in the field of computer science. It is a part of the Heap
data struct
1. What is the time complexity for inserting a new item in a ternary heap of n elements?
a) O (log n/ log 3)
b) O (n!)
c) O (n)
d) O (1)
Answer: a
Explanation: In order to insert a new item in a ternary heap data structure having n elements, the heap has
great efficiency for inserting them. So the time complexity for worst case is found to be O (log n/ log 3).
2. Is decrease priority operation performed more quickly in a ternary heap with respect to the binary heap.
a) True
b) False
Answer: a
Explanation: Ternary heap is a type of data structure in the field of computer science. It is a part of the Heap
data structure family. Due to the swapping process, the decrease priority operation performs more quickly in
a ternary heap.
3. What is the time complexity for decreasing priority of key in a minimum ternary heap of n elements?
a) O (log n/ log 3)
b) O (n!)
c) O (n)
d) O (1)
Answer: a
Explanation: In order to decrease the priority of an item in a ternary heap data structure having n elements,
the heap has great efficiency for decreasing them. So the time complexity for worst case is found to be O
(log n/ log 3). This is due to the upwards swapping process.
4. What is the time complexity for increasing priority of key in a maximum ternary heap of n elements?
a) O (log n/ log 3)
b) O (n!)
c) O (n)
d) O (1)
Answer: a
Explanation: In order to increase the priority of an item in a ternary heap data structure having n elements, it
performs upwards swapping. So the time complexity for worst case is found to be O (log n/ log 3).
5. What is the time complexity for deleting root key in a ternary heap of n elements?
a) O (log n/ log 3)
b) O (3log n/ log 3)
c) O (n)
d) O (1)
Answer: b
Explanation: In order to delete a root key in a ternary heap data structure having n elements, it performs
downward swapping. So the time complexity for worst case is found to be O (3log n/ log 3).
advertisement
6. What is the time complexity for increasing priority of key in a minimum ternary heap of n elements?
a) O (log n/ log 3)
b) O (3log n/ log 3)
c) O (n)
d) O (1)
Answer: b
Explanation: In order to the increasing the priority of key in a minimum ternary heap data structure having n
elements, it performs downward swapping. So the time complexity for worst case is found to be O (3log n/
log 3).
7. What is the time complexity for decreasing priority of key in a maximum ternary heap of n elements?
a) O (log n/ log 3)
b) O (3log n/ log 3)
c) O (n)
d) O (1)
Answer: b
Explanation: In order to decrease the priority of key in a maximum ternary heap data structure having n
elements, it performs downward swapping. So the time complexity for worst case is found to be O (3log n/
log 3).
8. Do ternary heap have better memory cache behavior than binary heap.
a) True
b) False
Answer: a
Explanation: Ternary heap is a type of data structure in the field of computer science. It is a part of the Heap
data structure family. Due to the swapping process, they have better memory cache behavior.
9. What is the time complexity for creating a ternary heap using swapping?
a) O (log n/ log 3)
b) O (n!)
c) O (n)
d) O (1)
Answer: c
Explanation: Ternary Heap can be formed by two swapping operations. Therefore, the time complexity for
creating a ternary heap using two swapping operation is found to be O (n).
Answer: a
Explanation: When working on the
Answer: a
Explanation: The reason for the simplicity of a pairing heap is its simplicity as it is simpler and outperform
other heap structures.
Answer: c
Explanation: A pairing heap is represented as a heap-ordered tree and the analysis of pairing heap is open.
3. The actual pairing heap implementation uses the right child and left child representation.
a) true
b) false
Answer: b
Explanation: The actual pairing heap implementation uses a left child and right sibling representation since
it follows heap order property.
4. Which node contains a pointer to its parent?
a) root node
b) right most child
c) left most child
d) left sibling
Answer: c
Explanation: A node that is a leftmost node contains a pointer to its parent, otherwise, the node is a right
sibling.
a) fibonacci heaps
b) pairing heap
c) skew heap
d) leftist heap
Answer: b
Explanation: The above figure is a representation of a pairing heap because it has left children and right
siblings.
advertisement
Answer: a
Explanation: The basic operation performed in a pairing heap is merging. Insertion is also done by merging.
7. If there are c children of the root, how many calls to the merge procedure is required to reassemble the
heap?
a) c
b) c+1
c) c-1
d) 1
Answer: c
Explanation: If there are c children of the root, then c-1 merges are required to reassemble the pairing heap.
8. Which of the following methods is the best choice for complex applications?
a) binary heap
b) d-heap
c) treap
d) pairing heap
Answer: d
Explanation: Pairing heap is the best choice for complex applications because it is simple and better than the
others.
Answer: a
Explanation: The pairing heaps insertion, deletion and search time complexity was initially inspired by that
of splay trees.
10. The roots of the elements of the subtrees are smaller than the root of the heap.
a) True
b) False
Answer: b
Explanation: The heap ordering property requires that all the root elements of the subtrees in the list are not
smaller than the root element of the heap.
11. The amortized time efficiency for performing deletion of a minimum element is?
a) O(N)
b) O(log N)
c) O(N2)
d) O(M log N)
Answer: b
Explanation: The amortized time efficiency for performing deletion of a minimum element is
mathematically found to be O(log N).
12. Out of the following given options, which is the fastest algorithm?
a) fibonacci heap
b) pairing heap
c) d-ary heap
d) binary heap
Answer: a
Explanation: Although pairing heap is an efficient algorithm, it is worse than the Fibonacci heap. Also,
pairing heap is faster than d-ary heap and binary heap.
Answer: a
Explanation: The run time efficiency of an insertion algorithm in a pairing heap is mathematically found to
be O(N).
Answer: a
Explanation: Use of pointers for merging reduces the speed of other operations. This is the main drawback
of all advanced data structures.
Answer: c
Explanation: A leftist heap supports two properties- structural property, ordering property and a heap order
property.
3. In a leftist heap, the null path length of a null node is defined as?
a) 0
b) 1
c) null
d) -1
Answer: d
Explanation: In a leftist heap tree, the null path length of a null node with no children is defined as -1.
4. How many nodes does a leftist tree with r nodes must have?
a) 2r
b) 2r-1
c) 2r
d) 2r-1
Answer: b
Explanation: A leftist tree with r nodes on the right path is proved to have at least 2r-1 nodes. This theorem
is proved by induction.
5. Which of the following operations does not destroy the leftist heap property?
a) insert
b) merge
c) delete
d) swap
Answer: c
Explanation: Performing insert and merge operations on the right path could destroy the leftist heap
property. It is extremely easy to restore that property.
advertisement
Answer: b
Explanation: The fundamental operations on leftist heaps is merge. Insertion operation is a merge of a one-
node heap with a larger heap.
Answer: a
Explanation: A leftist heap has a structural property and an ordering property which is similar to that of a
binary heap. Hence, leftist heap is also said to be binary heap.
Answer: d
Explanation: The efficiency of merge operations in leftist heap is mathematically found to be O( log N)
which is the same in binary heaps.
Answer: c
Explanation: The length of the shortest path from a node to a node without two children is defined as 0.
Answer: c
Explanation: All the operations are performed on the right path because right paths are short. However,
insertion and merges cannot be performed on the right path.
12. What would be the result if the left subtree of the root has a null path length of 1 and the right subtree
has a null path length of 2?
a) merge occurs without violation
b) violation at left subtree
c) violation at right subtree
d) violation at the root
Answer: d
Explanation: When two leftist heaps are merged, if the left subtree of the root has a null path length of 1 and
the right subtree has a null path length of 2, leftist property is violated at the root.
Answer: b
Explanation: While performing insertion via merge operation in a leftist heap, if the null path length is not
updated, all null path lengths will be 0.
14. What is the time taken to delete a minimum element in a leftist heap?
a) O(N)
b) O(N log N)
c) O(log N)
d) O(M log N)
Answer: c
Explanation: The time taken to delete a minimum element in a leftist heap is mathematically found to be
O(log N).
Answer: b
Explanation: A skew heap is a self-adjusting version of a leftist heap and it is simpler to implement.
2. The worst case running time of all operations in a skew heap is given as?
a) O(N)
b) O(N log N)
c) O(N2)
d) O(M log N)
Answer: a
Explanation: The worst case running time of all operations in a skew heap is mathematically found to be
O(N).
Answer: d
Explanation: The amortized cost per operation of a skew heap is O(log N) since the worst case analysis of
skew heap is O(N) and splay tree is O(M log N).
Answer: a
Explanation: Splay tree is a self -adjusting version of AVL tree. Similarly, skew heap is a self-adjusting
version of leftist heap.
6. What is the time per operation of merging, insertion and deletion operations in a skew heap?
a) O(N)
b) O(log N)
c) O(N log N)
d) O(N2)
Answer: b
Explanation: Skew heaps support merging, insertion and deletion all effectively in O(log N) time per
operation.
Answer: c
Explanation: In skew heaps, a recursive implementation could fail because of lack of stack space even
though performance is acceptable.
Answer: a
Explanation: It is an open problem to determine precisely the expected right path length of both leftist and
skew heaps and comparatively, the latter is difficult.
Answer: a
Explanation: The worst-case analysis for the naïve merge is an insertion in a right heavy tree. So, insertion
takes O(N).
10. How many types of the merge are available in skew heaps?
a) 1
b) 2
c) 3
d) 4
Answer: b
Explanation: Two kinds of the merge are available in skew heaps- naïve merge and skew merge.
Answer: b
Explanation: One way of doing skew merge is to begin with naïve merge and then swapping the left and
right children of the tree.
Answer: b
Explanation: The amortized efficiency of a skew heap is mathematically found to be O( log N).
13. In skew heaps, certain constraints are to be met in order to perform swapping.
a) true
b) false
Answer: b
Explanation: In skew heaps, swaps are unconditional. It is done with the exception that the largest of all
nodes does not
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)
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].
advertisement
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]
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
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
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)
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
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
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 s
Answer: a
Explanation: Trie is a very useful data structure which is based on the prefix of a string. Trie is used to
represent the “Retrieval” of data and thus the name Trie. And it is also known as a digital tree.
2. What traversal over trie gives the lexicographical sorting of the set of the strings?
a) postorder
b) preorders
c) inorder
d) level order
Answer: c
Explanation: In trie, we store the strings in such a way that there is one node for every common prefix.
Therefore the inorder traversal over trie gives the lexicographically sorted set of strings.
3. Which of the following is the efficient data structure for searching words in dictionaries?
a) BST
b) Linked List
c) Balancded BST
d) Trie
Answer: d
Explanation: In a BST, as well as in a balanced BST searching takes time in order of mlogn, where m is the
maximum string length and n is the number of strings in tree. But searching in trie will take O(m) time to
search the key.
4. Which of the following special type of trie is used for fast searching of the full texts?
a) Ctrie
b) Hash tree
c) Suffix tree
d) T tree
Answer: c
Explanation: Suffix tree, a special type of trie, contains all the suffixes of the given text at the key and their
position in the text as their values. So, suffix trees are used for fast searching of the full texts.
5. Following code snippet is the function to insert a string in a trie. Find the missing line.
advertisement
private void insert(String str)
{
TrieNode node = root;
for (int i = 0; i < length; i++)
{
int index = key.charAt(i) - 'a';
if (node.children[index] == null)
node.children[index] = new TrieNode();
________________________
}
node.isEndOfWord = true;
}
a) node = node.children[index];
b) node = node.children[str.charAt(i + 1)];
c) node = node.children[index++];
d) node = node.children[index++];
Answer: a
Explanation: In the insert() method we search if the string is present or not. If the string is not present, then
we insert the string into the trie. If it is present as the prefix, we mark the leaf node. So, correct option is
node = node.children[index];.
Answer: a
Explanation: Both the hashing and the trie provides searching in the linear time. But trie requires extra space
for storage and it is collision free. And trie allows finding all the strings with same prefix, so it is also called
prefix tree.
7. A program to search a contact from phone directory can be implemented efficiently using ______
a) a BST
b) a trie
c) a balanced BST
d) a binary tree
Answer: b
Explanation: Dictionaries, phone directories can be implemented efficiently using the trie. Because it trie
provides the efficient linear time searching over the entries.
8. What can be the maximum depth of the trie with n strings and m as the maximum sting the length?
a) log2n
b) log2m
c) n
d) m
Answer: d
Explanation: In the trie, the strings are stored efficiently based on the common prefixes. And trie has
maximum fan-out 26 if english alphabets are considered. Owing to this, the maximum depth is equal to the
maximum string length.
Answer: b
Explanation: A trie is an ordered tree where (i) the root represents an empty string(“”) (ii) each node other
than root is labeled with a character (iii) the children of a nodes are lexicographically ordered (iv) the paths
from the leaves to the root yields the strings.
10. Auto complete and spell checkers can be implemented efficiently using the trie.
a) True
b) False
Answer: a
Explanation: Trie provid
Answer: d
Explanation: In computer science, a suffix tree is also known as PAT tree or position tree. It is a compressed
search tree or prefix tree in which keys contain the suffix of text values as the text position.
Answer: b
Explanation: In computer science, a suffix tree is also known as PAT tree or position tree. It is a compressed
search tree or prefix tree in which keys contain the suffix of text values as the text position. It allows fast
string operation to be carried out by the user.
Answer: d
Explanation: Suffix tree is also known as PAT tree or position tree. It is a compressed search tree or prefix
tree in which keys contain the suffix of text values as the text position. It allows fast string operation. Total
time taken for construction of suffix tree is linear to the length of the tree.
Answer: d
Explanation: Suffix tree is also known as PAT tree or position tree. It is a compressed search tree or prefix
tree in which keys contain the suffix of text values as the text position. It allows fast string operation. Total
space taken for construction of a suffix tree is linear to the length of the tree.
Answer: b
Explanation: It is a compressed search tree or prefix tree in which keys contain the suffix of text values as
the text position. It allows fast string operation to be carried out by the user. The substring operation can be
performed by suffix tree in linear time.
advertisement
Answer: a
Explanation: In computer science, a suffix tree is also known as PAT tree or position tree. It is a compressed
search tree or prefix tree in which keys contain the suffix of text values as the text position. The concept of
Suffix Tree was introduced by Weiner in 1973.
7. Who among the following provided the first online contribution of Suffix Tree?
a) Weiner
b) Samuel F. B. Morse
c) Ukkonen
d) Alexander Morse
Answer: c
Explanation: In computer science, a suffix tree is also known as PAT tree or position tree. The concept of
Suffix Tree was introduced by Weiner in 1973. Ukkonen provided the first online contribution of Suffix tree
which had the time complexity of the fastest algorithm of that period.
Answer: d
Explanation: The concept of Suffix Tree was introduced by Weiner in 1973. Ukkonen provided the first
online contribution of Suffix tree which had the time complexity of the fastest algorithm of that period.
Ukkonen’s algorithm had a time complexity of n log n.
9. Who among the following provided the first suffix tree contribution for all alphabet?
a) Weiner
b) Farach
c) Ukkonen
d) Alexander Morse
Answer: b
Explanation: The concept of Suffix Tree was introduced by Weiner in 1973. Ukkonen provided the first
online contribution of Suffix tree which had the time complexity of the fastest algorithm of that period.
Farach gave the first suffix tree contribution for all alphabets in 1997.
10. Who among the following algorithm is used in external memory and compression of the suffix tree?
a) Weiner’s algorithm
b) Farach’s algorithm
c) Ukkonen’s algorithm
d) Alexander Morse
Answer: b
Explanation: The concept of Suffix Tree was introduced by Weiner in 1973. Ukkonen provided the first
online contribution of the Suffix tree. Farach gave the first suffix tree contribution for all alphabets in 1997.
Farach’s algorithm is used in external memory and compression.
12. Do all the nodes have at least two children in suffix tree.
a) True
b) False
Answer: b
Explanation: It is a compressed search tree or prefix tree in which keys contain the suffix of text values as
the text position. All the nodes (internal) except for the root nodes have at least two children.
13. Can the two edges that are coming out of a node have labels of string beginning with the same character?
a) True
b) False
Answer: b
Explanation: It is a compressed search tree or prefix tree in which keys contain the suffix of text values as
the text position. All the nodes (internal) except for the root nodes have at least two children. No two edges
that are coming out of a node have labels of string beginning with the same character.
Answer: c
Explanation: In computer science, the generalized suffix is a special suffix tree which contains a set of
strings or set of words instead of a single string like suffix tree. Hence Different operation can be performed
on a set of strings using a generalized suffix tree.
15. What is a time complexity for checking a string of length n is substring or not?
a) O (log n!)
b) O (n!)
c) O (n2)
d) O (n)
Answer: d
Explanation: Suffix tree is also known as PAT tree or position tree. It allows fast string operation. Total time
taken for construction of suffix tree is linear to the length of the tree. To check if a substring is present in a
string of a length of n, the time complexity for such operation is found to be O (n).
2. What is a time complexity for finding the longest substring that is common in string S1 and S2 (n1 and n2
are the string lengths of strings s1, s2 respectively)?
a) O (log n!)
b) Ɵ (n!)
c) O (n2+ n1)
d) Ɵ (n1 + n2)
Answer: d
Explanation: Suffix Tree allows fast string operation. To check if a substring is present in a string of a length
of n, the time complexity for such operation is found to be O (n). The time complexity for finding the
longest substring that is common in string S1 and S2 is Ɵ (n1 + n2).
3. What is a time complexity for finding the longest substring that is repeated in a string?
a) O (log n!)
b) Ɵ (n!)
c) O (n2+ n1)
d) Ɵ (n)
Answer: d
Explanation: Suffix Tree allows fast string operation. To check if a substring is present in a string of a length
of n, the time complexity for such operation is found to be O (n). The time complexity for finding the
longest substring that is repeated in a string is Ɵ (n).
4. What is a time complexity for finding frequently occurring of a substring of minimum length in a string?
a) Ɵ (n)
b) Ɵ (n!)
c) O (n2+ n1)
d) O (log n!)
Answer: a
Explanation: Suffix Tree allows fast string operation. To check if a substring is present in a string of a length
of n, the time complexity for such operation is found to be O (n). The time complexity for finding frequently
occurring of a substring of minimum length in a string is Ɵ (n).
5. What is a time complexity for finding the longest prefix that is common between suffix in a string?
a) Ɵ (n)
b) Ɵ (n!)
c) Ɵ (1)
d) O (log n!)
Answer: c
Explanation: Suffix Tree allows fast string operation. To check if a substring is present in a string of a length
of n, the time complexity for such operation is found to be O (n). The time complexity for finding the
longest prefix that is common between suffix in a string is Ɵ (1).
advertisement
6. What is a time complexity for finding all the maximal palindrome in a string?
a) Ɵ (n)
b) Ɵ (n!)
c) Ɵ (1)
d) O (log n!)
Answer: a
Explanation: Palindrome is a string that is the same when reading forward as well as backward. To check if
a substring is present in a string of a length of n, the time complexity for such operation is found to be O (n).
The time complexity for finding all the maximal palindrome in a string is Ɵ (n).
Answer: a
Explanation: Tandem Repeats are formed in DNA when the nucleotides pattern repeats more than once. To
check if a substring is present in a string of a length of n, the time complexity for such operation is found to
be O (n). The time complexity for finding all the tandem repeats in a string is O (n log n + z).
8. What is a time complexity for finding the longest palindromic substring in a string by using the
generalized suffix tree?
a) Linear Time
b) Exponential Time
c) Logarithmic Time
d) Cubic Time
Answer: a
Explanation: Palindrome is a string that is same when reading forward as well as backward. The time
complexity for finding the longest palindromic substring in a string by using generalized suffix tree is linear
time.
Answer: c
Explanation: The concept of Suffix Tree was introduced by Weiner in 1973. Ukkonen provided the first
online contribution of the Suffix tree. Farach gave the first suffix tree contribution for all alphabets in 1997.
Lempel – Ziv – Welch’s algorithm of data compression uses a suffix tree.
10. Which of the following data clustering algorithm uses suffix tree in search engines?
a) Weiner’s algorithm
b) Farach’s algorithm
c) Lempel – Ziv – Welch’s algorithm
d) Suffix Tree Clustering
Answer: d
Explanation: The concept of Suffix Tree was introduced by Weiner in 1973. Ukkonen provided the first
online contribution of Suffix. Farach gave the first suffix tree contribution for all alphabets in 1997. Suffix
Tree Clustering is a data clustering algorithm that uses suffix tree in search engines.
11. What is a time complexity for finding the total length of all string on all edges of a tree?
a) Ɵ (n)
b) Ɵ (n!)
c) Ɵ (1)
d) O (n2)
Answer: d
Explanation: To check if a substring is present in a string of a length of n, the time complexity for such
operation is found to be O (n). The time complexity for finding the total length of all string on all edges of a
tree is O (n2).
12. Can suffix tree be used in string problems occurring in a text editor.
a) True
b) False
Answer: a
Explanation: It is a compressed search tree or prefix tree in which keys contain the suffix of text values as
the text position. So, the suffix tree can be used in string problems occurring in a text editor. The time taken
to solve the problem is linear to the length of the string.
Answer: a
Explanation: It is a compressed search tree or prefix tree in which keys contain the suffix of text values as
the text position. So, a suffix tree is used in bioinformatics problems and solutions like pattern searching in
DNA and protein sequences.
14. For what size of nodes, the worst case of usage of space in suffix tree seen?
a) n Nodes
b) 2n Nodes
c) 2n nodes
d) n! nodes
Answer: c
Explanation: In computer science, the worst case of usage of space in a suffix tree is found to be for a
Fibonacci word for a full 2n nodes. The time complexity for usage of space is found to be O (n).
15. What is a time complexity for inserting an alphabet in the tree using hash maps?
a) O (log n!)
b) O (n!)
c) O (n2)
d) O (1)
Answer: d
Explanation: Suffix tree is also known as PAT tree or position tree. It allows fast string operation. Total time
taken for construction of suffix tree is linear to the length of the tree. The time complexity for inserting an
alphabet in the tree using hash maps is
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
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.
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.
advertisement
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
both the cases, the complexity is O(1+alpha) where 1 is to compute the hash function and alpha is the load
factor.
Answer: b
Explanation: Deletion becomes easier with doubly link
1. The case in which a key other than the desired one is kept at the identified location is called?
a) Hashing
b) Collision
c) Chaining
d) Open addressing
Answer: b
Explanation: When some other value is placed at a specified location other than the desired key, it is said to
be a collision.
Answer: c
Explanation: The data structure used to organize data for hash tables is linked list. It contains a data field and
a pointer field.
Answer: a
Explanation: Collision handling involves the process of formulating alternative indices for a key.
Answer: d
Explanation: Hashing is a technique of placing data items in specific locations. Collision may occur in
hashing but hashing is not a collision resolution technique.
Answer: b
Explanation: The hash location is defined as hash(f)= key mod table_size.
7 mod 10 gives 7. It is placed in 7th position.
Answer: b
Explanation: For hashing using separate chaining method, the load factor should be maintained as 1. For
open addressing method, it should not exceed 0.5.
Answer: c
Explanation: Hash tables are used to implement Insert and Find operations in constant average time. This is
the prime purpose of hashing.
Answer: a
Explanation: The hash node in separate chaining is similar to that of a linked list. The separate chaining hash
table is an array of linked lists.
10. Which of the following is the hashing function for separate chaining?
a) H(x)=(hash(x)+f(i)) mod table size
b) H(x)=hash(x)+i2 mod table size
c) H(x)=x mod table size
d) H(x)=x mod (table size * 2)
Answer: c
Explanation: The hashing function for separate chaining is given by H(x)= key mod table size. H(x)=hash(x)
+i2 mod table size defines quadratic probing.
Answer: d
Explanation: In general, load factor is denoted as ⅄. In separate chaining method, load factor is maintained
as 1.0.
12. In hash tables, how many traversal of links does a successful search require?
a) 1+⅄
b) 1+⅄2
c) 1+ (⅄/2)
d) ⅄3
Answer: c
Explanation: A successful search requires about 1+ (⅄/2) links to be traversed. There is a guarantee that at
least one link must be traversed.
13. Which of the following is a disadvantage of using separate chaining using linked lists?
a) It requires many pointers
b) It requires linked lists
c) It uses array
d) It does not resolve collision
Answer: a
Explanation: One of the major disadvantages of using separate chaining is the requirement of pointers. If the
number of elements are more, it requires more pointers.
14. What is the worst case search time of a hashing using separate chaining algorithm?
a) O(N log N)
b) O(N)
c) O(N2)
d) O(N3)
Answer: b
Explanation: The worst case search time of separate chaining algorithm using linked lists is mathematically
found to be O(N).
Answer: c
Explanation: From the giv
1. Which of the following is used in hash tables to determine the index of any input record?
a) hash function
b) hash linked list
c) hash tree
d) hash chaining
Answer: a
Explanation: Hash table is an example of a data structure that is built for fast access of elements. Hash
functions are used to determine the index of any input record in a hash table.
Answer: a
Explanation: Hash table is a data structure that has an advantage that it allows fast access of elements. Hash
functions are used to determine the index of any input record in a hash table.
Answer: a
Explanation: Hash function calculates and returns the index for corresponding data. This data is then
mapped in a hash table.
4. What is the time complexity of insert function in a hash table using a doubly linked list?
a) O(1)
b) O(n)
c) O(log n)
d) O(n log n)
Answer: a
Explanation: Time complexity of insert function in a hash table is O(1). Condition is that the number of
collisions should be low.
5. What is the time complexity of search function in a hash table using a doubly linked list?
a) O(1)
b) O(n)
c) O(log n)
d) O(n log n)
Answer: a
Explanation: Time complexity of search function in a hash table is O(1). Condition is that the number of
collisions should be low.
advertisement
6. What is the time complexity of delete function in the hash table using a doubly linked list?
a) O(1)
b) O(n)
c) O(log n)
d) O(n log n)
Answer: a
Explanation: Time complexity of delete function in a hash table is O(1). Condition is that the hash function
should be such that the number of collisions should be low.
Answer: a
Explanation: Hashing is also used in encryption algorithms. It is used for encryption and decryption of
digital signatures.
8. What is the advantage of using a doubly linked list for chaining over singly linked list?
a) it takes less memory
b) it is easy to implement
c) it makes the process of insertion and deletion faster
d) it causes less collisions
Answer: c
Explanation: Using a doubly linked list reduces time complexity significantly. Though it uses more memory
to store the extra pointer.
9. Which of the following technique stores data in the hash table itself in case of a collision?
a) Open addressing
b) Chaining using linked list
c) Chaining using doubly linked list
d) Chaining using binary tree
Answer: a
Explanation: Open addressing is used to store data in the table itself in case of a collision. Whereas chaining
stores data in a separate entity.
10. Which of the following technique stores data in a separate entity in case of a collision?
a) Open addressing
b) Chaining using doubly linked list
c) Linear probing
d) Double hashing
Answer: b
Explanation: Chaining using doubly linked list is used to store data in a separate entity (doubly linked list in
this case) in case of a collision. Whereas open addressing stores it in the table itself.
11. Collision is caused due to the presence of two keys having the same value.
a) True
b) False
Answer: a
Explanation: A collision is caused due to the presence of two keys having the same value. It is handled by
using any o
1. Which of the following variant of a hash table has the best cache performance?
a) hash table using a linked list for separate chaining
b) hash table using binary search tree for separate chaining
c) hash table using open addressing
d) hash table using a doubly linked list for separate chaining
Answer: c
Explanation: Implementation of the hash table using open addressing has a better cache performance as
compared to separate chaining. It is because open addressing stores data in the same table without using any
extra space.
Answer: c
Explanation: Hashing with separate chaining has an advantage that it is less sensitive to a hash function. It is
also easy to implement.
4. What is the time complexity of insert function in a hash table using a binary tree?
a) O(1)
b) O(n)
c) O(log n)
d) O(n log n)
Answer: a
Explanation: Time complexity of insert function in a hash table is O(1) on an average. Condition is that the
number of collisions should be low.
5. What is the time complexity of the search function in a hash table using a binary tree?
a) O(1)
b) O(n)
c) O(log n)
d) O(n log n)
Answer: a
Explanation: Time complexity of search function in a hash table is O(1). Condition is that the number of
collisions should be low.
advertisement
6. What is the time complexity of the delete function in the hash table using a binary tree?
a) O(1)
b) O(n)
c) O(log n)
d) O(n log n)
Answer: a
Explanation: Time complexity of delete function in a hash table is O(1). Condition is that the hash function
should be such that the number of collisions should be low.
Answer: a
Explanation: Hash table and BST both are examples of data structures. Hash table has an advantage that it
has a better time complexity for performing insert, delete and search operations.
Answer: d
Explanation: Open addressing is used to store data in the table itself in case of a collision. Whereas chaining
stores data in a separate entity.
Answer: a
Explanation: There are two methods of handling collisions in a hash table:- open addressing and separate
chaining. Open addressing requires more computation as compared to separate chaining.
11. In open addressing the hash table can never become full.
a) True
b) False
Answer: b
Explanation: There are t
Answer: a
Explanation: Hash table is an example of a data structure that is built for fast access of elements. Hash
functions are used to determine the index of any input record in a hash table.
Answer: a
Explanation: Hash table is a data structure that has an advantage that it allows fast access of elements. But
linked list is easier to implement as compared to the hash table.
3. Which of the following trait of a hash function is most desirable?
a) it should cause less collisions
b) it should cause more collisions
c) it should occupy less space
d) it should be easy to implement
Answer: a
Explanation: Hash function calculates and returns the index for corresponding data. So the most important
trait of a hash function is that it should cause a minimum number of collisions.
4. What is the time complexity of insert function in a hash table using list head?
a) O(1)
b) O(n)
c) O(log n)
d) O(n log n)
Answer: a
Explanation: Time complexity of insert function in a hash table is O(1). Condition is that the number of
collisions should be low.
5. What is the time complexity of search function in a hash table using list head?
a) O(1)
b) O(n)
c) O(log n)
d) O(n log n)
Answer: a
Explanation: Time complexity of search function in a hash table is O(1). Condition is that the number of
collisions should be low.
advertisement
6. What is the time complexity of delete function in the hash table using list head?
a) O(1)
b) O(n)
c) O(log n)
d) O(n log n)
Answer: a
Explanation: Time complexity of delete function in a hash table is O(1). Condition is that the hash function
should be such that the number of collisions should be low.
7. A hash table may become full in the case when we use open addressing.
a) true
b) false
Answer: a
Explanation: A hash table may become full in the case when we use open addressing. But when we use
separate chaining it does not happen.
8. What is the advantage of using linked list over the doubly linked list for chaining?
a) it takes less memory
b) it causes more collisions
c) it makes the process of insertion and deletion faster
d) it causes less collisions
Answer: a
Explanation: Singly linked list takes lesser space as compared to doubly linked list. But the time complexity
of the singly linked list is more than a doubly linked list.
9. What is the worst case time complexity of insert function in the hash table when the list head is used for
chaining?
a) O(1)
b) O(n log n)
c) O(log n)
d) O(n)
Answer: d
Explanation: Worst case time complexity of insert function in the hash table when the list head is used for
chaining is O(n). It is caused when a number of collisions are very high.
10. Which of the following technique is used for handling collisions in a hash table?
a) Open addressing
b) Hashing
c) Searching
d) Hash function
Answer: a
Explanation: Open addressing is the technique which is used for handling collisions in a hash table. Separate
chaining is another technique which is used for the same purpose.
11. By implementing separate chaining using list head we can reduce the number of collisions drastically.
a) True
b) False
Answer: b
Explanation: Collision is caused when a hash function returns repeated values. So collisions can be reduced
by developing a better hash function. Whereas separate chaining using list head is a collision handling
technique so it has no relation with a number of collisions taking place.
12. Which of the following is an advantage of open addressing over separate chaining?
a) it is simpler to implement
b) table never gets full
c) it is less sensitive to hash function
d) it has better cache performance
Answer: a
Explanation: Open addressing is the technique which is used for handling collisions in a hash table. It has a
better cache perfo
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
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.
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
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
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.
advertisement
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
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
Answer: b
Explanation: Clustering is not a theoretical problem but it occurs in implementations of hashing. Rehashing
is a kind of hashing.
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
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) \(\frac{1}{2} \frac{1+1}{(1-⅄)}\)
b) \(\frac{1}{2}\frac{1+1}{(1-⅄)^2}\)
c) \(\frac{1}{2}\frac{1+1}{(1+⅄)}\)
d) \(\frac{1}{2}\frac{1+1}{(1+⅄)(1-⅄)}\)
Answer: b
Explanation: The mathematical formula for calculating the number of probes for an unsuccessful search is \
(\frac{1}{2}\frac{1+1}{
Answer: d
Explanation: Quadratic probing comes under open addressing scheme to resolve collisions in hash tables.
Answer: a
Explanation: Quadratic probing can overcome primary collision that occurs in linear probing but a
secondary collision occurs in quadratic probing.
Answer: c
Explanation: Standard deletion cannot be performed in an open addressing hash table, because the cells
might have caused collision. Hence, the hash tables implement lazy deletion.
4. In quadratic probing, if the table size is prime, a new element cannot be inserted if the table is half full.
a) True
b) False
Answer: b
Explanation: In quadratic probing, if the table size is prime, we can insert a new element even though table
is exactly half filled. We can’t insert element if table size is more than half filled.
5. Which of the following is the correct function definition for quadratic probing?
a) F(i)=i2
b) F(i)=i
c) F(i)=i+1
d) F(i)=i2+1
Answer: a
Explanation: The function of quadratic probing is defined as F(i)=i2. The function of linear probing is
defined as F(i)=i.
advertisement
Answer: b
Explanation: 2 requirements are to be met with respect to table size. The table size should be a prime
number and the table size should not be more than half full.
Answer: a
Explanation: Quadratic probing handles primary collision occurring in the linear probing method. Although
secondary collision occurs in quadratic probing, it can be removed by extra multiplications and divisions.
Answer: b
Explanation: Linear probing offers better cache performance than quadratic probing and also it preserves
locality of reference.
10. For the given hash table, in what location will the element 58 be hashed using quadratic probing?
0 49
1
2
3
4
5
6
7
8 18
9 89
a) 1
b) 2
c) 7
d) 6
Answer: b
Explanation: Initially, 58 collid
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
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
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.
advertisement
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
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
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
Answer: b
Explanation: In multiplication method of creating hash functions the table size can be taken in integral
powers of 2.
m = 2p
m= 27
m = 128.
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
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)
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
Answer: a
Explanation: Because
1. Double hashing is one of the best methods available for open addressing.
a) True
b) False
Answer: a
Explanation: Double hashing is one of the best methods for open addressing because the permutations
produced have many characteristics of randomly chosen permutations.
Answer: c
Explanation: Double hashing uses a hash function of the form (h1(k) + i*h2(k))mod m where h1 and h2 are
auxiliary hash functions and m is the size of the hash table.
3. On what value does the probe sequence depend on?
a) c1
b) k
c) c2
d) m
Answer: b
Explanation: The probe sequence depends in upon the key k since the initial probe position, the offset or
both may vary.
4. The value of h2(k) can be composite relatively to the hash table size m.
a) True
b) False
Answer: b
Explanation: The value h2(k) must be relatively prime to the hash table size m for the entire hash table to be
searched. It can be ensured by having m in powers of 2 and designing h2 so that it produces an odd number.
5. What are the values of h1(k) and h2(k) in the hash function?
a)
h1(k) = m mod k
h2(k) = 1+ (m’ mod k)
advertisement
b)
h1(k) = 1 + (m mod k)
h2(k) = m’ mod k
c)
h1(k) = 1+ (k mod m)
h2(k) = k mod m
d)
h1(k) = k mod m
h2(k) = 1+ (k mod m’)
Answer: d
Explanation: The values h1(k) and h2(k) are k mod m and 1+(k mod m’) respectively where m is a prime
number and m’ is chosen slightly less than m. (m’=m-1).
6. What is the running time of double hashing?
a) Theta(m)
b) Theta(m2)
c) Theta(m log k)
d) Theta(m3)
Answer: a
Explanation: The running time of double hashing is Theta(m) since each possible (h1(k), h2(k)) pair yields a
distinct probe sequence. Hence the performance of double hashing is better.
7. Which technique has the greatest number of probe sequences?
a) Linear probing
b) Quadratic probing
c) Double hashing
d) Closed hashing
Answer: c
Explanation: Double hashing has the greatest number of probe sequences thereby efficiently resolves hash
collision problems.
Index Key
0 22
1 34
2
3
4
5 56
6
7 18
8 41
9
10
a) 3
b) 10
c) 4
d) 6
Answer: d
Explanation: The number 72 must be inserted at index 6.
H(k)=k mod m
H(72)= 72 mod 11
H(72)= 6.
Index Key
0
1 79
2
3
4 69
5 98
6
7 72
8
9
10
11 50
12
a) 2
b) 9
c) 4
d) 8
Answer: b
Explanation: Here the hash table is of size 13 with h1(k) = k mod 13 and h2(k) = 1 + k mod 11. Since 14 = 1
(mod 13) and 14 = 3 (mod 11), the key 14 is inserted into empty slot 9.
Answer: c
Explanation: The value of
Answer: b
Explanation: Hash list is the list of hashes of the blocks in a set file. Hash tree is a generalization of the hash
list in which leaves are labeled with the hash of a data block and every non-leaf node is hash of the labels of
its children.
Answer: a
Explanation: Hash trees are used in distributed systems for efficient data verification. Hash tree used hashes
instead of the full files, hence they are efficient. Because Hashes are ways of encoding files that are much
smaller than the actual file itself.
Answer: c
Explanation: The general form the hash tree which is used widely is the Tiger tree hash. It uses a binary hash
tree, usually has a data block size of 1024 bytes and uses the Tiger hash.
4. Which of the following is true for a Hash tree?
a) Hashing is used for sequential access
b) Indexing is used for direct access
c) Hash tree allows only sequential access
d) Hashing is used for direct access
Answer: d
Explanation: Hash tree allows direct as well as sequential access of the records. Hashing is used for direct
access and indexing is generally used for the sequential access.
Answer: a
Explanation: Hash tree is generally known as Merkle tree after Ralph Merkle who patented it in 1979.
Typically Merkle trees have a branching factor of 2, meaning that each node has up to 2 children.
advertisement
6. What will be the height of the hash tree with branching factor 2 and with 8 records?
a) 3
b) 5
c) 4
d) 6
Answer: c
Explanation: Consider 8 records A B C D E F G H. These records are stored in Hash tree in as shown in
figure below.
8. What is the worst case time complexity of the insertion in the hash tree?
a) O(logk(n))
b) O(n2)
c) O(nlogk(n))
d) O(kn)
Answer: a
Explanation: To insert a record in the hash tree the key is compressed and hashed to get the slot for the
entry. So, a hash tree with branching factor k takes O(logk(n)) for insertion in worst case.
Answer: a
Explanation: The sequential access in the hash tree is more efficient and faster than in B-tree. Because while
constructing the hash tree in the expansions and contractions of the file is an estimated.
10. Hash tree is used in data synchronisation. In the worst case the data synchronisation takes ______ time.
a) O(logn)
b) O(n2)
c) O(nlogn)
d) O(n)
Answer: d
Explanation: In average scenarios, the synchronisation takes O(logn) because it is based on the traversal and
searching. The w
Answer: a
Explanation: In computer science as well as data mining, to find the similarity between two given sets, a
technique called MinHash or min-wise independent permutation scheme is used. It helps in the quick
estimation of the similarity between two sets.
3. Which technique was firstly used to remove duplicate web pages from search results in AltaVista search
engine?
a) MinHash
b) Stack
c) Priority Queue
d) PAT Tree
Answer: a
Explanation: In computer science as well as data mining, to find the similarity between two given sets, a
technique called MinHash or min-wise independent permutation scheme is used. It helps in the quick
estimation of the similarity between two sets. It is used in removing duplicate web pages from search results
in AltaVista search engine.
4. Which technique was firstly used clustering documents using the similarity of two words or strings?
a) MinHash
b) Stack
c) Priority Queue
d) PAT Tree
Answer: a
Explanation: In computer science as well as data mining, to find the similarity between two given sets, a
technique called MinHash or min-wise independent permutation scheme is used. It helps in the quick
estimation of similarity between two sets. It is used in clustering documents using the similarity of two
words or strings.
Answer: b
Explanation: In computer science as well as data mining, to find the similarity between two given sets, a
technique called MinHash or min-wise independent permutation scheme is used. It helps in the quick
estimation of similarity between two sets. Jaccard Coefficient is used for similarity between two sets.
advertisement
6. Which of the following is defined as the ratio of total elements of intersection and union of two sets?
a) Rope Tree
b) Jaccard Coefficient Index
c) Tango Tree
d) MinHash Coefficient
Answer: b
Explanation: MinHash helps in the quick estimation of similarity between two sets. Jaccard Coefficient is
used for similarity between two sets. Jaccard Coefficient Index is defined as the ratio of total elements of
intersection and union of two sets.
7. What is the value of the Jaccard index when the two sets are disjoint?
a) 1
b) 2
c) 3
d) 0
Answer: d
Explanation: MinHash helps in the quick estimation of similarity between two sets. Jaccard Coefficient is
used for the similarity between two sets. Jaccard Coefficient Index is defined as the ratio of total elements of
intersection and union of two sets. For two disjoint sets, the value of the Jaccard index is zero.
Answer: a
Explanation: Jaccard Coefficient Index is defined as the ratio of total elements of intersection and union of
two sets. For two disjoint sets, the value of the Jaccard index is zero. The members of two set more common
relatively when the Jaccard Index is Closer to 1.
9. What is the expected error for estimating the Jaccard index using MinHash scheme for k different hash
functions?
a) O (log k!)
b) O (k!)
c) O (k2)
d) O (1/k½)
Answer: d
Explanation: Jaccard Coefficient Index is defined as the ratio of total elements of intersection and union of
two sets. For two disjoint sets, the value of the Jaccard index is zero. The expected error for estimating the
Jaccard index using MinHash scheme for k different hash functions is O (1/k½).
10. How many hashes will be needed for calculating Jaccard index with an expected error less than or equal
to 0.05?
a) 100
b) 200
c) 300
d) 400
Answer: d
Explanation: The expected error for estimating the Jaccard index using MinHash scheme for k different hash
functions is O (1/k½). 400 hashes will be needed for calculating Jaccard index with an expected error less
than or equal to 0.05.
11. What is the expected error by the estimator Chernoff bound on the samples performed without
replacement?
a) O (log k!)
b) O (k!)
c) O (k2)
d) O (1/k½)
Answer: d
Explanation: The expected error for estimating the Jaccard index using MinHash scheme for k different hash
functions is O (1/k½). The expected error by the estimator Chernoff bound on the samples performed
without replacement is O (1/k½).
12. What is the time required for single variant hashing to maintain the minimum hash queue?
a) O (log n!)
b) O (n!)
c) O (n2)
d) O (n)
Answer: d
Explanation: The expected error for estimating the Jaccard index using MinHash scheme for k different hash
functions is O (1/k½). The time required for single variant hashing to maintain the minimum hash queue is
O (n).
13. How many bits are needed to specify the single permutation by min-wise independent family?
a) O (log n!)
b) O (n!)
c) Ω (n2)
d) Ω (n)
Answer: d
Explanation: The time required for single variant hashing to maintain the minimum hash queue is O (n). Ω
(n) bits are needed to specify the single permutation by min-wise independent family.
Answer: a
Explanation: MinHash was originally used to remove the duplicate webpages from a search engine. But in
data mining, MinHash used as a tool for association rule learning by Cohen at 2001.
15. Did Google conduct a large evaluation for comparing the performance by two technique MinHash and
SimHash.
a) True
b) False
Answer: a
Explanation: MinHash was originally used to remove the duplicate webpages from a search engine. But in
data mining, MinHash u
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: b
Explanation: Since each key is associated with a slot in the array, it is better to use direct addressing when
the universe of keys is small as the array size grows with the increase in number of keys.
Answer: d
Explanation: Since every key has a unique array position, searching takes a constant time.
4. What is the time complexity to insert an element into the direct address table?
a) O(n)
b) O(logn)
c) O(nlogn)
d) O(1)
Answer: d
Explanation: As every key has a unique array position, it takes constant time to insert an element.
advertisement
Answer: b
Explanation: Using a dynamic set, the size of the array is restricted to the number of keys, hence saves
space. The complexity to implement dynamic array is larger than in normal case.
6. What is the time complexity to delete an element from the direct address table?
a) O(n)
b) O(logn)
c) O(nlogn)
d) O(1)
Answer: d
Explanation: As every key has a unique array position, it takes constant time to delete an element, although
the deleted position must be specified by nil.
7. How is a bit vector better compared to a normal array for implementing the hash table?
a) It saves time
b) It saves space
c) It saves both time and space
d) It reduces code complexity
Answer: b
Explanation: A bit vector is an array of bits of only 0s and 1s, a bit vector of length m takes much less space
than an array of m pointers. The complexity to implement bit vector is larger than in normal case.
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.
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,
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.
advertisement
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;
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];
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 verte
1. Incidence matrix and Adjacency matrix of a graph will always have same dimensions?
a) True
b) False
Answer: b
Explanation: For a graph having V vertices and E edges, Adjacency matrix have V*V elements while
Incidence matrix have V*E elements.
Answer: c
Explanation: For every edge only the vertices with which it is connected would have the value 1 in the
matrix, as an edge connects two vertices sum will always be 2.
Answer: b
Explanation: Columns may represent edges and vertices may be represented by the rows.
4. The column sum in an incidence matrix for a directed graph having no self loop is __________
a) 0
b) 1
c) 2
d) equal to the number of edges
Answer: a
Explanation: Under every edge column there would be either all 0 values or a pair of -1 and +1 value exists.
5. Time complexity to check if an edge exists between two vertices would be ___________
a) O(V*V)
b) O(V+E)
c) O(1)
d) O(E)
Answer: d
Explanation: We have to check for all edges, in the worst case the vertices will have no common edge.
advertisement
6. The graphs G1 and G2 with their incidences matrices given are Isomorphic.
e1 e2 e3 e4 e5 e6
v1 1 0 0 0 0 0
v2 1 1 0 0 0 1
v3 0 1 1 0 1 0
v4 0 0 1 1 0 0
v5 0 0 0 1 1 1
e1 e2 e3 e4 e5 e6
v1 0 0 1 0 0 0
v2 1 0 1 0 1 0
v3 1 1 0 1 0 0
v4 0 1 0 0 0 1
v5 0 0 0 1 1 1
a) True
b) False
Answer: a
Explanation: Two graphs are isomorphic if their Incidence Matrices differ only by permutation of columns
and rows.
7. If a connected Graph (G) contains n vertices what would be the rank of its incidence matrix?
a) n-1
b) values greater than n are possible
c) values less than n-1 are possible
d) insufficient Information is given
Answer: a
Explanation: Every column of the incidence matrix may contain only +1 and -1 as non zero entries rank
would be less than n.
8. In the following DAG find out the number of required Stacks in order to represent it in a Graph Structured
Stack.
a) 1
b) 2
c) 3
d) 4
Answer: c
Explanation: Path ADE, BDE and BCE are possible.
Answer: c
Explanation: A Graph Structured Stack is a Directed Acyclic Graph with each path representing a stack.
10. If a Graph Structured Stack contains {1,2,3,4} {1,5,3,4} {1,6,7,4} and {8,9,7,4}, what would be the
source and sink vertices of the DAC?
a) Source – 1, 8 Sink – 7,4
b) Source – 1 Sink – 8,4
c) Source – 1, 8 Sink – 4
d) Source – 4, Sink – 1,8
Answer: c
Explanation: Every Stack of the Graph Structured Stack represents a path, each path starts with the source
vertex and ends with the sink vertex.
Answer: b
Explanation: Tomita’s is a parsing algorithm which uses Graph Structured Stack in its implementation.
12. If in a DAG N sink vertices and M source vertices exists, then the number of possible stacks in the
Graph Structured Stack representation would come out to be N*M.
a) True
b) False
Answer: b
Explanation: The answer wou
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.
advertisement
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];
void addEdge(int i,int j,int weigh)
{
adjacent[a].push_back(i);
adjacent[b].push_back(j);
weight[a].push_back(weigh);
weight[b].push_back(weigh);
}
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: Th
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.
advertisement
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.
8. Which of the following graphs are isomorphic to each other?
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 o
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.
a) ABCED
b) AEDCB
c) EDCBA
d) ADECB
Answer: a
Explanation: In this case two answers are possible including ADEBC.
9. What would be the value of the distance matrix, after the execution of the given code?
#include <bits/stdc++.h>
#define INF 1000000
int graph[V][V] = { {0, 7, INF, 4},
{INF, 0, 13, INF},
{INF, INF, 0, 12},
{INF, INF, INF, 0}
};
int distance[V][V], i, j, k;
for (i = 0; i < V; i++)
for (j = 0; j < V; j++)
distance[i][j] = graph[i][j];
for (k = 0; k < V; k++)
for (i = 0; i < V; i++)
for (j = 0; j < V; j++)
{
if (distance[i][k] + distance[k][j] < distance[i][j])
distance[i][j] = distance[i][k] + distance[k][j];
return 0;
}
a)
{
{0, 7, INF, 4},
{INF, 0, 13, INF},
{INF, INF, 0, 12},
{INF, INF, INF, 0}
};
b)
{
{0, 7, 20, 24},
{INF, 0, 13, 25},
{INF, INF, 0, 12},
{INF, INF, INF, 0}
};
c)
{
{0, INF, 20, 24},
{INF, INF, 13, 25},
{INF, INF, 0, 12},
{INF, INF, INF, 0}
{INF, 0, 13, 25},
{INF, INF, 0, 12},
{24, INF, INF, 0}
};
Answer: b
Explanation: The program computes the shortest sub distances.
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 exi
Answer: a
Explanation: A sink vertex is a vertex which has an outgoing degree of zero.
2. Which of the following is not a topological sorting of the given graph?
a) A B C D E F
b) A B F E D C
c) A B E C F D
d) A B C D F E
Answer: d
Explanation: Topological sorting is a linear arrangement of vertices such that for every directed edge uv
from vertex u to vertex v, u comes before v in the ordering. In A B C D F E, F comes before E in ordering.
3. With V(greater than 1) vertices, how many edges at most can a Directed Acyclic Graph possess?
a) (V*(V-1))/2
b) (V*(V+1))/2
c) (V+1)C2
d) (V-1)C2
Answer: a
Explanation: The first edge would have an outgoing degree of atmost V-1, the next edge would have V-2
and so on, hence V-1 + V-2…. +1 equals (V*(V-1))/2.
Answer: c
Explanation: Topological sorting can be done in O(V+E), here V and E represents number of vertices and
number of edges respectively.
5. If there are more than 1 topological sorting of a DAG is possible, which of the following is true.
a) Many Hamiltonian paths are possible
b) No Hamiltonian path is possible
c) Exactly 1 Hamiltonian path is possible
d) Given information is insufficient to comment anything
Answer: b
Explanation: For a Hamiltonian path to exist all the vertices must be connected with a path, had that
happened there would have been a unique topological sort.
advertisement
6. What sequence would the BFS traversal of the given graph yield?
a) A F D B C E
b) C B A F E D
c) A B D C E F
d) E F D C B A
Answer: c
Explanation: In BFS nodes gets explored and then the neighbors of the current node gets explored, before
moving on to the next levels.
7. What would be the output of the following C++ program if the given input is
0 0 0 1 1
0 0 0 0 1
0 0 0 1 0
1 0 1 0 0
1 1 0 0 0
#include <bits/stdc++.h>
using namespace std;
bool visited[5];
int G[5][5];
void fun(int i)
{
cout<<i<<" ";
visited[i]=true;
for(int j=0;j<5;j++)
if(!visited[j]&&G[i][j]==1)
fun(j);
}
int main()
{
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
cin>>G[i][j];
for(int i=0;i<5;i++)
visited[i]=0;
fun(0);
return 0;
}
a) 0 2 3 1 4
b) 0 3 2 4 1
c) 0 2 3 4 1
d) 0 3 2 1 4
Answer: b
Explanation: Given Input is the adjacency matrix of a graph G, whereas the function ‘fun’ prints the DFS
traversal.
Answer: d
Explanation: Cyclic Directed Graphs cannot be sorted topologically.
9. For any two different vertices u and v of an Acyclic Directed Graph if v is reachable from u, u is also
reachable from v?
a) True
b) False
Answer: b
Explanation: If such vertices exists it means that the graph contains a cycle which contradicts the first part of
the statement.
10. What is the value of the sum of the minimum in-degree and maximum out-degree of an Directed Acyclic
Graph?
a) Depends on a Graph
b) Will always be zero
c) Will always be greater than zero
d) May be zero or greater than zero
Answer: b
Explanation: E
1. In which of the following does a Directed Acyclic Word Graph finds its application in?
a) String Matching
b) Number Sorting
c) Manipulations on numbers
d) Pattern Printing
Answer: a
Explanation: A Directed Acyclic Word Graph is similar to suffix tree, it can be viewed as a Deterministic
Finite Automata.
2. What is the number of words that can be formed from the given Directed Acyclic Word Graph?
a) 2
b) 4
c) 12
d) 7
Answer: b
Explanation: Words namely BATS, BOTS, BAT and BOT can be formed.
3. Determine the longest string which is described by the given Directed Acyclic Word Graph.
a) BATS
b) BOATS
c) BOT
d) BAT
Answer: a
Explanation: Starting from the initial state and choosing B, A, T, S respectively.
4. What is time complexity to check if a string(length S1) is a substring of another string(length S2) stored in
a Directed Acyclic Word Graph, given S2 is greater than S1?
a) O(S1)
b) O(S2)
c) O(S1+S2)
d) O(1)
Answer: a
Explanation: For each check of a word of length S1, we need to follow at most S1 edges.
5. In which of the following case does a Propositional Directed Acyclic Graph is used for?
a) Representation of Boolean Functions
b) String Matching
c) Searching
d) Sorting of number
Answer: a
Explanation: A Propositional Directed Acyclic Graph is used to represent a boolean function.
advertisement
6. Consider the following symbols and choose which of the symbols represent nodes having atleast one
child?
a) iv) and v)
b) iii) iv) and v)
c) i) and ii)
d) i) and iii)
Answer: c
Explanation: The symbols Δ and ◊ represents logical AND and OR gates.
7. Which of the following symbols represent nodes having exactly one child?
a) iv) and v)
b) v)
c) i) and iii)
d) iii)
Answer: d
Explanation: ∇ symbol represents the logical NOT gate.
a) iv) and v)
b) v)
c) i) and iii)
d) ii)
Answer: a
Explanation: The two symbols T, ⊥ represent the Boolean values.
Answer: a
Explanation: Both Binary Decision Diagram and Propositional Directed Acyclic Graph may be used to
represent the same Boolean function.
10. In a Propositional Directed Acyclic Graph Leaves maybe labelled with a boolean variable.
a) True
b) False
Answer: a
Explanation: In a Propo
Answer: c
Explanation: In i) self loops exist for both the vertices, in iii) self loop exists in the second vertex.
Answer: a
Explanation: Only graphs with every vertex having even degree have eulerian circuits or cycles.
Answer: b
Explanation: Sum of degrees of all the edges equal to 2 times the number of edges. 2*12=4*n, n=>6.
Answer: b
Explanation: If a vertex has a degree 9 that means it is connected to all the other vertices, in case of
Multigraphs for an isolate vertex, and a multiple edge may compensate.
Answer: c
Explanation: In i) self loops exist for both the vertices, in iii) self loop exists in the second vertex.
advertisement
6. Possible number of labelled simple Directed, Pseudo and Multigarphs exist having 2 vertices?
a) 3, Infinite, 4
b) 4, 3, Infinite
c) 4, Infinite, infinite
d) 4, Infinite, Infinite
Answer: d
Explanation: MultiGraphs and PseudoGraphs may have infinite number of edges, while 4 possible simple
graphs exist.
7. Which of the following is a HyperGraph, where V is the set of vertices, E is the set of edges?
a) V = {v1, v2, v3} E = {e1, e2} = {{v2, v3} {v1, v3}}
b) V = {v1, v2} E = {e1} = {{v1, v2}}
c) V = {v1, v2, v3} E = {e1, e2, e3} = {{v2, v3}{v3, v1}{v2, v1}}
d) All of the mentioned
Answer: d
Explanation: In a uniform Graph all the hyper-edges have the same cardinality.
Answer: a
Explanation: The columns represent edges while rows represent vertices.
Answer: b
Explanation: The degree of v1,v2,v3,v4,v5,v6 is 3,2,1,2,2,1 respectively.
Answer: a
Explanation: All PsuedoGraphs are MultiGraphs, but all MultiGraphs are not PseudoGraphs as all
PseudoGraphs have
Answer: c
Explanation: An Inverter is a directed graph which is used to solve Boolean expressions, hence have no
loops.
2. In which of the following case does a Binary Decision Diagram is used for?
a) Representation of Boolean Functions
b) String Matching
c) Searching
d) Sorting of number
Answer: a
Explanation: A Binary Decision Diagram is used to represent a Boolean function.
4. In a Binary Decision Diagrams 0 values by a _________ line and the 1 values are represented by a
_________ line.
a) dashed, bold
b) bold, dashed
c) dotted, bold
d) dotted, dashed
Answer: c
Explanation: It is used to distinguish between the 2 values without explicitly writing.
5. How many nodes are required to create a Binary Decision Tree having 4 variables?
a) 24
b) 24-1
c) 25
d) 25-1
Answer: d
Explanation: Binary Decision Trees are complete Binary Trees of level V + 1, here V is the number of
variables.
advertisement
Answer: a
Explanation: And Inverter Graphs are not canonical in nature.
7. Size of an And Inverter Graph is the number of _______ gates and the number of logic levels is number
of ________ gates on the __________ path from a primary input to a primary output.
a) AND, AND, average
b) AND, OR, longest
c) OR, OR, shortest
d) AND, AND, longest
Answer: d
Explanation: The given statement forms the attributes of the And Inverter Graph.
Answer: c
Explanation: And Inverter is a directed graph which is used to solve boolean expressions, hence have no
loops.
9. The And Inverter Graph representation of a Boolean function is more efficient than the Binary Decision
Diagram.
a) True
b) False
Answer: a
Explanation: The conversion from the network logic is faster and more scalable than in the case of the
Binary Decision Diagram.
10. Which of the following logical operation can’t be implemented by polynomial time graph manipulation
algorithms using Binary Decision Diagrams?
a) Conjunction
b) Disjunction
c) Negation
d) Tautology Checking
Answer: d
Explanation: In Binary Decisio
Answer: d
Explanation: It is practical to implement linear search in the situations mentioned in When the list has only a
few elements and When performing a single search in an unordered list, but for larger elements the
complexity becomes larger and it makes sense to sort the list and employ binary search or hashing.
2. Select the code snippet which performs unordered linear search iteratively?
a)
b)
c)
d)
advertisement
int unorderedLinearSearch(int arr[], int size, int data)
{
int index;
for(int i = 0; i < size-1; i++)
{
if(arr[i] == data)
{
index = i;
break;
}
}
return index;
}
Answer: a
Explanation: Unordered term refers to the given array, that is, the elements need not be ordered. To search
for an element in such an array, we need to loop through the elements until the desired element is found.
Answer: d
Explanation: The element is at the head of the array, hence O(1).
Answer: c
Explanation: Worst case is when the desired element is at the tail of the array or not present at all, in this
case you have to traverse till the end of the array, hence the complexity is O(n).
5. Select the code snippet which performs ordered linear search iteratively?
a)
b)
c)
d)
Answer: b
Explanation: The term ordered refers to the items in the array being sorted(here we assume ascending order).
So traverse through the array until the element, if at any time the value at i exceeds key value, it means the
element is not present in the array. This provides a slightly better efficiency than unordered linear search.
6. What is the best case and worst case complexity of ordered linear search?
a) O(nlogn), O(logn)
b) O(logn), O(nlogn)
c) O(n), O(1)
d) O(1), O(n)
Answer: d
Explanation: Although ordered linear search is better than unordered when the element is not present in the
array, the best and worst cases still remain the same, with the key element being found at first position or at
last position.
7. Choose the code snippet which uses recursion for linear search.
a)
public void linSearch(int[] arr, int first, int last, int key)
{
if(first == last)
{
System.out.print("-1");
}
else
{
if(arr[first] == key)
{
System.out.print(first);
}
else
{
linSearch(arr, first+1, last, key);
}
}
}
b)
public void linSearch(int[] arr, int first, int last, int key)
{
if(first == last)
{
System.out.print("-1");
}
else
{
if(arr[first] == key)
{
System.out.print(first);
}
else
{
linSearch(arr, first+1, last-1, key);
}
}
}
c)
public void linSearch(int[] arr, int first, int last, int key)
{
if(first == last)
{
System.out.print("-1");
}
else
{
if(arr[first] == key)
{
System.out.print(last);
}
else
{
linSearch(arr, first+1, last, key);
}
}
}
d)
public void linSearch(int[] arr, int first, int last, int key)
{
if(first == last)
{
System.out.print("-1");
}
else
{
if(arr[first] == key)
{
System.out.print(first);
}
else
{
linSearch(arr, first+1, last+1, key);
}
}
}
Answer: a
Explanation: Every time check the key with the array value at first index, if it is not equal then call the
function again with an incremented first index.
Answer: a
Explanation: The print statement is executed only when the items are equal and their indices are not.
9. Select the code snippet which prints the element with maximum frequency.
a)
b)
c)
d)
Answer: a
Explanation: Traverse through the array and see if it is equal to the previous element, since the array is
sorted this method works with a time complexity of O(nlogn), without sorting a Brute force technique must
be applied for which the time complexity will be O(n2).
Answer: b
Explanation: The complexity of linear search as the name suggests is O(n) which is much greater than other
searching techniques like binary search(O(logn)). Linear search is easy to implement and understand than
other searching techniques.
1. Is there any difference in the speed of execution between linear serach(recursive) vs linear
search(lterative)?
a) Both execute at same speed
b) Linear search(recursive) is faster
c) Linear search(Iterative) is faster
d) Cant be said
Answer: c
Explanation: The Iterative algorithm is faster than the latter as recursive algorithm has overheads like calling
function and registering stacks repeatedly.
2. Is the space consumed by the linear search(recursive) and linear search(iterative) same?
a) No, recursive algorithm consumes more space
b) No, recursive algorithm consumes less space
c) Yes
d) Nothing can be said
Answer: a
Explanation: The recursive algorithm consumes more space as it involves the usage the stack space(calls the
function numerous times).
Answer: a
Explanation: In the worst case scenario, there might be a need of calling the stack n times. Therfore O(n).
Answer: a
Explanation: It is used when the size of the dataset is low as its runtime is O(n) which is more when
compared to the binary search O(logn).
5. The array is as follows: 1,2,3,6,8,10. At what time the element 6 is found? (By using linear
search(recursive) algorithm)
a) 4th call
b) 3rd call
c) 6th call
d) 5th call
Answer: a
Explanation: Provided that the search starts from the first element, the function calls itself till the element is
found. In this case, the element is found in 4th call.
advertisement
6. The array is as follows: 1,2,3,6,8,10. Given that the number 17 is to be searched. At which call it tells that
there’s no such element? (By using linear search(recursive) algorithm)
a) 7th call
b) 9th call
c) 17th call
d) The function calls itself infinite number of times
Answer: a
Explanation: The function calls itself till the element is found. But at the 7th call it terminates as goes
outside the array.
7. What is the best case runtime of linear search(recursive) algorithm on an ordered set of elements?
a) O(1)
b) O(n)
c) O(logn)
d) O(nx)
Answer: a
Explanation: The best case occurs when the given element to be found is at the first position. Therefore O(1)
is the correct answer.
for(i=0;i<n;i++)
{
if(a[i]==key)
printf("element found");
}
b)
LinearSearch(int[] a, n,key)
{
if(n<1)
return False
if(a[n]==key)
return True
else
LinearSearch(a,n-1,key)
}
c)
LinearSearch(int[] a, n,key)
{
if(n<1)
return True
if(a[n]==key)
return False
else
LinearSearch(a,n-1,key)
}
d)
LinearSearch(int[] a, n,key)
{
if(n<1)
return False
if(a[n]==key)
return True
else
LinearSearch(a,n+1,key)
}
Answer: b
Explanation: Compare n with first element in arr[]. If element is found at first position, return it. Else recur
for remaining array and n.
9. Can linear search recursive algorithm and binary search recursive algorithm be performed on an
unordered list?
a) Binary search can’t be used
b) Linear search can’t be used
c) Both cannot be used
d) Both can be used
Answer: a
Explanation: As binary search requires comparison, it is required that the list be ordered. Whereas this
doesn’t matter for linear search.
10. What is the recurrence relation for the linear search recursive algorithm?
a) T(n-2)+c
b) 2T(n-1)+c
c) T(n-1)+c
d) T(n+1)+c
Answer: c
Explanation: After each call in the
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)
advertisement
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);
}
}
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
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
Answer: a
Explanation: At first level key = 90
At second level key= 99
Here 90 and 99 are mid values.
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)
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.
b)
c)
Answer: b
Explanation: Find the ‘mid’, check if it equals the key, if not, continue the iterations until low <= high.
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
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
Answer: a
Explanation: Trace the input with the binary search iterative code.
Answer: b
Explanation: T(n) = T(n/2) + theta(1)
Using the divide and conquer mast
1. In which of the cases uniform binary search fails compared to binary search?
a) A table lookup is generally faster than an addition and a shift
b) Many searches will be performed on the same array
c) Many searches will be performed on several arrays of the same length
d) Complexity of code
Answer: d
Explanation: Uniform binary search code is more complex to implement than binary search as it involves
mid points to be computed in hand before search.
2. Which of the following is a suitable lookup table that can be used in the uniform binary search?(N is the
number of elements in the array and the delta array is global)
a)
b)
advertisement
public static void make_delta(int N)
{
int power = 1;
int i = 0;
do
{
int half = power;
power >>= 1;
delta[i] = (N + half) / power;
}
while (delta[i++] != 0);
}
d)
Answer: a
Explanation: This provides a single lookup index and the values are dependent on the the number of
elements(N) in the array.
3. Given delta[4] is a global array and number of elements in the sorted array is 10, what are the values in
the delta array?
a) 4, 3, 1, 0
b) 5, 3, 1, 0
c) 4, 2, 1, 1
d) 5, 2, 1, 1
Answer: b
Explanation: Trace with respect to the make_delta function, always note that the last element is always 0.
4. Choose the appropriate code snippet that performs uniform binary search.
a)
b)
c)
d)
Answer: c
Explanation: Unlike the usual binary search which a low, high and a mid variable and every time comparing
the key with the mid value, the comparing index is obtained from the lookup delta table, choosing the left or
right side of the array is same as with the normal binary search.
Answer: b
Explanation: With every iteration we are dividing the array into two parts(though not equal halves), the
complexity remains same as the normal binary search.
Answer: b
Explanation: Tracing with the above code, comparison #1: i=4, comparison #2: i=7, comparison #3: i=8
Answer: b
Explanation: This gives a very slight improvement as you are skipping the first k elements.
Answer: d
Explanation: Linear search has O(n) complexity and Binary search has O(logn) complexity, in Jump search
you have to jump backwards only once, hence it is preferabl
1. Jump search algorithm requires which of the following condition to be true?
a) array should be sorted
b) array should have not be sorted
c) array should have a less than 64 elements
d) array should be partially sorted
Answer: a
Explanation: Jump sort requires the input array to be sorted. The algorithm would fail to give the correct
result if array is not sorted.
Answer: c
Explanation: In jump search algorithm jumps are made until element having value greater than the value of
element being searched is found. After this linear search is performed in backwards direction.
3. Which of the following step is taken after finding an element having value greater than the element being
searched?
a) linear search takes place in the forward direction
b) linear search takes place in the backward direction
c) binary search takes place in the forward direction
d) binary search takes place in a backward direction
Answer: b
Explanation: First an element having value greater than the element being searched is found. After this
linear search is performed in a backward direction.
4. How many jumps will be made in the worst case of jump search(let block jumped =k)?
a) n*k
b) n/k
c) k/n
d) n+k
Answer: b
Explanation: Worst case occurs when the value to be searched is in the last section of the array. So, in this
case the number of jumps will be n/k.
5. What will be the maximum number of comparisons that can be made in jump search algorithm (assuming
k to be blocks jumped)?
a) k
b) n/k
c) k-1
d) k-1
Answer: c
Explanation: Worst case occurs when the element being searched is present just after the element that has
been compared while making the last jump. So, in this case k-1 comparisons will have to be made.
advertisement
6. What is the value of jump taken for maximum efficiency while implementing jump search?
a) n/2
b) n2
c) n1/2
d) log n
Answer: c
Explanation: Total number of comparisons required will be n/k + k-1 in worst case. This function will be
minimum for k=n1/2. So this value of jump will be the best for implementing jump search.
Answer: d
Explanation: Jump search does not require any additional space for searching the required element. Thus its
auxiliary space requirement will be O(1).
Answer: b
Explanation: Binary search has the least time complexity (equal to log n) out of the given searching
algorithms. This makes binary search preferable in most cases.
9. In which of the following case jump search will be preferred over binary search?
a) jumping backwards takes significantly more time than jumping forward
b) jumping forward takes significantly more time than jumping backwards
c) when the given array is very large in size
d) when the given array is very small in size
Answer: a
Explanation: Jump search only needs to jump backwards once, while a binary can jump backwards up to log
n times. Thus jump search will be preferred over binary search if jumping backwards is expensive.
10. Best case of jump search will have time complexity of _________
a) O(1)
b) O(n)
c) O(log n)
d) O(n log n)
Answer: a
Explanation: Best case of jump search will be when the first element of the array is the element that is being
searched. In this case only one comparison will be required. Thus it will have a time complexity of O(1).
b)
c)
d)
12. Jump search is worse than linear search in terms of time complexity.
a) True
b) False
Answer: b
Explanation: Linear search has a time complexity of O(n) and the time complexity of jump search is O(n1/2).
So jump search is better than linear search in terms of time complexity.
Answer: b
Explanation: The time complexity of jump search is O(n1/2) in worst and average case. It is due to the fact
that size of optimal jump is n1/2.
Answer: b
Explanation: With every iteration, we divide the given array into two sub arrays(not necessarily equal).
Answer: c
Explanation: None.
b)
advertisement
public static int fibSearch(final int key, final int[] a)
{
int low = 0;
int high = a.length - 1;
int fibCurrent = 1;
int fibPrev = 1;
int N = a.length;
while (low <= high)
{
int tmp = fibCurrent + fibPrev;
fibPrev = fibCurrent;
fibCurrent = tmp;
N = N - (fibCurrent - fibPrev);
final int mid = low + (high - low) - (fibCurrent + fibPrev);
if (key < a[mid]) high = mid - 1;
else if (key > a[mid]) low = mid + 1;
else return mid;
}
return -1;
}
c)
d)
Answer: a
Explanation: Here instead of choosing middle of the array as a point of array division, we use Fibonacci
numbers, the division index are strictly between two Fibonacci numbers.
Answer: a
Explanation: Since it divides the array into two parts, although not equal, its time complexity is O(logn), it is
better than binary search in case of large arrays.
Answer: d
Explanation: When the speed of access depends on the location previously accessed, Fibonacci search is
better compared to binary search as it performs well on those locations which have lower dispersion.
Fibonacci search won’t work on unsorted arrays. The input should be a sorted array or array should be
sorted before Fibonacci search.
Answer: c
Explanation: If the step size is 1, it becomes a linear search, if it is n, we reach the end of the list in just on
step, if it is n/2, it becomes similar to binary search, therefore the most efficient step size is found to be
sqrt(n).
b)
d)
Answer: b
Explanation: After finding the correct block of k elements, a sequential search is performed in this block.
Answer: c
Explanation: Since the size of the step is sqrt(n), the complexity is also
Answer: a
Explanation: Exponential sort requires the input array to be sorted. The algorithm would fail to give the
correct result if array is not sorted.
2. Which of the following searching algorithm is used with exponential sort after finding the appropriate
range?
a) Linear search
b) Binary search
c) Jump search
d) Fibonacci Search
Answer: b
Explanation: In exponential search, we first find a range where the required elements should be present in
the array. Then we apply binary search in this range.
Answer: a
Explanation: Exponential search has neither an exponential space complexity nor exponential time
complexity. It is named exponential search because it searches for an element in an exponential manner.
4. Choose the correct while loop statement from the following that finds the range where are the element
being search is present (x is the element being searched in an array arr of size n)?
a)
b)
while (i < n && arr[i] <= x)
i = i/2;
c)
d)
while (i < n)
i = i*2;
Answer: a
Explanation: In exponential search we first find the range where the element being searched can be present
before applying binary search. We do this by comparing the value of element under search with the array
elements present at the positions 1,2,4,8….n.
advertisement
Answer: d
Explanation: In exponential search, we first find a range where the required elements should be present in
the array. Then we apply binary search in this range. This takes O(log n) time in the worst case.
6. What is the auxiliary space requirement of an exponential sort when used with iterative binary search?
a) O(n)
b) O(2n)
c) O(1)
d) O(log n)
Answer: c
Explanation: Exponential search does not require any auxiliary space for finding the element being searched.
So it has a constant auxiliary space O(1).
7. What is the auxiliary space requirement of the exponential sort when used with recursive binary search?
a) O(n)
b) O(2n)
c) O(1)
d) O(log n)
Answer: d
Explanation: Exponential search requires an auxiliary space of log n when used with recursive binary search.
This space is required for the recursion call stack space.
Answer: b
Explanation: Exponential search has the least time complexity (equal to log n) out of the given searching
algorithms. This makes exponential search preferable in most cases.
9. In which of the following case jump search will be preferred over exponential search?
a) jumping backwards takes significantly more time than jumping forward
b) jumping forward takes significantly more time than jumping backwards
c) when the given array is very large in size
d) when the given array is very small in size
Answer: a
Explanation: Jump search only needs to jump backwards once, while an exponential search can jump
backwards up to log n times. Thus jump search will be preferred if jumping backwards is expensive.
10. Best case of the exponential search will have time complexity of?
a) O(1)
b) O(n)
c) O(log n)
d) O(n log n)
Answer: a
Explanation: Best case of the exponential search will be when the first element of the array is the element
that is being searched. In this case, only one comparison will be required. Thus it will have a time
complexity of O(1).
b)
d)
Answer: a
Explanation: In exponential search we first find a range where the required element should be present in the
array. Then we apply binary search in this range.
12. Jump search has a better time complexity than the exponential search.
a) True
b) False
Answer: b
Explanation: The worst case time complexity of jump search and exponential searches are O(n1/2) and
O(log n) respectively. So exponential search is better in terms of time complexity.
13. Exponential search performs better than binary search when the element being searched is present near
the starting point of the array.
a) True
b) False
Answer: a
Explanation: Exponential search first finds the range where binary search needs to be applied. So when the
element is present near the starting point of the array then exponential search performs better than standard
binary search.
14. Choose the incorrect statement about exponential search from the following.
a) Exponential search is an in place algorithm
b) Exponential search has a greater time complexity than binary search
c) Exponential search performs better than binary search when the element being searched is present near
the starting point of the array
d) Jump search has a greater time complexity than an exponential search
Answer: b
Explanation: Time complexity of exponential search and binary search are the same. But exponential search
performs better than binary search when the element being searched is present near the starting point of the
array.
Answer: a
Explanation: Logarithmic search is not an alternate name of the exponential search. Some alternate names of
exponential sear
1. Which of the following is the most desirable condition for interpolation search?
a) array should be sorted
b) array should not be sorted but the values should be uniformly distributed
c) array should have a less than 64 elements
d) array should be sorted and the values should be uniformly distributed
Answer: d
Explanation: Desirable condition for interpolation search is that the array should be sorted and the values
should be uniformly distributed. The algorithm would fail to give the correct result if array is not sorted.
Answer: b
Explanation: Interpolation search is a variation of binary search which gives the best result when the array
has uniformly distributed values. Interpolation search goes to different positions depending on the value
being searched whereas binary search always goes to the middle element.
Answer: b
Explanation: Interpolation search is an improvement over a binary search for the case when array is sorted
and has uniformly distributed values. Binary search performs better when the values are not distributed
uniformly.
4. In which of the following case jump search performs better than interpolation search?
a) When array has uniformly distributed values but is not sorted
b) when array is sorted and has uniform distribution of values
c) when array is sorted but the values increases exponentially
d) when array is not sorted
Answer: c
Explanation: In case of non uniform distribution of values the time complexity of interpolation search is
O(n) whereas the average time complexity of jump search is O(n1/2). So in such a case jump search has a
better performance.
5. What is the time complexity of interpolation search when the input array has uniformly distributed values
and is sorted?
a) O(n)
b) O(log log n)
c) O(n log n)
d) O(log n)
Answer: b
Explanation: Interpolation search goes to different positions in the array depending on the value being
searched. It is an improvement over binary search and has a time complexity of O(log log n).
advertisement
Answer: c
Explanation: Interpolation search does not require any auxiliary space for finding the element being
searched. So it has a constant auxiliary space O(1).
7. What is the time complexity of exponential search when the input array is sorted but the values are not
uniformly distributed?
a) O(n1/2)
b) O(log log n)
c) O(n)
d) O(log n)
Answer: c
Explanation: When an array has non uniformly distributed values then in that case the algorithm of
interpolation search fails to work efficiently. As a result, it has a time complexity of O(n) in such a case.
8. Which of the following searching algorithm is fastest when the input array is sorted and has uniformly
distributed values?
a) jump search
b) exponential search
c) binary search
d) interpolation search
Answer: d
Explanation: Interpolation search has a time complexity of O( log log n) when the array is sorted and has
uniformly distributed values. It has the least time complexity out of the given options for such a case.
9. Which of the following searching algorithm is fastest when the input array is sorted but has non uniformly
distributed values?
a) jump search
b) linear search
c) binary search
d) interpolation search
Answer: c
Explanation: Interpolation search has a time complexity of O(n) when the array does not have uniformly
distributed values. So in such a case binary search has the least time complexity out of the given options.
10. Which of the following searching algorithm is fastest when the input array is not sorted but has
uniformly distributed values?
a) jump search
b) linear search
c) binary search
d) interpolation search
Answer: b
Explanation: Out of the given options linear search is the only searching algorithm which can be applied to
arrays which are not sorted. It has a time complexity of O(n) in the worst case.
Answer: a
Explanation: Interpolation search has an auxiliary space complexity of O(1). So it qualifies as an in place
algorithm.
12. Interpolation search has a better time complexity than exponential search for any given array.
a) True
b) False
Answer: b
Explanation: The worst case time complexity of interpolation search and exponential search are O(n) and
O(log n) respectively. So exponential search is better when the worst case scenario is considered.
13. What is the formula used for calculating the position in interpolation search?
(x = element being searched, A[] = input array, low and high are the leftmost and rightmost index of A[]
respectively)
a) ((x – A[low]) * (high – low)) / (A[high] – A[low])
b) high + ((x – A[low]) * (high – low)) / (A[high] – A[low])
c) low + ((x – A[low]) * (high – low)) / (A[high] – A[low])
d) x + ((x – A[low]) * (high – low)) / (A[high] – A[low])
Answer: c
Explanation: For calculating the position after each iteration in interpolation search we use the formula low
+ ((x – A[low]) * (high – low)) / (A[high] – A[low]). Then the value at the calculated position is compared
with the element being searched.
14. What are the updated values of high and low in the array if the element being searched is greater than the
value at calculated index in interpolation search? (pos = current position)
a) low = pos + 1, high remains unchanged
b) high = pos – 1, low remains unchanged
c) low = low +1, high = high – 1
d) low = pos +1, high = pos – 1
Answer: a
Explanation: When the element being searched is greater than the value at the calculated position then in
that case we update low and high remains unaltered. Updated value of low is low = pos + 1.
15. What are the updated values of high and low in the array if the element being searched is lower than the
value at calculated index in interpolation search? (pos = current position)
a) low = pos + 1, high remains unchanged
b) high = pos – 1, low remains unchanged
c) low = low +1, high = high – 1
d) low = pos +1, high = pos – 1
Answer: b
Explanation: When the elem
Answer: b
Explanation: A sub string is a subset of another string. So “FOUND” is the only possible sub string out of
the given options.
#include<bits/stdc++.h>
using namespace std;
void func(char* str2, char* str1)
{
int m = strlen(str2);
int n = strlen(str1);
for (int i = 0; i <= n - m; i++)
{
int j;
for (j = 0; j < m; j++)
if (str1[i + j] != str2[j])
break;
if (j == m)
cout << i << endl;
}
}
int main()
{
char str1[] = "1253234";
char str2[] = "323";
func(str2, str1);
return 0;
}
a) 1
b) 2
c) 3
d) 4
Answer: c
Explanation: The given code describes the naive method of finding a pattern in a string. So the output will
be 3 as the given sub string begins at that index in the pattern.
3. What will be the worst case time complexity of the following code?
advertisement
#include<bits/stdc++.h>
using namespace std;
void func(char* str2, char* str1)
{
int m = strlen(str2);
int n = strlen(str1);
for (int i = 0; i <= n - m; i++)
{
int j;
for (j = 0; j < m; j++)
if (str1[i + j] != str2[j])
break;
if (j == m)
cout << i << endl;
}
}
int main()
{
char str1[] = "1253234";
char str2[] = "323";
func(str2, str1);
return 0;
}
a) O(n)
b) O(m)
c) O(m * n)
d) O(m + n)
Answer: c
Explanation: The given code describes the naive method of pattern searching. By observing the nested loop
in the code we can say that the time complexity of the loop is O(m*n).
#include<bits/stdc++.h>
using namespace std;
void func(char* str2, char* str1)
{
int m = strlen(str2);
int n = strlen(str1);
for (int i = 0; i <= n - m; i++)
{
int j;
for (j = 0; j < m; j++)
if (str1[i + j] != str2[j])
break;
if (j == m)
cout << i << endl;
}
}
int main()
{
char str1[] = "1253234";
char str2[] = "323";
func(str2, str1);
return 0;
}
a) O(n)
b) O(1)
c) O(log n)
d) O(m)
Answer: b
Explanation: The given code describes the naive method of pattern searching. Its auxiliary space
requirement is O(1).
5. What is the worst case time complexity of KMP algorithm for pattern searching (m = length of text, n =
length of pattern)?
a) O(n)
b) O(n*m)
c) O(m)
d) O(log n)
Answer: c
Explanation: KMP algorithm is an efficient pattern searching algorithm. It has a time complexity of O(m)
where m is the length of text.
6. What will be the best case time complexity of the following code?
#include<bits/stdc++.h>
using namespace std;
void func(char* str2, char* str1)
{
int m = strlen(str2);
int n = strlen(str1);
for (int i = 0; i <= n - m; i++)
{
int j;
for (j = 0; j < m; j++)
if (str1[i + j] != str2[j])
break;
if (j == m)
cout << i << endl;
}
}
int main()
{
char str1[] = "1253234";
char str2[] = "323";
func(str2, str1);
return 0;
}
a) O(n)
b) O(m)
c) O(m * n)
d) O(m + n)
Answer: b
Explanation: The given code describes the naive method of pattern searching. The best case of the code
occurs when the first character of the pattern does not appear in the text at all. So in such a case, only one
iteration is required thus time complexity will be O(m).
7. What is the time complexity of Z algorithm for pattern searching (m = length of text, n = length of
pattern)?
a) O(n + m)
b) O(m)
c) O(n)
d) O(m * n)
Answer: a
Explanation: Z algorithm is an efficient pattern searching algorithm as it searches the pattern in linear time.
It has a time complexity of O(m + n) where m is the length of text and n is the length of the pattern.
8. What is the auxiliary space complexity of Z algorithm for pattern searching (m = length of text, n = length
of pattern)?
a) O(n + m)
b) O(m)
c) O(n)
d) O(m * n)
Answer: b
Explanation: Z algorithm is an efficient pattern searching algorithm as it searches the pattern in linear time.
It an auxiliary space of O(m) for maintaining Z array.
9. The naive pattern searching algorithm is an in place algorithm.
a) true
b) false
Answer: a
Explanation: The auxiliary space complexity required by naive pattern searching algorithm is O(1). So it
qualifies as an in place algorithm.
10. Rabin Karp algorithm and naive pattern searching algorithm have the same worst case time complexity.
a) true
b) false
Answer: a
Explanation: The worst case time complexity of Rabin Karp algorithm is O(m*n) but it has a linear average
case time complexity. So Rabin Karp and naive pattern searching algorithm have the same worst case ti
Answer: b
Explanation: An insertion algorithm consists of N-1 passes when an array of N elements is given.
Answer: a
Explanation: Insertion sort is similar to that of a binary heap algorithm because of the use of temporary
variable to swap.
Answer: d
Explanation: The average case analysis of a tight bound algorithm is mathematically achieved to be O(N2).
4. Any algorithm that sorts by exchanging adjacent elements require O(N2) on average.
a) True
b) False
Answer: a
Explanation: Each swap removes only one inversion, so O(N2) swaps are required.
Answer: a
Explanation: The total number of pairs in a list L is N(N-1)/2. Thus, an average list has half this amount, or
N(N-1)/4 inversions.
advertisement
6. What is the running time of an insertion sort algorithm if the input is pre-sorted?
a) O(N2)
b) O(N log N)
c) O(N)
d) O(M log N)
Answer: c
Explanation: If the input is pre-sorted, the running time is O(N), because the test in the inner for loop always
fails immediately and the algorithm will run quickly.
7. What will be the number of passes to sort the elements using insertion sort?
14, 12,16, 6, 3, 10
a) 6
b) 5
c) 7
d) 1
Answer: b
Explanation: The number of passes is given by N-1. Here, N=6. Therefore,
6-1=5 passes.
8. For the following question, how will the array elements look like after second pass?
34, 8, 64, 51, 32, 21
a) 8, 21, 32, 34, 51, 64
b) 8, 32, 34, 51, 64, 21
c) 8, 34, 51, 64, 32, 21
d) 8, 34, 64, 51, 32, 21
Answer: d
Explanation: After swapping elements in the second pass, the array will look like, 8, 34, 64, 51, 32, 21.
10. In C, what are the basic loops required to perform an insertion sort?
a) do- while
b) if else
c) for and while
d) for and if
Answer: c
Explanation: To perform an insertion sort, we use two basic loops- an outer for loop and an inner while loop.
11. Binary search can be used in an insertion sort algorithm to reduce the number of comparisons.
a) True
b) False
Answer: a
Explanation: Binary search can be used in an insertion sort algorithm to reduce the number of comparisons.
This is called a Binary insertion sort.
12. Which of the following options contain the correct feature of an insertion sort algorithm?
a) anti-adaptive
b) dependable
c) stable, not in-place
d) stable, adaptive
Answer: d
Explanation: An insertion sort is stable, adaptive, in-place and incremental in nature.
13. Which of the following sorting algorithms is the fastest for sorting small arrays?
a) Quick sort
b) Insertion sort
c) Shell sort
d) Heap sort
Answer: b
Explanation: For sorting small arrays, insertion sort runs even faster than quick sort. But, it is impractical to
sort large arrays.
14. For the best case input, the running time of an insertion sort algorithm is?
a) Linear
b) Binary
c) Quadratic
d) Depends on the input
Answer: a
Explanation: The best case input for an insertion sort algorithm runs in linear time and is given by O(N).
15. Which of the following examples represent the worst case input for an insertion sort?
a) array in sorted order
b) array sorted in reverse order
c) normal unsorted array
d) large array
Answer: b
Explanation: The worst case input for an insertion sort algorithm will be an array sorted in reverse order and
its running time is qu
Answer: a
Explanation: During insertion sort, the relative order of elements is not changed. Therefore, it is a stable
sorting algorithm. And insertion sort requires only O(1) of additional memory space. Therefore, it sorts In-
place.
2. Which of the following sorting algorithm is best suited if the elements are already sorted?
a) Heap Sort
b) Quick Sort
c) Insertion Sort
d) Merge Sort
Answer: c
Explanation: The best case running time of the insertion sort is O(n). The best case occurs when the input
array is already sorted. As the elements are already sorted, only one comparison is made on each pass, so
that the time required is O(n).
3. The worst case time complexity of insertion sort is O(n2). What will be the worst case time complexity of
insertion sort if the correct position for inserting element is calculated using binary search?
a) O(nlogn)
b) O(n2)
c) O(n)
d) O(logn)
Answer: b
Explanation: The use of binary search reduces the time of finding the correct position from O(n) to O(logn).
But the worst case of insertion sort remains O(n2) because of the series of swapping operations required for
each insertion.
Answer: a
Explanation: In the incremental algorithms, the complicated structure on n items is built by first building it
on n − 1 items. And then we make the necessary changes to fix things in adding the last item. Insertion sort
builds the sorted sequence one element at a time. Therefore, it is an example of an incremental algorithm.
advertisement
void insertionSort(int arr[], int array_size)
{
int i, j, value;
for (i = 1; i < array_size; i++)
{
value = arr[i];
j = i;
while (________ )
{
arr[j] = arr[j − 1];
j = j − 1;
}
arr[j] = value;
}
}
Answer: b
Explanation: In insertion sort, the element is A[j] is inserted into the correct position in the sorted sequence
A[1… j – 1]. So, condition given in (j > 0) && (arr[j − 1] > value) will implement while loop correctly.
6. Which of the following is good for sorting arrays having less than 100 elements?
a) Quick Sort
b) Selection Sort
c) Merge Sort
d) Insertion Sort
Answer: d
Explanation: The insertion sort is good for sorting small arrays. It sorts smaller arrays faster than any other
sorting algorithm.
7. Consider an array of length 5, arr[5] = {9,7,4,2,1}. What are the steps of insertions done while running
insertion sort on the array?
a) 7 9 4 2 1 4 7 9 2 1 2 4 7 9 1 1 2 4 7 9
b) 9 7 4 1 2 9 7 1 2 4 9 1 2 4 7 1 2 4 7 9
c) 7 4 2 1 9 4 2 1 9 7 2 1 9 7 4 1 9 7 4 2
d) 7 9 4 2 1 2 4 7 9 1 4 7 9 2 1 1 2 4 7 9
Answer: a
Explanation: The steps performed while running insertion sort on given array are:
Initial : 9 7 4 2 1 key = 7
7 9 4 2 1 key = 4
4 7 9 2 1 key = 2
2 4 7 9 1 key = 1
1 2 4 7 9
In each step, the key is the element that is compared with the elements present at the left side to it.
8. Statement 1: In insertion sort, after m passes through the array, the first m elements are in sorted order.
Statement 2: And these elements are the m smallest elements in the array.
a) Both the statements are true
b) Statement 1 is true but statement 2 is false
c) Statement 1 is false but statement 2 is true
d) Both the statements are false
Answer: b
Explanation: In insertion sort, after m passes through the array, the first m elements are in sorted order but
they are whatever the first m elements were in the unsorted array.
9. In insertion sort, the average number of comparisons required to place the 7th element into its correct
position is ____
a) 9
b) 4
c) 7
d) 14
Answer: b
Explanation: On average (k + 1) / 2 comparisons are required to place the kth element into its correct
position. Therefore, average number of comparisons required for 7th element = (7 + 1)/2 = 4.
Answer: d
Explanation: In Exchange sorts, we compare each element of an array and swap those elements that are not
in their prope
Answer: a
Explanation: Auxiliary memory is required for storing the data temporarily.
Answer: c
Explanation: Selection is based on keys, hence a file with large values and small keys can be efficiently
sorted with selection sort.
Answer: d
Explanation: Selection sort creates a sub-list, LHS of the ‘min’ element is already sorted and RHS is yet to
be sorted. Starting with the first element the ‘min’ element moves towards the final element.
int min;
for(int j=0; j<arr.length-1; j++)
{
min = j;
for(int k=j+1; k<=arr.length-1; k++)
{
if(arr[k] < arr[min])
min = k;
}
int temp = arr[min];
arr[min] = arr[j];
arr[j] = temp;
}
b)
advertisement
int min;
for(int j=0; j<arr.length-1; j++)
{
min = j;
for(int k=j+1; k<=arr.length; k++)
{
if(arr[k] < arr[min])
min = k;
}
int temp = arr[min];
arr[min] = arr[j];
arr[j] = temp;
}
c)
int min;
for(int j=0; j<arr.length-1; j++)
{
min = j;
for(int k=j+1; k<=arr.length-1; k++)
{
if(arr[k] > arr[min])
min = k;
}
int temp = arr[min];
arr[min] = arr[j];
arr[j] = temp;
}
d)
int min;
for(int j=0; j<arr.length-1; j++)
{
min = j;
for(int k=j+1; k<=arr.length; k++)
{
if(arr[k] > arr[min])
min = k;
}
int temp = arr[min];
arr[min] = arr[j];
arr[j] = temp;
}
Answer: a
Explanation: Starting with the first element as ‘min’ element, selection sort loops through the list to select
the least element which is then swapped with the ‘min’ element.
Answer: a
Explanation: Since selection sort is an in-place sorting algorithm, it does not require additional storage.
Answer: d
Explanation: In the average case, even if the input is partially sorted, selection sort behaves as if the entire
array is not sorted. Selection sort is insensitive to input.
Answer: b
Explanation: As the input size increases, the performance of selection sort decreases.
8. The given array is arr = {3,4,5,2,1}. The number of iterations in bubble sort and selection sort
respectively are __________
a) 5 and 4
b) 4 and 5
c) 2 and 4
d) 2 and 5
Answer: a
Explanation: Since the input array is not sorted, bubble sort takes 5 iterations and selection sort takes 4(n-1)
iterations.
9. The given array is arr = {1,2,3,4,5}. (bubble sort is implemented with a flag variable)The number of
iterations in selection sort and bubble sort respectively are __________
a) 5 and 4
b) 1 and 4
c) 0 and 4
d) 4 and 1
Answer: d
Explanation: Selection sort is insensitive to input, hence 4(n-1) iterations. Whereas bubble sort iterates only
once to set the flag to 0 as the input is already sorted.
Answer: d
Explanation: The best, average and worst case complexities of selection sort is O(n2).
(n-1) + (n-2) + (n-3)
Answer: a
Explanation: As the name suggests, external sorting algorithm uses external memory like tape or disk.
Answer: b
Explanation: As the name suggests, internal sorting algorithm uses internal main memory.
3. What is the worst case complexity of bubble sort?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)
Answer: d
Explanation: Bubble sort works by starting from the first element and swapping the elements if required in
each iteration.
b)
c)
advertisement
for(int j=arr.length; j>=0; j--)
{
for(int k=0; k<j; k++)
{
if(arr[k] > arr[k+1])
{
int temp = arr[k];
arr[k] = arr[k+1];
arr[k+1] = temp;
}
}
}
d)
Answer: a
Explanation: The outer loop keeps count of number of iterations, and the inner loop checks to see if
swapping is necessary.
Answer: d
Explanation: Bubble sort works by starting from the first element and swapping the elements if required in
each iteration even in the average case.
6. Which of the following is not an advantage of optimised bubble sort over other sorting techniques in case
of sorted elements?
a) It is faster
b) Consumes less memory
c) Detects whether the input is already sorted
d) Consumes less time
Answer: c
Explanation: Optimised Bubble sort is one of the simplest sorting techniques and perhaps the only advantage
it has over other techniques is that it can detect whether the input is already sorted. It is faster than other in
case of sorted array and consumes less time to describe whether the input array is sorted or not. It consumes
same memory than other sorting techniques. Hence it is not an advantage.
7. The given array is arr = {1, 2, 4, 3}. Bubble sort is used to sort the array elements. How many iterations
will be done to sort the array?
a) 4
b) 2
c) 1
d) 0
Answer: a
Explanation: Even though the first two elements are already sorted, bubble sort needs 4 iterations to sort the
given array.
8. How can you improve the best case efficiency in bubble sort? (The input is already sorted)
a)
boolean swapped = false;
for(int j=arr.length-1; j>=0 && swapped; j--)
{
swapped = true;
for(int k=0; k<j; k++)
{
if(arr[k] > arr[k+1])
{
int temp = arr[k];
arr[k] = arr[k+1];
arr[k+1] = temp;
swapped = false;
}
}
}
b)
c)
d)
Answer: c
Explanation: A boolean variable ‘swapped’ determines whether any swapping has happened in a particular
iteration, if no swapping has occurred, then the given array is sorted and no more iterations are required.
9. What is the best case efficiency of bubble sort in the improvised version?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)
Answer: c
Explanation: Some iterations can be skipped if the list is sorted, hence efficiency improves to O(n).
10. The given array is arr = {1,2,4,3}. Bubble sort is used to sort the array elements. How many iterations
will be done to sort the array with improvised version?
a) 4
b) 2
c) 1
d) 0
Answer: b
Explanation: Only 2 e
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.
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).
advertisement
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
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
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.
13. Merge sort is preferred for arrays over linked lists.
a) true
b) false
Answer: b
Explanation: Merge sort is preferred for linked list over arrays. It is because in a linked list the insert
operation takes only O(1) time and space which implies that we can implement merge operation in constant
time.
14. Which of the following sorting algorithm makes use of merge sort?
a) tim sort
b) intro sort
c) bogo sort
d) quick sort
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)
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
Answer: d
Explanation: Bottom
Answer: c
Explanation: Merge sort uses the technique of divide and conquer in order to sort a given array. It divides
the array into two halves and apply merge sort algorithm to each half individually after which the sorted
versions of these halves are merged together.
Answer: c
Explanation: The merging of two sorted arrays requires an additional space of n due to which the auxiliary
space requirement of merge sort is O(n). Thus merge sort is not an in place sorting algorithm.
Answer: c
Explanation: Space complexity of in place version of merge sort is O(log n) which is used for storing call
stack formed due to recursion. Note that the algorithms with space complexity as O(log n) also qualifies as
in place algorithms as the value of log n is close to 1.
5. What is the average time complexity of in place merge sort when we use the following function for
merging?
advertisement
void in_place_merge(int arr[], int l, int middle, int r)
{
int start2 = middle + 1;
if (arr[middle] <= arr[start2])
{
return;
}
while (l <= middle && start2 <= r)
{
if (arr[l] <= arr[start2])
{
l++;
}
else
{
int val = arr[start2];
int index = start2;
while (index != l)
{
arr[index] = arr[index - 1];
index--;
}
arr[l] = val;
l++;
middle++;
start2++;
}
}
}
a) O(n log n)
b) O(n2)
c) O(n2 log n)
d) O(n log n2)
Answer: b
Explanation: The merge function in the in place merge sort takes O(n2) time so the recurrence relation
becomes T(n)=2T(n/2)+n2. This can be solved using master’s theorem and is found equal to O(n2).
Answer: a
Explanation: Merge sort implements sorting by merging the sorted versions of smaller parts of the array.
Thus its method of sorting is called merging.
7. In place merge sort has same time complexity as standard merge sort.
a) true
b) false
Answer: b
Explanation: In place version of merge sort has a greater time complexity as compared to its standard
version. It is because the merging in in-place merge sort takes place in O(n2) time whereas in standard
version it takes O(n) time.
Answer: a
Explanation: In-place merge sort like standard merge sort is a stable sort. This implies that the relative
position of equal valued elements in the input and sorted array remain same.
9. Choose the incorrect statement about merge sort from the following?
a) both standard merge sort and in-place merge sort are stable
b) standard merge sort has greater time complexity than in-place merge sort
c) standard merge sort has greater space complexity than in-place merge sort
d) in place merge sort has O(log n) space complexity
Answer: b
Explanation: Time complexity of standard merge sort is O(n log n) and that of in-place merge sort is O(n2).
So the time complexity of in-place merge sort is more than that of standard merge sort.
10. Choose the correct function from the following that implements merging in in-place merge sort.
a)
b)
c)
d)
Answer: b
Explanatio
Answer: c
Explanation: Merge sort uses the technique of divide and conquer in order to sort a given array. It divides
the array into two halves and applies merge sort algorithm to each half individually after which the sorted
versions of these halves are merged together.
Answer: a
Explanation: The recurrence relation for merge sort is given by T(n) = 2T(n/2) + n. This can be solved using
master’s theorem and is found equal to O(n log n).
Answer: c
Explanation: The merging of two sorted arrays requires an additional space of n due to which the auxiliary
space requirement of merge sort is O(n). Thus merge sort is not an in place sorting algorithm.
Answer: b
Explanation: The auxiliary space complexity of bottom up merge sort is same as standard merge sort as both
uses the same algorithm for merging the sorted arrays which takes o(n) space. But bottom up merge sort
does not need to maintain a call stack.
Answer: a
Explanation: The merge function in the bottom up merge sort takes O(n) time which is placed inside the for
loop. The loop runs for O(log n) time, thus the overall time complexity of the code becomes O(n log n).
advertisement
Answer: a
Explanation: Merge sort implements sorting by merging the sorted versions of smaller parts of the array.
Thus its method of sorting is called merging.
Answer: b
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: a
Explanation: Bottom up merge sort like standard merge sort is a stable sort. This implies that the relative
position of equal valued elements in the input and sorted array remain same.
9. Choose the correct statement about bottom up merge sort from the following?
a) bottom up merge sort has greater time complexity than standard merge sort
b) bottom up merge sort has lesser time complexity than standard merge sort
c) bottom up merge sort saves auxiliary space required on call stack
d) bottom up merge sort uses recursion.
Answer: c
Explanation: Bottom up merge sort unlike standard merge sort uses an iterative algorithm for sorting. Thus,
it saves auxiliary space required by the call stack.
10. Choose the correct option from the following that represents bottom up merge sort function?
a)
b)
void mergesort(int Arr[], int temp[], int low, int high)
{
for (int m = 1; m <= high - low; m = 2*m)
{
for (int i = low; i < high; i += m)
{
int left = i;
int mid = i + m - 1;
int right = min(i + 2*m - 1, high);
merge(Arr, temp, left, mid, right);
}
}
}
c)
d)
Answer: a
Explanation: Bottom up merge
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).
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
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
Answer: d
Explanation: Left element=8, right element=0,
Centre=[position(left+right)/2]=6.
advertisement
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
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
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
Answer: b
Explanation: A good cut-off range is anywhere between N=5 and N=20 to avoid nasty degenerate cases.
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
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
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.
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.
advertisement
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
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
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
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
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 seq
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)
advertisement
public static void quickSort(int[] arr, int low, int high)
{
int pivot;
if(high>low)
{
pivot = partition(arr, low, high);
quickSort(arr, low, pivot);
quickSort(arr, pivot+2, high);
}
}
Answer: a
Explanation: Based on the pivot returned by the call to partition, recursive calls to quickSort sort the given
array.
Answer: d
Explanation: When the input array is already sorted.
b)
c)
d)
Answer: b
Explanation: The array is partitioned such that the elements left to the pivot are lesser than the pivot while
the elements right of the pivot are greater than the pivot.
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
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
Answer: d
Explanation: There is only one pivot with which the array will be sorted, the pivot is 1.
Answer: b
Explanation: Onc
Answer: c
Explanation: Quick sort uses the technique of divide and conquer in order to sort a given array. It divides the
array into two parts about the pivot and then apply a quick sort to both the parts.
2. What is a randomized quick sort?
a) quick sort with random partitions
b) quick sort with random choice of pivot
c) quick sort with random output
d) quick sort with random input
Answer: b
Explanation: Randomized quick sort chooses a random element as a pivot. It is done so as to avoid the worst
case of quick sort in which the input array is already sorted.
3. What is the purpose of using randomized quick sort over standard quick sort?
a) so as to avoid worst case time complexity
b) so as to avoid worst case space complexity
c) to improve accuracy of output
d) to improve average case time complexity
Answer: a
Explanation: Randomized quick sort helps in avoiding the worst case time complexity of O(n2) which
occurs in case when the input array is already sorted. However the average case and best case time
complexities remain unaltered.
Answer: c
Explanation: Auxiliary space complexity of randomized quick sort is O(log n) which is used for storing call
stack formed due to recursion. Note that the algorithms with space complexity as O(log n) also qualifies as
in place algorithms as the value of log n is close to 1.
Answer: a
Explanation: The average case time complexity of randomized quick sort is same as that of standard quick
sort as randomized quick sort only helps in preventing the worst case. It is equal to O(n log n).
advertisement
Answer: a
Explanation: In-place algorithms requires constant or very less auxiliary space. Quick sort qualifies as an in
place sorting algorithm as it has a very low auxiliary space requirement of O(log n).
Answer: b
Explanation: Randomized quick sort like standard quick sort is also not a stable sorting algorithm. It is
because the elements with the same values are not guaranteed to appear in the same relative order in the
output sorted array.
Answer: b
Explanation: Best case time complexity is given in the case when there is equal partitioning of the array
about the pivot. It is given by the relation T(n) = 2T(n/2) + n which gives the result O(n log n).
Answer: d
Explanation: Randomized quick sort prevents the worst case complexity of O(n2) in most of the cases. But in
some rare cases the time complexity can become O(n2). The probability of such a case is however very low.
b)
void partition_random(int arr[], int low, int high)
{
srand(time(NULL));
int random = high + rand() % (high - low);
swap(arr[random], arr[high]);
}
c)
d)
Answer: a
Explanation: For generating unique random numbers every time we use srand(time(NULL)). Then after
generating the random index we swap the value of element at the random index with the element at last
index.
Answer: c
Explanation: Ran
Answer: c
Explanation: Quick sort uses the technique of divide and conquer in order to sort a given array. It divides the
array into two parts about the pivot and then applies quick sort to both the parts.
Answer: d
Explanation: In the median of three technique the median of first, last and middle element is chosen as the
pivot. It is done so as to avoid the worst case of quick sort in which the time complexity shoots to O(n2).
3. What is the purpose of using a median of three quick sort over standard quick sort?
a) so as to avoid worst case time complexity
b) so as to avoid worst case space complexity
c) to improve accuracy of output
d) to improve average case time complexity
Answer: a
Explanation: Median of three quick sort helps in avoiding the worst case time complexity of O(n2) which
occurs in case when the input array is already sorted. However, the average case and best case time
complexities remain unaltered.
Answer: c
Explanation: Auxiliary space complexity of median of three quick sort is O(log n) which is used for storing
call stack formed due to recursion. Note that the algorithms with space complexity as O(log n) also qualifies
as in place algorithms as the value of log n is close to 1.
5. What is the average time complexity of the median of three quick sort?
a) O(n log n)
b) O(n2)
c) O(n2 log n)
d) O(n log n2)
Answer: a
Explanation: The average case time complexity of median of three quick sort is the same as that of a
standard quick sort as randomized quick sort only helps in preventing the worst case. It is equal to O(n log
n).
advertisement
Answer: b
Explanation: Quick sort makes partitions of the input array about the pivot in order to implement sorting.
Thus its method of sorting is called partitioning.
7. Median of three quick sort is an in place sort.
a) true
b) false
Answer: a
Explanation: In-place algorithms require constant or very less auxiliary space. Median of three quick sort
qualifies as an in-place sorting algorithm. It has a very low auxiliary space requirement of O(log n).
Answer: b
Explanation: Median of three quick sort like standard quick sort is also not a stable sorting algorithm. It is
because the elements with the same values are not guaranteed to appear in the same relative order in the
output sorted array.
9. What is the best case time complexity Median of three quick sort?
a) O(log n)
b) O(n log n)
c) O(n2)
d) O(n2 log n)
Answer: b
Explanation: Best case time complexity is given in the case when there is equal partitioning of the array
about the pivot. It is given by the relation T(n) = 2T(n/2) + n which gives the result O(n log n).
10. Which of the following function chooses a random index as the pivot?
a)
b)
d)
Answer: a
Explanation: In the median of three quick sort the median of first, last and middle element is chosen. Then
the chosen element is taken as a pivot. This helps in avoiding the worst case of O(n2).
11. What will be the pivot for the array arr={8,2,4,9} for making the first partition when a median of three
quick sort is implemented?
a) 8
b) 2
c) 4
d) 9
Answer: a
Explanation: While making the first partition the first, last and middle elements will be 8, 9 and 2
respectively. Thu
Answer: a
Explanation: The other name for a shell sort algorithm is diminishing decrement sort as the distance between
comparisons decreases as the algorithm runs until the last phase.
2. The worst case running time of shell sort, using Shell’s increments is?
a) O(N)
b) O(N log N)
c) O(log N)
d) O(N2)
Answer: d
Explanation: The lower bound of a shell sort algorithm is mathematically found to be O(N2).
Answer: b
Explanation: Shell sort algorithm is invented by Donald shell. Merge sort is invented by John Von
Neumann. Quick sort is invented by Tony Hoare.
4. Shell sort algorithm is the first algorithm to break the quadratic time barrier.
a) True
b) False
Answer: a
Explanation: Shell sort broke the quadratic time barrier as it works by comparing elements that are distant.
Answer: b
Explanation: Shell sort is an example of internal sorting because sorting of elements is done internally using
an array.
advertisement
6. Shell sort uses a sequence called a incrementing sequence to sort the elements.
a) True
b) False
Answer: a
Explanation: Shell sort uses an increment sequence h1, h2, h3… and this sequence will work as long as
h1=1.
Answer: a
Explanation: Shell sort is an extension of insertion sort because it swaps elements at far distances and at a
faster rate.
Answer: c
Explanation: The general strategy to hk sort is for each position, i, in hk,, hk+1,…., N-1, place the element
in the correct spot among i, i-hk,i-2hk, etc.
10. Which of the following statements is the basic for loop for a shell sort algorithm?
a) for(increment=N/2;increment>0;increment/=2)
b) for(i=1;i<n;i++)
c) for(i=n/2;i>=0;i- -)
d) for(i=0;i< n;i++;numelements- -)
Answer: a
Explanation: for(increment=N/2;increment>0;increment/=2) represents shell sort, for(i=1;i<n;i++)
represents insertion sort, for(i=n/2;i>=0;I- -) represents heap sort, for(i=0;i<n;i++;numelements- -) merge
sort.
11. On how many increment sequences does the worst case analysis of shell sort depends?
a) one
b) two
c) three
d) four
Answer: c
Explanation: The worst case analysis of shell sort depends on two increment sequences- using Shell’s
increments, Sedgewick’s and Hibbard’s increments.
12. What is the worst case running time of shell sort using Hibbard’s increments?
a) O(N)
b) O(N2)
c) O(N1/2)
d) O(N3/2)
Answer: d
Explanation: Mathematically, the lower bound analysis for shell sort using Hibbard’s increments is O(N3/2).
Answer: b
Explanation: Shell’s increments are of the form 1,3,7,….,2k-1. The key difference is that the consecutive
elements have no common factors.
14. What is the worst case analysis of shell sort using Shell’s increments?
a) O(N)
b) O(N2)
c) O(N1/2)
d) O(N3/2)
Answer: b
Explanation: The worst case analysis is mathematically found to be O(N2). The proof is rather complicated.
15. What is the worst case analysis of Shell sort using Sedgewick’s increments?
a) O(N2)
b) O(N3/2)
c) O(N4/3)
d) O(N5/4)
Answer: c
Explanation: The wo
Answer: b
Explanation: Shell sort is also known as diminishing increment sort since each pass is defined by an
increment h such that only the records which are h units apart will be sorted.
3. Shell sort is applied on the elements 27 59 49 37 15 90 81 39 and the chosen decreasing sequence of
increments is (5,3,1). The result after the first iteration will be
a) 27 59 49 37 15 90 81 39
b) 27 59 37 49 15 90 81 39
c) 27 59 39 37 15 90 81 49
d) 15 59 49 37 27 90 81 39
Answer: c
Explanation: Given elements 27 59 49 37 15 90 81 39,
First Iteration (span = 5):
4. Consider the following code snippet, which implements the Shell sort algorithm.
Answer: d
Explanation: In Shell sort, for increment = h we sort the sub-arrays that start at arbitrary element and include
every hth element.
So, if h = 4 the algorithms sorts:
Sub-array formed with elements at positions 1, 5, 9, 13 … in original array
Sub-array formed with elements at positions 2, 6, 10, 14 … in original array
Sub-array formed with elements at positions 3, 7, 11, 15 … in original array
Sub-array formed with elements at positions 4, 8, 12, 16 … in original array
Therefore, the condition given in option k >= span && y < elements[k- span] will implement while loop
correctly.
advertisement
Answer: a
Explanation: Shell sort is an improvement on insertion sort that allows the exchange of elements that are far
apart. Shell sort algorithm sorts separate sub-arrays of the original input array. These sub-arrays contains
every hth element of the original array.
Answer: d
Explanation: An array that is 7-sorted, becomes 7-ordered. And an array that is 5-sorted, becomes 5-ordered.
If k-ordered array is h-sorted, it remains k-ordered. Thus, an array that is first 7-sorted, then 5-sorted
becomes both 7-ordered and 5-ordered.
7. If Hibbard increments (h1= 1, h2= 3, h3= 7, …, hk = 2k–1) are used in a Shell sort implementation, then
the best case time complexity will be ________
a) O(nlogn)
b) O(n)
c) O(n2)
d) O(logn)
Answer: a
Explanation: The best case occurs when the array is already sorted. In best case the number of comparison
for each of the increments-based insertion sorts is equal to length of array.
Here 2k –1 < n, where n is the number of records. So k < log(n+1), thus the sorting time in best case is less
the n * log(n+1). Therefore best case time complexity is O(nlogn).
8. Records R1, R2, R3,.. RN with keys K1, K2, K3,.. KN are said to be h-ordered, if ________
a) Ki <= Ki+h for 1<= i*h <= N
b) Kh <= Ki+h for 1<= i <= N
c) Ki <= Kh for 1<= i <= h
d) Ki <= Ki+h for 1<= i <= N-h
Answer: d
Explanation: Records are h-ordered if every hth element (starting anywhere) yields a sorted array. Therefore,
given records with keys K1, K2, K3,.. KN are said to be h-ordered, if Ki <= Ki+h for 1<= i <= N-h.
9. Shell sort is more efficient than insertion sort if the length of input arrays is small.
a) True
b) False
Answer: b
Explanation: Insertion sort is more efficient than Shell sort if the length of array is small because insertion
sort is quite simple to program and involve very few actions other than comparisons and replacements on
each pass.
Answer: a
Explanation: Bot
Answer: c
Explanation: Heap sort is based on the algorithm of priority queue and it gives the best sorting time.
Answer: a
Explanation: The basic strategy is to build a binary heap of N elements which takes O(N) time.
Answer: b
Explanation: Heap sort is slower than Shell sort because Shell sort uses Sedgewick’s increment sequence.
4. Consider the following heap after buildheap phase. What will be its corresponding array?
a) 26,53,41,97,58,59,31
b) 26,31,41,53,58,59,97
c) 26,41,53,97,31,58,59
d) 97,53,59,26,41,58,31
Answer: d
Explanation: Constructing a max heap using the elements 97,53,59,26,41,58,31 will cause the heap to look
like that.
5. In what position does the array for heap sort contains data?
a) 0
b) 1
c) -1
d) anywhere in the array
Answer: a
Explanation: The array for heap sort contains data at position 0 whereas for a binary heap, array begins at 1.
This is the reason for its complexity.
advertisement
6. In heap sort, after deleting the last minimum element, the array will contain elements in?
a) increasing sorting order
b) decreasing sorting order
c) tree inorder
d) tree preorder
Answer: b
Explanation: By logic, after deleting minimum element, the heap will contain elements in decreasing sorting
order. We can change this by altering the ordering property.
Answer: b
Explanation: The total running time of a heap sort algorithm is mathematically found to be O(N log N).
8. How many arrays are required to perform deletion operation in a heap?
a) 1
b) 2
c) 3
d) 4
Answer: b
Explanation: To perform deletion operation in a heap, we require 2 arrays and that occupies extra memory
space and hence increase in running time.
Answer: c
Explanation: The time taken to perform a deletion of a minimum element is mathematically found to be
O( log N).
Answer: a
Explanation: Heap sort uses fewer comparisons than other sorting algorithms and hence it is an extremely
stable algorithm.
11. What is the average number of comparisons used in a heap sort algorithm?
a) N log N-O(N)
b) O(N log N)-O(N)
c) O(N log N)-1
d) 2N log N + O(N)
Answer: d
Explanation: The average number of comparisons in a heapsort algorithm is mathematically found to be 2N
log N + O(N).
12. What is the time taken to copy elements to and from two arrays created for deletion?
a) O(N)
b) O(N log N)
c) O(log N)
d) O(N2)
Answer: a
Explanation: The time taken to copy elements to and from the main array and extra array is found to be
O(N).
13. What is the average number of comparisons used to heap sort a random permutation of N distinct items?
a) 2N log N-O(N)
b) 2N log N-O(N log N)
c) 2N log N-O(N log log N)
d) 2N log N-O(log N)
Answer: c
Explanation: According to
Answer: b
Explanation: Heap sort is an implementation of selection sort using the input array as a heap representing a
descending priority queue. Heap sort algorithm is divided into two phase. In first phase the max-heap is
created and the second phase (selection phase) deletes the elements from the priority queue using siftdown
operation.
Answer: c
Explanation: Heap sort is a comparison based sorting algorithm and has time complexity O(nlogn) in the
average case. Heap sort is an in-place algorithm as it needs O(1) of auxiliary space. Heap sort uses heap and
operations on heap can change the relative order of items with the same key values. Therefore, Heap sort is
not a stable sort.
3. The essential part of Heap sort is construction of max-heap. Consider the tree shown below, the node 24
violates the max-heap property. Once heapify procedure is applied to it, which position will it be in?
a) 4
b) 5
c) 8
d) 9
Answer: d
Explanation: In max-heap element at each node is smaller than or equal to the element at its parent node. On
applying the heapify procedure on item at position 2, it will be in position 9 as shown below.
Answer: c
Explanation: The max-heap is also known as descending heap. Max-heap of size n is an almost complete
binary tree of n nodes such that the element at each node is less than or equal to the element at its parent
node.
Answer: a
Explanation: In Heap sort, the call to procedure build_Max-heap takes O(n) time and each of O(n) calls to
the function max_Heapify takes O(logn) time. So the worst case complexity of Heap sort is O(nlogn).
advertisement
6. In average case Heap sort is as efficient as the Quick sort.
a) True
b) False
Answer: b
Explanation: Quick sort is more efficient than Heap sort because experiments indicate that Heap sort
requires twice as much time as Quick sort for randomly sorted input.
7. Choose the correct option to fill? X so that the code given below implements the Heap sort.
#include <stdio.h>
void heapify(int arr[], int n, int i)
{
int largest = i; // Initialize largest as root
int l = 2*i + 1; // left = 2*i + 1
int r = 2*i + 2; // right = 2*i + 2
if (l < n && arr[l] > arr[largest])
largest = l;
if (r < n && arr[r] > arr[largest])
largest = r;
if (largest != i)
{
swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}
void heapSort(int arr[], int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
for (int i=n-1; i>=0; i--)
{
X;
heapify(arr, i, 0);
}
}
void printArray(int arr[], int n)
{
for (int i=0; i<n; ++i)
printf(“%d”,arr[i]);
printf(“\n”);
}
int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr)/sizeof(arr[0]);
heapSort(arr, n);
printf(“Sorted array is \n");
printArray(arr, n);
}
a) swap(arr[0], arr[n])
b) swap(arr[i], arr[n])
c) swap(arr[0], arr[i])
d) swap(arr[i], arr[2*i])
Answer: c
Explanation: Steps in heap sort are : (i) Build the max-heap, (ii) Swap the root element with the last element
of the heap, (iii) Reduce the size of heap by 1 and heapify the root element, (iv) Repeat the steps form step
number (v) until all the elements are sorted. Therefore the correct option is swap(arr[0], arr[i]).
8. Which one of the following is a variation of Heap sort?
a) Comb sort
b) Smooth sort
c) Binary tree sort
d) Shell sort
Answer: b
Explanation: Smooth sort is a variation of Heap sort. Smooth sort has O(nlogn) worst case time complexity
like Heap sort. But Smooth sort takes O(n) time to sort the nearly sorted input array.
Answer: a
Explanation: Introsort is a hybrid sorting algorithm that combines Quick sort and Heap sort to retain
advantages of both. It has worst case speed of Heap sort and average case speed of Quick sort.
10. How many elements can be sorted in O(logn) time using Heap sort?
a) O(1)
b) O(n/2)
c) O(logn/log(logn))
d) O(logn)
Answer: c
Explanation: The time complexity of Heap sort is O(klogk) for k input elements,
for k = logn/log(logn),
O(klogk) = O(logn/log(logn) * log(logn/log(logn)))
∴ O(klogk) = O(l
Answer: b
Explanation: Introsort is the in built sorting algorithm used by C++. It is an example of a hybrid sorting
algorithm which means it uses more than one sorting algorithm as a routine.
3. Introsort begins sorting the given array by using which of the following sorting algorithm?
a) selection sort
b) quick sort
c) insertion sort
d) heap sort
Answer: b
Explanation: Introsort begins sorting any given array by using quick sort. Then it may switch to heap sort or
insertion sort or may stick to quick sort depending upon the size of the partition.
Answer: a
Explanation: Out of the given options introsort is the only algorithm which is not stable. As it may use quick
sort in some case to perform sorting which is itself not stable. Thus stability of introsort is not guaranteed.
Answer: a
Explanation: Introsort may use quick sort or heap sort or insertion sort internally in order to sort the given
input. All of the three algorithms are in place, thus making introsort to be an in-place sorting algorithm.
Answer: a
Explanation: Quicksort, heap sort and insertion sort are comparison based sorts. Thus overall introsort also
becomes a comparison based sort.
Answer: b
Explanation: Worst case time complexity of quicksort is avoided when we implement introsort. Introsort
switches to heap sort when there is a possibility of crossing the maximum depth limit.
Answer: b
Explanation: Average time complexity of introsort remains to be O(n log n) as for most of the cases quick
sort and heap sort are used which have O(n log n) time complexity for an average case.
Answer: d
Explanation: Introsort is a hybrid of quick sort, heap sort and insertion sort. So like quick sort it may use
O(log n) auxiliary space in the stack to store call statements.
11. Why is heap sort preferred over merge sort for introsort implementation?
a) Because heap sort is faster
b) Because heap sort requires less space
c) Because heap sort is easy to implement
d) Because heap sort is easy to understand
Answer: b
Explanation: Both heap sort and merge sort have the same time complexity. But heap sort is an in-place
sorting algorithm whereas merge sort requires O(n) auxiliary space which makes heap sort a more preferable
option.
12. Why is insertion sort preferred over other sorting algorithms (like selection sort, bubble sort etc.) for
introsort implementation?
a) Because insertion sort is faster and adaptive
b) Because insertion sort requires less space
c) Because insertion sort is easy to implement
d) Because insertion sort is easy to understand
Answer: a
Explanation: When small arrays need to be sorted then insertion sort proves to be the best choice. Also it is
adaptive so it performs better than others when the given array is fully/partially sorted.
13. What is the cut-off for switching from quick sort to insertion sort in the implementation of introsort?
a) 4
b) 8
c) 16
d) 32
Answer: c
Explanation: When small arrays needs to be sorted then insertion sort proves to be the best choice. So when
the size of the partition is less than 16 introsort switches to insertion sort. This particular value has been
deduced experimentally.
14. What is the cut-off for switching from quick sort to heap sort in the implementation of introsort?
a) 16
b) n2
c) n log(n)
d) 2 log (n)
Answer: d
Explanation: Quicksort has a worst case time complexity of O(n2) which is not preferable. So in order to
avoid worst case of quicksort, introsort switches to heap sort when the depth is greater than 2 log(n). This
particular value has been deduced experimentally.
15. Which of the following sorting algorithm will be preferred when the size of partition is between 16 and 2
log(n) while implementing introsort?
a) quick sort
b) insertion sort
c) heap sort
d) merge sort
Answer: a
Explanation: Quicksort proves to be the best sorting algorithm for mid sized arrays as it has low space and
time complexity. Thus quick sort is preferred when size of partition is between 16 and 2 log(n).
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[] = {1,3,4,2,5};
int n = sizeof(arr)/sizeof(arr[0]);
sort(arr, arr+n, greater<int>());
int a;
for (a = 0; a < n; a++)
cout << arr[a] << " ";
return 0;
}
a) 1 2 3 4 5
b) 1 3 4 2 5
c) 5 4 3 2 1
d) error
Answer: c
Explanation: The given program sorts the input in descending order. It is due to the third parameter i.e.
greater() which is passed to the function sort().
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[] = {1, 3,4,2,5};
int n = sizeof(arr)/sizeof(arr[0]);
sort(arr, arr+n);
int a;
for ( a = 0; a< n; a++)
cout << arr[a] << " ";
return 0;
}
a) 1 2 3 4 5
b) 1 3 4 2 5
c) 5 4 3 2 1
d) error
Answer: a
Explanation: The given program sorts the input in ascending order. Function sort() uses two parameters in
the form of address of the first and last element of the array to sort the array.
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[] = {1, 3,4,2,5};
int n = sizeof(arr)/sizeof(arr[0]);
sort(arr+2, arr+n, greater<int>());
int a;
for (int a = 0; a < n; a++)
cout << arr[a] << " ";
return 0;
}
a) 1 2 3 4 5
b) 1 5 4 3 2
c) 5 4 3 2 1
d) 1 3 5 4 2
Answer: d
Explanation: As the first parameter to function sort() is arr+2 so the sorting begins from the third element i.e.
4. Also as ther
1. Which of the following is Python’s standard sorting algorithm?
a) quick sort
b) introsort
c) merge sort
d) tim sort
Answer: d
Explanation: Tim sort has been python’s standard sorting algorithm since its version 2.3. It is an example of
hybrid sorting algorithm which means it uses more than one sorting algorithm as a routine.
Answer: c
Explanation: Tim sort is a hybrid sorting algorithm which means it uses more than one sorting algorithm as a
routine. It is derived from insertion sort and merge sort.
3. Tim sort begins sorting the given array by using which of the following sorting algorithm?
a) selection sort
b) quick sort
c) insertion sort
d) merge sort
Answer: c
Explanation: Tim sort begins sorting any given array by using insertion sort for each run. The array is
divided into smaller parts for this purpose, each part having a size equal to value of run. Then these small
parts called runs are merged in order to obtain sorted array.
Answer: a
Explanation: Out of the given options Tim sort is the only algorithm which is stable. As both constituents of
Tim sort (I.e insertion sort and merge sort) are stable so Tim sort also becomes stable.
Answer: b
Explanation: Tim sort is not an in-place sorting algorithm as it requires auxiliary space. It is because it
requires to merge sorted runs which requires a third array of the size equal to the sum of the two runs.
advertisement
6. Tim sort is a comparison based sort.
a) true
b) false
Answer: a
Explanation: Merge sort and insertion sort are comparison based sorts. Thus overall Tim sort also becomes a
comparison based sort.
Answer: a
Explanation: Best case time complexity of Tim sort occurs when the input array is already sorted. In such a
case only one run will be required.
Answer: b
Explanation: Worst case time complexity of Tim sort is O(n log n). It is because the worst complexity of
merge sort is O(n log n) and insertion sort is only applied for small arrays.
Answer: b
Explanation: Average time complexity of Tim sort remains to be O(n log n). It is the same as the average
case complexity of merge sort.
Answer: a
Explanation: Tim sort is a hybrid of merge sort and insertion sort. It requires to merge sorted runs which
require a third array of the size equal to the sum of the two runs. So in worst case the auxiliary space
requirement will be O(n).
11. Which of the following algorithm is implemented internally in java when we use function arrays.sort()?
a) intro sort
b) quick sort
c) tim sort
d) merge sort
Answer: c
Explanation: Java makes use of Tim sort internally for implementing arrays.sort(). It is mainly due to the
fastness of this algorithm in comparison to other comparison based sorts.
12. Why is insertion sort preferred over other sorting algorithms (like selection sort, bubble sort etc.) for Tim
sort implementation?
a) Because insertion sort is faster and adaptive
b) Because insertion sort requires less space
c) Because insertion sort is easy to implement
d) Because insertion sort is easy to understand
Answer: a
Explanation: When small arrays need to be sorted then insertion sort proves to be the best choice. Also, it is
adaptive so it performs better than others when the given array is fully/partially sorted.
13. In which case will tim sort will work as an insertion sort?
a) when no. of elements are less than 64
b) when no. of elements are greater than 64
c) when no. of elements are less than size of run
d) when no. of elements are less than 32
Answer: c
Explanation: Tim sort uses a hybrid of insertion and merge sort. It reduces to insertion sort when the size of
array is less than the size of run as insertion sort is efficient in sorting small arrays.
Answer: c
Explanation: Usually the size of the run is chosen somewhere between 32 and 64. The size of run is
preferably chosen in powers of 2 in order to maintain balance while merging the sorted runs.
import java.util.Arrays;
public class SortExample
{
public static void main(String[] args)
{
// Our arr contains 8 elements
int[] arr = {10,7,9,5,8,4};
Arrays.sort(arr);
System.out.printf(Arrays.toString(arr));
}
}
a) [4,5,7,8,9,10]
b) [10,9,8,7,5,4]
c) 4,5,7,8,9,10
d) error
Answer: a
Explanation: The given program sorts the input in ascending order by using the function Arrays.sort(). It
uses Tim sort internally.
import java.util.Arrays;
public class SortExample
{
public static void main(String[] args)
{
int[] arr = {10,7,9,5,8,4};
Arrays.sort(arr, 1, 3);
System.out.printf(Arrays.toString(arr));
}
}
a) [4,5,7,8,9,10]
b) [10,9,8,7,5,4]
c) [10,5,7,8,9,4]
d) [10,7,9,5,8,4]
Answer: d
Explanation: The given program sorts only a portion of the input array. It is done by passing two extra
arguments to the f
Answer: c
Explanation: Out of the given options only cube sort is a parallel sorting algorithm. It builds self balancing
multi dimensional arrays from the input keys.
Answer: c
Explanation: The worst case performance of cube sort is O(n log n). This is the fastest possible complexity
with a comparison based sort.
3. What is the auxiliary space requirement of cube sort?
a) O(n)
b) O(1)
c) O(log n)
d) O(n log n)
Answer: a
Explanation: Cube sort requires an auxiliary space of O(n). This is the worst case of auxiliary space
complexity.
Answer: b
Explanation: Best case time complexity of cube sort occurs when the input array is almost sorted. So in such
a case only O(n) time is required for sorting.
Answer: b
Explanation: The average case performance of cube sort is O(n log n). This is the fastest possible complexity
with a comparison based sort.
advertisement
Answer: d
Explanation: Out of the given algorithms only cube sort is stable. This implies that the relative position of
equal valued elements in the input and sorted array remains the same.
Answer: b
Explanation: Cube sort has an auxiliary space complexity of O(n). So it does not qualify to be an in-place
sort.
Answer: a
Explanation: In a general case the memory overhead of cube sort is low. But when the data set is small then
in that case the memory overhead becomes high.
Answer: a
Explanation: Cube sort is a comparison based sorting algorithm. This is because it compares elements in
order to sort them.
10. Which of the following sorting algorithm uses the method of insertion?
a) cube sort
b) bubble sort
c) quick sort
d) selection sort
Answer: a
Explanation: Cube sort is the only algorithm from the given ones that uses the method of insertion. Other
than this, th
1. Consider the original array 17 8 12 4 26. How many comparisons are needed to construct the BST on the
original array?
a) 5
b) 4
c) 7
d) 10
Answer: d
Explanation: Original array is 17 8 12 4 26. The BST built on this array is shown in the figure below.
To built the BST, we travel down the tree until a leaf is reached. Therefore, for every element we compare
the element with the internal nodes until we the leaves and then once again compare the element with its
parent to decide whether it is right child or left child. So, for given array we need to perform 10 comparisons
to build the BST.
2. In binary tree sort, we first construct the BST and then we perform _______ traversal to get the sorted
order.
a) inorder
b) postorder
c) preorder
d) level order
Answer: a
Explanation: In binary tree sort is a sort algorithm where a binary search tree is built from the elements to be
sorted, and then we perform inorder traversal on the BST to get the elements in sorted order.
3. What is the worst case time complexity of the binary tree sort?
a) O(n)
b) O(nlogn)
c) O(n2)
d) O(logn)
Answer: c
Explanation: For the binary tree sort the worst case when the BST constructed is unbalanced. BST gets
unbalanced when the elements are already sorted. So, in the worst case, O(n2) time is required to built the
BST and O(n) time to traverse the tree. Therefore, the worst case time complexity is O(n2) + O(n) = O(n2).
4. The insert() procedure, given below, builds the BST on the input elements, which is the first step of the
binary tree sort. Choose the correct to fill the condition.
Answer: b
Explanation: In binary tree sort, the BST is built on the input elements and the tree is traversed in in-order to
get the sorted order. While building the BST, we travel down the tree until a leaf is reached. While traveling
dawn the tree, we travel on left subtree if the new element is less than the node or to the right if the element
is greater or equal to the node. So, correct option is newElement < node->value.
advertisement
5. What is the best case time complexity of the binary tree sort?
a) O(n)
b) O(nlogn)
c) O(n2)
d) O(logn)
Answer: b
Explanation: The best case occurs when the BST is balanced. So, when tree is balanced we require O(nlogn)
time to build the tree and O(n) time to traverse the tree. So, the best case time complexity of the binary tree
sort is O(nlogn).
Answer: b
Explanation: In binary tree sort it is required to reserve one tree node for each array element. Its
implementation requires two pointer variables for each node. So, it requires extra memory. The worst case
space complexity of binary tree sort is Θ(n). Therefore, binary tree sort is not an in-place sorting algorithm.
Answer: d
Explanation: Binary tree sort and quick sort have same running time i.e O(nlogn)
in average case and O(n2) in worst case. Binary tree is not in-place sorting algorithm.
8. Which of the following sorting algorithms can be considered as improvement to the binary tree sort?
a) Heap sort
b) Quick sort
c) Selection sort
d) Insertion sort
Answer: a
Explanation: Heap sort is basically improvement to the binary tree sort. Heap sort builds a heap on the input
element by adjusting the position of the elements within the original array, rather than creating nodes as in
binary tree sort.
Answer: a
Explanation: Out of the given options only cycle sort is an unstable sorting algorithm. This implies that the
relative position of equal valued elements in the input and sorted array does not remain the same when we
use cycle sort.
Answer: d
Explanation: The worst case performance of cycle sort is O(n2). It is because it has to make n comparisons
for each element of the array.
Answer: b
Explanation: Cycle sort requires an auxiliary space of O(1). So this makes it an in-place sorting algorithm.
Answer: a
Explanation: Best case time complexity of cycle sort is O(n2). This shows that cycle sort is not an adaptive
sorting algorithm and thus makes it undesirable when the given array is already almost sorted.
Answer: b
Explanation: The time complexity of cycle sort is O(n2) in any case. So cycle sort algorithm is not adaptive,
as it will take the same time to sort an already sorted array and any other randomly arranged array.
Answer: b
Explanation: Cycle sort has an auxiliary space complexity of O(1). So it qualifies to be an in-place sort. All
other given options are not in place sorting algorithm.
Answer: c
Explanation: Cycle sort is a slow sorting algorithm as compared to quick sort, merge sort etc. and is also not
adaptive. But it offers an advantage that it performs minimal write operations which can be very useful in a
situation where the write operation is expensive.
Answer: a
Explanation: Cycle sort is a comparison based sorting algorithm. This is because it compares elements in
order to sort them.
10. Which of the following sorting algorithm uses the method of insertion?
a) cycle sort
b) bubble sort
c) quick sort
d) selection sort
Answer: a
Explanation: Cycle sort is the only algorithm from the given ones that uses the method of insertion. Other
than this, insertion sort also uses the method of insertion for sorting.
11. How many write operations will be required to sort the array arr={2,4,3,5,1} using cycle sort?
a) 4
b) 5
c) 6
d) 3
Answer: a
Explanation: Cycle sort requires a minimum number of write operations in order to sort a given array. So in
this case, only 4 write operations will be required.
12. Which of the following algorithm is best suited for the case where swap operation is expensive?
a) bubble sort
b) cycle sort
c) cocktail sort
d) merge sort
Answer: b
Explana
1. Which of the following is a disadvantage of library sort when compared to insertion sort?
a) library sort has greater time complexity
b) library sort has greater space complexity
c) library sort makes more comparisons
d) it has no significant disadvantage
Answer: b
Explanation: Library sort has a disadvantage that it takes up O(n) auxiliary space whereas insertion sort
takes constant auxiliary space.
Answer: a
Explanation: Library sort does not require the entire input data at the beginning itself in order to sort the
array. It rather creates a partial solution in every step, so future elements are not required to be considered.
Hence it is an online sorting algorithm like insertion sort.
Answer: c
Explanation: Library sort requires the use of Insertion sort and binary search in its code. So it is a modified
version of insertion sort.
Answer: c
Explanation: Out of the given options library sort is the only algorithm which is stable. It is because the
elements with identical values appear in the same order in the output array as they were in the input array.
5. Which of the following sorting algorithm requires the use of binary search in their implementation?
a) radix sort
b) library sort
c) odd-even sort
d) bead sort
Answer: b
Explanation: Library sort makes use of a binary search algorithm. It is used to find the correct index in the
array where the element should be inserted. Then after the insertion of the element re-balancing of the array
takes place.
advertisement
Answer: a
Explanation: In library sort, we need to compare elements in order to insert them at the correct index. So we
can say that it uses comparisons in order to sort the array. Thus it qualifies as a comparison based sort.
Answer: b
Explanation: Library sort uses binary search in order to insert elements in the sorted segment of the array
which reduces its time complexity. So the average time complexity of library sort is O(n log n).
Answer: a
Explanation: The best case time complexity of library sort is O(n). It occurs in the case when the input is
already/almost sorted.
Answer: c
Explanation: The worst case time complexity of library sort is the same as that of insertion sort. The worst
case time complexity is O(n2).
Answer: a
Explanation: Library sort is also known as gapped insertion sort because it uses insertion sort with gaps in
between successive elements. These gaps allow for fast insertion.
Answer: a
Explanation: Library sort has a better average time complexity as compared to insertion sort because it uses
binary search for finding the index where the element has to be inserted in the sorted array. This makes the
process faster.
Answer: a
Explanation: The auxiliary space required by library sort is O(n). This space is taken up by the gaps present
in between successive elements.
Answer: a
Explanation: Library sort is an adaptive algorithm. It is because the time complexity of the algorithm
improves when the input array is almost sorted.
Answer: a
Explanation: Out of the given options library sort is the only algorithm which is not in place. It is because
the auxiliary space required by library sort is O(n).
Answer: d
Explanation: Library sort is not an in place sorting algorithm as it requires O(n) auxiliary space. The array
needs
Answer: b
Explanation: Strand sort requires the use of recursion for implementing its algorithm. On the other hand, the
sorting algorithms given in the remaining options use iterative methods.
Answer: a
Explanation: Strand sort is most efficient when data is stored in a linked list as it involves many insertions
and deletions which is performed quite efficiently with the help of a linked list. Using an array would
increase time complexity significantly.
Answer: a
Explanation: The best case of strand sort occurs when the input array is already sorted. In this case, it has
linear time complexity.
4. What is the auxiliary space complexity of strand sort?
a) O(n)
b) O(1)
c) O(log n)
d) O(n log n)
Answer: a
Explanation: The auxiliary space complexity of strand sort is O(n). It is because a sub-list of size n has to be
maintained.
Answer: b
Explanation: Strand sort has an auxiliary space complexity of O(n). So it is not an in place sorting algorithm.
advertisement
Answer: a
Explanation: Pigeonhole sort is an example of a comparison based sorting algorithm. This is because it
compares the value of elements present in a list in order to sort them.
Answer: a
Explanation: Strand sort is an example of a stable sorting algorithm. It is because the elements with identical
values appear in the same order in the output array as they were in the input array.
Answer: c
Explanation: Average case time complexity of strand sort is O(n2). So it is not as efficient as quick sort or
merge sort.
Answer: a
Explanation: Best case time complexity of strand sort is O(n). It occurs in the case where the input array is
already sorted.
Answer: c
Explanation: Worst case time complexity of strand sort is O(n2). It occurs in the case where the input array is
in reverse sorted order.
11. Strand sort algorithm used which of the following method for sorting a list?
a) merging
b) selection
c) insertion
d) partitioning
Answer: b
Explanation: Strand sort uses the method of selection for sorting any given list. This is because it selects the
strands of elements from the input list which are sorted.
Answer: b
Explanation: Strand sort
Answer: d
Explanation: Cocktail sort is also known by the name of ripple sort. It is also known by other names like –
bidirectional bubble sort, cocktail shaker sort, shuttle sort, shuffle sort etc.
Answer: a
Explanation: Cocktail sort is very similar to bubble sort. It works by traversing an array in both directions
alternatively. It compares the adjacent elements in each iteration and swaps the ones which are out of order.
Answer: c
Explanation: In cocktail sort manipulation is done on the input array itself. So no extra space is required to
perform sorting. Thus it requires constant auxiliary space.
Answer: a
Explanation: Out of the given options quick sort is the only algorithm which is not stable. Cocktail sort like
bubble sort is a stable sorting algorithm.
Answer: a
Explanation: Cocktail sort is an in place sorting technique as it only requires constant auxiliary space for
manipulating the input array. Rest all other options are not in place.
Join [email protected]
Answer: a
Explanation: Cocktail sort compares the value of different elements in the array for sorting. Thus, it is a
comparison based sort.
7. Cocktail sort uses which of the following methods for sorting the input?
a) selection
b) partitioning
c) merging
d) exchanging
Answer: d
Explanation: Cocktail sort uses a method of exchanging as it swaps the elements which are out of order.
This swapping is done in two phases i.e. forward phase and backward phase.
Answer: c
Explanation: Worst case complexity is observed when the input array is reverse sorted. This is the same as
the worst case complexity of bubble sort.
Answer: a
Explanation: Best case complexity is observed when the input array is already sorted. This is the same as the
best case complexity of bubble sort.
Answer: c
Explanation: Cocktail sort takes O(n2) time on average as it keeps on applying bubble sort on the elements in
two phases until they are sorted. This is the same as the average time complexity of bubble sort.
11. How many iterations are required to sort the array arr={2,3,4,5,1} using bubble sort and cocktail sort
respectively?
a) 4,2
b) 5,3
c) 5,2
d) 4,3
Answer: a
Explanation: Cocktail sort applies bubble sort in two phases until the array gets sorted. So here bubble sort
will take 4 iterations to sort the given array whereas cocktail sort takes only 2 iterations. This shows cocktail
sort has a comparatively better performance.
a) Bubble sort
b) Selection sort
c) Bidirectional bubble sort
d) Odd-even sort
Answer: c
Explanation: The given function represents bidirectional bubble sort also known as cocktail sort. In this sort,
we apply bubble sort in two phases i.e. forward and backward phase until the array gets sorted.
Answer: b
Explanation: Both
2. The gap between two elements being compared shrinks by a factor of _______ after every iteration.
a) 1.1
b) 1.2
c) 1.3
d) 1.4
Answer: c
Explanation: It has been found experimentally that the gap between the two elements should shrink by a
factor of 1.3 after each iteration for the most efficient sorting.
Answer: a
Explanation: Initial gap is taken to be equal to the number of elements in the array and shrinks by a factor of
1.3 in each iteration, initial gap is independent of the number of iterations and compiler being used.
Answer: a
Explanation: Worst case complexity is observed when the input array is reverse sorted. This is same as the
worst case complexity of bubble sort.
5. The gap value after 3 iterations in an array with 6 elements will be _______
a) 4
b) 3
c) 2
d) 1
Answer: c
Explanation: Initially the gap value will be 6. For the first iteration, it will be 6/1.3=4 then 4/1.3=3 for
second iteration and 3/1.3=2 for the third iteration.
Join [email protected]
7. The given array is arr={7,4,5,8,1,2}. The number of iterations required to sort the array using comb sort
and bubble sort respectively will be _______
a) 7 and 8
b) 5 and 6
c) 5 and 5
d) 4 and 5
Answer: d
Explanation: Comb sort takes 1 iteration less as compared to bubble sort as it makes use of variable gap
value whereas bubble sort uses a constant gap value of 1.
Answer: b
Explanation: Comb sort is not a stable sorting algorithm as it does not sort the repeated elements in the same
order as they appear in the input.
9. What is the best case time complexity of comb sort and bubble sort respectively?
a) O(n2) and O(n log n)
b) O(n log n) and O(n)
c) O(n) and O(n2)
d) O(n2/2a) (a=number of increment) and O(n2)
Answer: b
Explanation: Best case complexity for comb sort and bubble sort is O(n log n) and O(n) respectively. It
occurs when the input array is already sorted.
Answer: a
Explanation: Co
Answer: b
Explanation: Gnome sort was originally named as stupid sort but later on it got renamed as gnome sort.
2. How many loops are required to implement gnome sorting algorithm?
a) Single loop
b) 2 nested loops
c) 3 nested loops
d) It does not require any loop
Answer: a
Explanation: In this sorting algorithm the variable representing the index number is not incremented in case
the adjacent pair of elements are out of place. In such a case its value is decremented instead. Thus it is able
to implement sorting using a single loop.
Answer: c
Explanation: Gnome sort and merge sort are stable sorting algorithms as the elements with identical values
appear in the same order in the output array as they were in the input array when any of these sorting
algorithms are implemented.
Answer: a
Explanation: Auxiliary space used by gnome sort is O(1) as it does not use any extra space for manipulating
the input. Thus it also qualifies as an in place sorting algorithm.
5. The given array is arr = {1,2,4,3,5}.The number of iterations required to sort the array using gnome sort
will be _________
a) 5
b) 6
c) 7
d) 8
Answer: b
Explanation: 6 iterations will be required as one pair of elements i.e. {4,3} is out of place which causes the
loop to take one step backward.
advertisement
Answer: a
Explanation: When the input array is already sorted then in that case there will be no need to decrease the
value of the index variable at any stage. So only O(n) time is required in this case as we keep on increasing
its value after each iteration.
b)
c)
Answer: c
Explanation: The first if statement increments the value of index if found to be 0 so that comparison can take
place for this element. Second if statement checks whether the adjacent pair of elements are in order or not.
If found out of order they are swapped under the else statement and index is decremented.
Answer: b
Explanation: Worst case occurs when the input array is reverse sorted as it will have the maximum number
of decrements while sorting. This causes the algorithm to have a time complexity of O(n2) in this case.
Answer: b
Explanation: In gnome sort the loop has to take one step backwards every time any adjacent pair of elements
is out of place whi
Answer: c
Explanation: Bogosort is also known by names like stupid sort, monkey sort, permutation sort, slow sort and
shotgun sort.These names are particularly chosen due to its inefficient algorithm.
Answer: a
Explanation: Bogosort algorithm successively generates permutations of its input. This process is repeated
until the sorted version of the array is found.
Answer: b
Explanation: Bogosort algorithm do not require any extra space for sorting the input array. Thus its auxiliary
space requirement is O(1).
Answer: b
Explanation: Best case time complexity of bogosort occurs when the input array is already sorted. So in such
a case we only need to check whether all the elements are sorted which can be done in O(n) time.
Answer: c
Explanation: There is no upper bound to the worst case of this algorithm. It can go on to take very large
amount of time if the array has many elements. So the worst case of this algorithm can be taken as
O(infinity).
Join [email protected]
Answer: d
Explanation: Out of the given algorithms only bogosort is not stable. This is because it creates permutations
of the input array in order to obtain the sorted version. So there is no guarantee that the sorted version
obtained by such a method gives a stable output.
7. Which of the following is an in-place sorting algorithm?
a) Merge sort
b) Bogosort
c) Radix sort
d) Counting sort
Answer: b
Explanation: Out of the given algorithms only bogosort is an in-place sorting algorithm. It is because
bogosort algorithm do not require any extra space for sorting the input array.
8. Sleep sort should be preferred over bogosort as it has better time complexity.
a) true
b) false
Answer: b
Explanation: If we sort an array using sleep sort then there is no guarantee that the output we get is correctly
sorted. So even though sleep sort is better than bogosort in time complexity but it cannot be preferred due to
its inaccuracy.
Answer: b
Explanation: For calculating the average we first need to calculate the number of possible permutations an
array of size n can have. This will be equal to n!. As each permutation also needs to be checked whether it is
sorted or not so this takes another n time. Thus overall time complexity becomes O(n*n!).
b)
c)
d)
Answer: a
Explanation: To implement bogosort algorithm we need to shuffle the input array until we get the sorted
array. So we
1. Which of the following header file is a must to implement sleep sort algorithm?
a) string.h
b) math.hw
c) bios.h
d) windows.h
Answer: d
Explanation: To implement sleep sort algorithm we need functions like WaitForMultipleObjects(),
_beginthread(). These are included in the header file windows.h.
Answer: a
Explanation: Sleep sort algorithm does not work for negative numbers. It is because thread cannot sleep for
negative amount of time.
3. In how many comparisons does the array arr={1,4,2,3,5} gets sorted if we use sleep sort?
a) 5
b) 3
c) 1
d) 0
Answer: d
Explanation: Sleep sort makes different elements of the array to sleep for an amount of time that is
proportional to its magnitude. So it does not require to perform any comparison in order to sort the array.
Answer: a
Explanation: In sleep sort each element is made to sleep for a time that is proportional to its magnitude.
Then the elements are printed in the order in which they wake up.
Answer: c
Explanation: Sleep sort requires multithreading process for making the elements to sleep. This process
happens in the background at the core of the OS and so cannot be compiled on an online compiler.
advertisement
6. Time complexity of sleep sort can be approximated to be ___________
a) O(n + max(input))
b) O(n2)
c) O(n log n + max(input))
d) O(n log n)
Answer: c
Explanation: As the sleep() function creates multiple threads by using priority queue which takes n log n
time for insertion. Also the output is obtained when all the elements wake up. This time is proportional to
the max(input). So its time complexity is approximately O(n log n + max(input)).
7. Sleep sort can be preferred over which of the following sorting algorithms for large number of input
elements?
a) Quick sort
b) Bubble sort
c) Selection sort
d) No sorting algorithm is preferred
Answer: d
Explanation: Sleep sort is not preferred over any of the given sorting algorithms as sleep sort does not
guarantee a correct output every time. So sleep sort is not a reliable sorting technique.
Answer: b
Explanation: All the major processes involved in sleep sort takes place internally in the OS. So it does not
require any auxiliary space to sort the elements.
Answer: c
Explanation: Sleep sort gives a sorted output when the array elements are positive. But when any other case
than this occur out of the above given cases then we may not see a correct output. This makes sleep sort very
unreliable sorting technique.
10. Which of the following sorting algorithm is most closely related to the OS?
a) gnome sort
b) sleep sort
c) radix sort
d) bogo sort
Answer: b
Explanation: Sleep sort is most closely related to the operating system. It is because most of the major steps
of this algorithm takes place at the core of OS.
Answer: a
Explanation: Sleep sort is an in-place sorting technique as most of its major steps takes place in the
background. So it do
1. How many comparisons will be made to sort the array arr={1,5,3,8,2} using pigeonhole sort?
a) 5
b) 7
c) 9
d) 0
Answer: d
Explanation: As pigeonhole sort is an example of a non-comparison sort so it is able to sort an array without
making any comparison. So 0 comparisons are required.
Answer: d
Explanation: Heap sort, merge sort and quick sort are examples of comparison sort as it needs to compare
array elements in order to sort an array. Whereas pigeonhole sort is a non-comparison based sort.
Answer: c
Explanation: Pigeonhole sort is a non-comparison based sort. It is most efficient in the case where the
number of elements are comparable to the input range.
Answer: d
Explanation: Pigeonhole sort algorithm requires two arrays. The first one is required to store the input
elements so its size is n. The second one is the pigeonhole array and has a size equal to range k. Overall
space complexity becomes O(n+k).
Answer: d
Explanation: The auxiliary array used in pigeonhole sorting is called pigeonhole. It is used to store every
element in its corresponding hole.
advertisement
Answer: a
Explanation: Pigeonhole sort is an example of a stable sorting algorithm. It is because the elements with
identical values appear in the same order in the output array as they were in the input array.
Answer: b
Explanation: Pigeonhole sort requires space of O(n+k). So it does not qualify to be an in place sorting
algorithm.
Answer: b
Explanation: Time complexity of pigeonhole sort is O(n+k). It has two loops. One of the loops runs from 0
to range(k) and the other one runs from 0 to n so the time complexity becomes O(n+k).
9. The complexity of which of the following sorting algorithms remains to be the same in its best, average
and worst case?
a) quick sort
b) insertion sort
c) pigeonhole sort
d) bubble sort
Answer: c
Explanation: The time complexity of pigeonhole remains unvaried in all three cases. It is given by O(n+k).
But it is efficient only when the number of elements is comparable to the input range.
10. Choose the correct statement from the following.
a) pigeonhole sort is a comparison based sort
b) any comparison based sorting can be made stable
c) quick sort is not a comparison based sort
d) any comparison based sort requires at least O(n2) time
Answer: b
Explanation: Any comparison based sorting technique can be made stable by considering the position as
criteria while making comparisons. Pigeonhole sort is a stable sort.
Answer: a
Explanation: Pigeonhole sort is efficient in the cases where the range is comparable to a number of input
elements as it performs sorting in linear time. Whereas merge sort takes O(n log n) in any case.
b)
c)
d)
13. Which of the following algorithm takes linear time for sorting?
a) pigeonhole sort
b) heap sort
c) comb sort
d) cycle sort
Answer: a
Explanation: Pigeonhole sort has a linear time complexity of O(n+k). Whereas all other given options have a
non
Answer: d
Explanation: In Distribution sort the inputted values are distributed to multiple intermediate structures which
are then combined and placed on the output. And LSD radix sort distributes values into buckets based on the
digits within values, so it is a distribution sort.
Answer: b
Explanation: Time complexity of LSD radix sort depends upon the word size and the number on items. It
runs in O(wn) time in worst case, where n is the number of inputted elements and w is the number of digits
in the largest number.
Answer: a
Explanation: LSD radix sort sorts the N elements in (w/logR) passes where w is the number of digits in
largest number and R(radix) is extra space required for performing the sorting operation.
Answer: b
Explanation: LSD radix sort uses bucket sort for grouping the keys based on the digits at that value. And as
it grouped the keys based on the digits at that values, it is integer sorting algorithm.
Answer: d
Explanation: In LSD radix sort after sorting the multiple elements with the same key will be in the same
order as they were in the input array. So LSD radix sort is stable sort.
advertisement
Answer: b
Explanation: LSD radix sort is faster than comparison sorts when the word size is less than logn. But LSD
radix sort runs slowly for elements with larger word size and smaller radix.
7. Which of the following should be used to sort a huge database on a fixed-length key field?
a) Insertion sort
b) Merge sort
c) LSD radix sort
d) Quick sort
Answer: c
Explanation: LSD radix requires only w passes to sort a fixed-length string, where w is a length of the
strings. So, LSD radix sort is best suited to sort a huge database on a fixed-length key field.
Answer: a
Explanation: Forward radix sort combines the advantages of LSD and MSD radix sort. Forward radix sort
inspects a complete horizontal strip at a time just like LSD radix sort.
Answer: b
Explanation: LSD radix sort sorts the keys in right-to-left order, working with Least Significant Digit first.
The inner loop has a lot of instructions and LSD radix sort is used to sort fixed-length strings.
Answer: a
Explanation: L
1. How many comparisons will be made to sort the array arr = {1, 5, 3, 8, 2} using MSD radix sort?
a) 5
b) 7
c) 9
d) 0
Answer: d
Explanation: As MSD radix sort is an example of non comparison sort so it is able to sort an array without
making any comparison. So the answer should be 0.
Answer: a
Explanation: MSD stands for Most Significant Digit. It is named so because in this algorithm the processing
begins from the most significant digit.
3. Which of the following combines qualities of MSD radix sort and LSD radix sort?
a) in-place MSD radix sort
b) stable MSD radix sot
c) 3 way radix quick sort
d) forward radix sort
Answer: d
Explanation: Forward radix sort combines the qualities of MSD and LSD radix sort. The sorting is done by
separating the strings into groups.
Answer: b
Explanation: Top down radix sort is an alternate name of MSD radix sort. It is because in this algorithm the
processing starts from the most significant digit and end at least significant digit.
advertisement
Answer: c
Explanation: MSD radix sort takes non constant time for sorting the input data. So it is not an in place
sorting algorithm.
7. MSD radix sort should be preferred over LSD radix sort when we have to maintain the original relative
order.
a) True
b) False
Answer: b
Explanation: MSD radix sort is not a stable sort whereas LSD radix sort is stable. So when we require to
preserve the original order then in that case we should prefer LSD radix sort.
8. What is the average time complexity of MSD radix sort (w= bits required to store each key)?
a) O(n + w)
b) O(n.w)
c) O(n2)
d) O(n log n)
Answer: b
Explanation: Time complexity of radix sort is O(n.w). It performs better than quick sort when we have log n
bits for every digit.
Answer: b
Explanation: MSD radix sort takes non constant time for sorting the input data. So it is not an in place
sorting algorithm.
10. Which of the following statement is not a stable sorting algorithm?
a) LSD radix sort
b) MSD radix sort
c) Counting sort
d) Pigeonhole sort
Answer: b
Explanation: MSD radix sort is not a stable sort. It is because the elements with identical values do not
appear in the same order in the output array as they were in the input array.
Answer: b
Explanation: Quick sort has a better cache performance than radix sort. Radix sort also takes more space as
compared to quick sort.
Answer: a
Explanation: Radix sort performs better than quick sort when we have log n bits for every digit. But radix
sort takes more space as compared to quick sort.
13. What will be the order of elements of the array arr = {23, 67, 143, 654, 43} after first iteration of MSD
sort is complete?
a) 23, 43, 67, 143, 654
b) 23, 67, 43, 143, 654
c) 23, 67, 143, 654, 43
d) 23, 143, 43, 654, 67
Answer: b
Explanation: In the first ite
1. How many comparisons will be made to sort the array arr={1,5,3,8,2} using counting sort?
a) 5
b) 7
c) 9
d) 0
Answer: d
Explanation: As counting sort is an example of non comparison sort so it is able to sort an array without
making any comparison.
2. Which of the following is not an example of non comparison sort?
a) bubble sort
b) counting sort
c) radix sort
d) bucket sort
Answer: a
Explanation: Bubble sort is not an example of non comparison sort as it needs to compare array elements in
order to sort an array.
3. Which of the following sorting techniques is most efficient if the range of input data is not significantly
greater than a number of elements to be sorted?
a) selection sort
b) bubble sort
c) counting sort
d) insertion sort
Answer: c
Explanation: Time complexity of counting sort is given as O(n+k) where n is the number of input elements
and k is the range of input. So if range of input is not significantly larger than number of elements in the
array then it proves to be very efficient.
Answer: d
Explanation: Counting sort uses two extra arrays to get the input array sorted. First array is required to store
the count of all the elements which fall in the range of input data elements, so its size is k. The second array
is required to store the input elements in sorted manner, so its size is n. Thus overall auxiliary space required
becomes O(n+k).
5. It is not possible to implement counting sort when any of the input element has negative value.
a) True
b) False
Answer: b
Explanation: It is possible to extend the counting sort algorithm for negative numbers as well. In such a case
we store the minimum element at the 0th index.
advertisement
7. Which of the following uses the largest amount of auxiliary space for sorting?
a) Bubble sort
b) Counting sort
c) Quick sort
d) Heap sort
Answer: b
Explanation: Counting sort requires auxiliary space of O(n+k) whereas quick sort, bubble sort and heap sort
are in place sorting techniques. Thus counting sort requires most auxiliary space.
Answer: b
Explanation: Time complexity of counting sort is O(n+k) as counting the occurrence of each element in the
input range takes k time and then finding the correct index value of each element in the sorted array takes n
time.
9. The complexity of which of the following sorting algorithms remains to be the same in its best, average
and worst case?
a) quick sort
b) insertion sort
c) counting sort
d) gnome sort
Answer: c
Explanation: The time complexity of counting sort remains unvaried in all the three cases. It is given by
O(n+k).
10. Which of the following statement is true about comparison based sorting?
a) counting sort is a comparison based sort
b) any comparison based sorting can be made stable
c) bubble sort is not a comparison based sort
d) any comparison based sort requires at least O(n2) time
Answer: b
Explanation: Any comparison based sorting technique can be made stable by considering a position as
criteria while making comparisons.
11. Counting sort is often used as a sub routine for radix sort.
a) true
b) false
Answer: a
Explanation: Counting sort is used as a sub routine for radix sort as it is a stable and non comparison based
sorting algorithm.
Answer: a
Explanation: Counting sort is very efficient in the cases where range is comparable to number of input
elements as it performs sorting in linear time.
13. which of the following represents the algorithm of counting sort correctly?
a)
function countingSort(array, k) is
count ← new array of k zeros
for i = 1 to length(array) do
count[array[i]] ← count[array[i]] + 1
for i = 2 to k do
count[i] ← count[i] + count[i +1]
for i = length(array) downto 1 do
output[count[array[i]]] ← array[i]
count[array[i]] ← count[array[i]] - 1
return output
b)
function countingSort(array, k) is
count ← new array of k zeros
for i = 1 to length(array) do
count[array[i]] ← count[array[i]] + 1
for i = 2 to k do
count[i] ← count[i] + count[i - 1]
for i = length(array) downto 1 do
output[count[array[i]]] ← array[i]
count[array[i]] ← count[array[i]] - 1
return output
c)
function countingSort(array, k) is
count ← new array of k zeros
for i = 1 to length(array) do
count[array[i]] ← count[array[i]] + 1
for i = 1 to k do
count[i] ← count[i] + count[i - 1]
for i = length(array) downto 1 do
output[count[array[i]]] ← array[i]
count[array[i]] ← count[array[i]] - 1
return output
d)
function countingSort(array, k) is
count ← new array of k zeros
for i = 1 to length(array) do
count[array[i]] ← count[array[i]] + 1
for i = 2 to k do
count[i] ← count[i] + count[i + 1]
for i = length(array) downto 1 do
output[count[array[i]]] ← array[i]
count[array[i]] ← count[array[i]] - 1
return output
Answer: b
Explanation: The first loop counts the number of occurrences of each element. Second loop performs prefix
sum on count to determine position range where items having that key should be placed in. The third loop
places each element at its correct position.
Answer: d
Explanation: Counting sort can only be used for arrays with integer elements because otherwise array of
frequencies cannot be constructed.
15. Which of the following algorithm takes non linear time for sorting?
a) counting sort
b) quick sort
c) bucket sort
d) radix sort
Answer: b
Explanation: Quick sort re
1. How many comparisons will be made to sort the array arr={1, 5, 3, 8, 2} using bucket sort?
a) 5
b) 7
c) 9
d) 0
Answer: d
Explanation: As bucket sort is an example of a non-comparison sort so it is able to sort an array without
making any comparison. So the answer should be 0.
Answer: c
Explanation: Bucket sort is also known as bin sort. It is an example of a non-comparison sort.
3. Which of the following non-comparison sort can also be considered as a comparison based sort?
a) counting sort
b) MSD radix sot
c) bucket sort
d) pigeonhole sort
Answer: c
Explanation: Bucket sort can also be considered as a comparison based sort. It is because it can also be
implemented with comparisons.
Answer: d
Explanation: Bucket sort is a non comparison based integer sort. It sorts the given data by distributing the
array elements into a number of buckets. It is not an in place sorting technique.
5. Which of the following don’t affect the time complexity of bucket sort?
a) algorithm implemented for sorting individual buckets
b) number of buckets used
c) distribution of input
d) input values
Answer: d
Explanation: Time complexity of bucket sort is affected by various factors. These include algorithm
implemented for sorting individual buckets, number of buckets used and distribution of input. It doesnot
depend on the input value. It can be either positive or negative or zero.
advertisement
Answer: b
Explanation: Bucket sort works by distributing the array elements into a number of buckets. So bucket sort
is most efficient in the case when the input is uniformly distributed.
Answer: b
Explanation: Pigeonhole sort is a particular case of bucket sort. Bucket sort is also closely related to MSD
radix sort.
8. What is the worst case time complexity of bucket sort (k = number of buckets)?
a) O(n + k)
b) O(n.k)
c) O(n2)
d) O(n log n)
Answer: c
Explanation: Time complexity of bucket sort is O(n2) in the worst case. So if bucket sort does not get the
inputs in the desired manner then it becomes very inefficient.
9. What is the best time complexity of bucket sort (k= number of buckets)?
a) O(n + k)
b) O(n.k)
c) O(n2)
d) O(n log n)
Answer: a
Explanation: Time complexity of bucket sort is O(n+k). It performs better than any comparison based sort if
there is a uniform input distribution.
Answer: a
Explanation: Bucket sort is not necessarily a stable sorting algorithm. This is because its stability depends on
the stability of the algorithm that we have used to sort the individual buckets.
Answer: b
Explanation: Bucket sort is not an in place sorting algorithm. It requires an auxiliary space of O(n k) in the
worst case.
12. What is the worst space complexity of bucket sort (k = number of buckets)?
a) O(n + k)
b) O(n.k)
c) O(n2)
d) O(n log n)
Answer: b
Explanation: Worst
Answer: a
Explanation: Bead sort is also known as gravity sort. It is because this algorithm was designed by keeping
the natural phenomenon of falling objects in mind.
2. Which of the following sorting algorithm was inspired by the natural phenomenon of falling objects?
a) bogo sort
b) heap sort
c) bead sort
d) strand sort
Answer: c
Explanation: The algorithm of bead sort was inspired by the natural phenomenon of falling objects. Thus, it
is also known by the name of gravity sort.
Answer: c
Explanation: Bead sort algorithm is only applicable to positive integers. This is because it works by placing
number of beads equal to key value, in each row.
Answer: c
Explanation: The auxiliary space complexity of bead sort is O(n2). It is because an array of size
maximum_element*n (maximum_element is the maximum element that is present in the array and n is the
size of the array) has to be maintained.
Answer: b
Explanation: Bead sort has an auxiliary space complexity of O(n2). So it is not an in place sorting algorithm.
advertisement
Answer: b
Explanation: Bead sort is an example of non comparison based sorting algorithm. This is because it does not
compare the value of elements present in a list in order to sort them.
7. How many comparisons will be required to sort the array arr={5, 4, 7, 1, 9} using bead sort?
a) 5
b) 4
c) 6
d) 0
Answer: d
Explanation: Bead sort is an example of a non-comparison based sorting algorithm. So no comparison is
required to be performed in order to sort the array.
8. What is the average time complexity of bead sort (S = sum of input elements)?
a) O(n)
b) O(S)
c) O(n2)
d) O(n log n)
Answer: b
Explanation: Average case time complexity of bead sort is O(S). It is because we drop each bead as a
separate operation.
9. What is the best case time complexity of bead sort (S = sum of input elements)?
a) O(n)
b) O(S)
c) O(n2)
d) O(n log n)
Answer: a
Explanation: Best case time complexity of bead sort is O(n). It is when a row of beads is dropped as a
distinct operation and since the number of rows is equal to n.
10. What is the worst case time complexity of bead sort (S= sum of input elements)?
a) O(n)
b) O(S)
c) O(n2)
d) O(n log n)
Answer: b
Explanation: Worst case time complexity of bead sort is O(S). It is because we drop each bead as a separate
operation.
11. Which of the following code fragment puts sorted values in an array using beads correctly?
a)
b)
c)
d)
Answer: b
Explanation: After sorting the elements in the bead array we finally need to shift them to the original array.
So we need to apply the condition j < max && beads[i * max + j] in order to achieve this.
Answer: a
Explanat
1. What is the time complexity for a given pancake sort given it undergoes “n” flip operations?
a) O(n)
b) O(n2)
c) O(n3)
d) O(2n)
Answer: b
Explanation: Most sorting algorithms try to sort making the least number of comparisons but in pancake sort
we try to sort using as few reversals as possible. Because the total number of flip operations performed in a
pancake sort is O(n), the overall time complexity is O(n2).
Answer: a
Explanation: When we use pancake sort, we sort the array to find the largest, and then flip the array at that
point to bring that value to the bottom of the pancake stack. The size of the array that we are dealing with is
then reduced and the process continues. Flip operation is the most important function in the pancake sort
technique.
3. There is one small error in the following flip routine. Find out which line it is on.
a) Line 3
b) Line 5
c) Line 7
d) Line 9
Answer: c
Explanation: After initialization of the array titled arr; for each while loop iteration of increasing init, we
should make arr[init]=arr[i]. This makes sure that the changes will be made in order to flip the order of the
array that was to be flipped. Here in line 7 it has been written in reverse and is incorrect.
advertisement
4. How many flips does the simplest of pancake sorting techniques require?
a) 3n−3 flips
b) 2n-4 flips
c) 2n-3 flips
d) 3n-2 flips
Answer: c
Explanation: The minimum number of flips required to sort any stack of n pancakes has been shown to lie
between 1.087n and 1.636n. using average of that 1.36n and extracting that for values of n>1. We have 1.36,
2.72, 4.08 etc. This matches best with 2n-3 which is equal to 1, 3, 5, 7, 9, etc. An upper bound of 2n-3
comes by iteratively using the next largest element in its correct place using two flips.
Answer: c
Explanation: Pancake Sorting finds application in educational use not to mention parallel processing
networks by providing optimal routing algorithms between networks.
6. In addition to the pancake sorting problem, there is the case of the burnt pancake problem in which we are
dealing with pancakes (discs) that are burnt on one side only. In this case it is taken that the burnt side must
always end up _______
a) Faced down
b) Faced up
c) It doesn’t matter
d) Both sides are burnt
Answer: a
Explanation: A varation of this pancake is with burnt pancakes. Here each pancake has a burnt side and all
pancakes must, in addition, end up with the burnt side on bottom. It is a more difficult version of the regular
pancake problem.
7. In a computational complexity theory, a problem with decision making is said to be NP-complete when it
is both in NP and NP-hard. What does NP mean?
a) Non Polynomial time
b) Non-deterministic Probabilistic
c) Non-deterministic Polynomial time
d) Non Probabilistic time
Answer: c
Explanation: Although any given solution to an NP-complete problem can be validated quickly in
polynomial time; there is no way to efficiently locate a solution to begin with. The unique characteristic of
NP-complete problems is that no fast solution to them is known and hence NP-complete problems are said
to be non-deterministic polynomial time.
8. When we realize a specific implementation of a pancake algorithm, every move when we find the greatest
of the sized array and flipping can be modeled through __________
a) Combinations
b) Exponential functions
c) Logarithmic functions
d) Permutations
Answer: d
Explanation: Here when we flipping the array or stack, we have to take utmost priority to preserve the order
of the list so that that sorting doesnt become invalid. Hence we use permutations, we are ensuring that order
matters.
9. The Pancake Problems (1975, 1979, 1973) did NOT involve which of the following people?
a) Bill Gates
b) Jacob Goodman
c) Christos Papadimitriou
d) John Goodman
Answer: d
Explanation: (Jacob Goodman – 1975) What is the maximum number of flips needed to sort a permutation
of [n] into ascending order?
(Bill Gates and Christos Papadimitriou – 1979) What is the maximum number of flips needed to sort a
signed permutation of [n] into ascending order with all positive signs?
10. There is a one line error in the following routine. Find that line.
a) Line 2
b) Line 4
c) Line 6
d) Line 5
Answer: b
Explanation: T
Answer: c
Explanation: Odd-even sort is also known by the name of a brick sort. This algorithm was first proposed by
Habermann in 1972 and was initially invented for parallel computation of local interconnection.
Answer: a
Explanation: Odd-even sort is very similar to bubble sort. It works by applying bubble sort in two phases I.e
odd phase and even phase. In odd phase bubble sort is applied on odd indexed elements and in even phase
bubble sort is applied on even indexed elements.
Answer: c
Explanation: In odd-even sort manipulation is done on the input array itself. So no extra space is required to
perform sorting. Thus it requires constant auxiliary space.
Answer: a
Explanation: Out of the given options quick sort is the only algorithm which is not stable. Brick sort like
bubble sort is a stable sorting algorithm.
Answer: a
Explanation: Brick sort is an in place sorting technique as it only requires constant auxiliary space for
manipulating the input array.
Join [email protected]
Answer: a
Explanation: Odd-even sort compares the value of different elements in the array for sorting. Thus, it is a
comparison based sort.
7. Brick sort uses which of the following methods for sorting the input?
a) selection
b) partitioning
c) merging
d) exchanging
Answer: d
Explanation: Brick sort uses the method of exchanging as it swaps the elements which are out of order. This
swapping is done in two phases i.e. odd phase and even phase.
Answer: a
Explanation: Best case complexity is observed when the input array is already sorted. This is the same as the
best case complexity of bubble sort.
Answer: c
Explanation: Odd-even sort takes O(n2) time on average as it keeps on applying bubble sort on the elements
in two phases until they are sorted.
11. How many odd and even phases are required respectively to sort the given array using odd-even
sort.arr={3,2,3,8,5,6,2,1}.
a) 3,3
b) 4,4
c) 3,4
d) 4,3
Answer: b
Explanation: Odd-even sort applies bubble sort in two phases until the array gets sorted. So here 8 phases
will be required in totality to sort the array. Out of these 4 phases will be odd phase and the other 4 will be
even phase.
b)
c)
Answer: b
Explanation
Answer: b
Explanation: Stooge sort requires the use of recursion for implementing its algorithm. On the other hand, the
sorting algorithms given in the remaining options use iterative methods.
Answer: d
Explanation: In stooge sort recursion is applied to 2/3 part of the array 3 times. Rest of the portion of code
has a constant time complexity. So the overall recurrence relation becomes T(n) = 3T(2/3n) + O(1).
3. In which of the following case stooge sort is most efficient (in terms of time complexity)?
a) when input array is already sorted
b) when input array is reverse sorted
c) when input array is large
d) it has the same time complexity in any case
Answer: d
Explanation: Stooge sort has the same time complexity under any case. It is given by the recurrence relation
T(n) = 3T(2/3n) + O(1).
Answer: a
Explanation: The space complexity of the stooge sort is O(n). It is used to store the input array.
5. What is the first step in the algorithm of stooge sort(after base case)?
a) apply stooge sort on first 2/3 elements of array
b) apply stooge sort on last 2/3 elements of array
c) apply stooge sort on first 1/3 elements of array
d) compare first and last element of the array
Answer: d
Explanation: The first step in the algorithm of stooge sort is to compare the first and last element of the array
and switch them if found out of order. In the second step stooge sort is applied on the first 2/3 elements of
the array.
Join [email protected]
Answer: a
Explanation: Stooge sort is an example of a comparison based sorting algorithm. This is because it compares
the value of elements present in a list in order to sort them.
Answer: b
Explanation: Stooge sort is not a stable sorting algorithm. It is because the elements with identical values do
not appear in the same order in the output array as they were in the input array.
Answer: d
Explanation: The recurrence relation of stooge sort is given as T(n) = 3T(2/3n) + O(1). It is found to be
equal to O(n2.7) using the master’s theorem.
9. How many recursive statements are used in the algorithm of stooge sort?
a) 0
b) 1
c) 2
d) 3
Answer: d
Explanation: The algorithm of stooge sort uses 3 recursive statements in its algorithm. The first and third
recursive statement applies stooge sort to the first 2/3 elements of the array and the second recursive
statement applies stooge sort to last 2/3 elements of the array.
10. Which of the following sorting algorithm has the same time complexity in every case?
a) stooge sort
b) strand sort
c) quick sort
d) bubble sort
Answer: a
Explanation: Stooge sort has the same time complexity of O(n2.7) in any case. This also shows that it is not
an adaptive sorting algorithm.
11. Which of the following sorting algorithm is worst in terms of time complexity?
a) bubble sort
b) selection sort
c) insertion sort
d) stooge sort
Answer: d
Explanation: Stooge sort has a time complexity of O(n2.7) which is the worst out of the given options. This
shows that stooge sort is even less efficient than bubble sort which is itself considered to be a very
inefficient sort.
Answer: c
Explanation: Stooge sort is not an adaptive sorting algorithm. This is because it does not perform better in
the case when the array is already/almost sorted.
b)
c)
d)
Answer: a
Explanation: Stooge sort compare first and last element of the array and switch them if found out of order.
Then
1. Which of the following is not an alternative name of permutation sort?
a) stupid sort
b) bogo sort
c) donkey sort
d) monkey sort
Answer: c
Explanation: Permutation sort is also known by names like stupid sort, monkey sort, bogo sort, slow sort and
shotgun sort. These names are particularly chosen due to its inefficient algorithm.
Answer: a
Explanation: Permutation sort algorithm successively generates permutations of its input. This process is
repeated until the sorted version of the array is found.
Answer: b
Explanation: Permutation sort algorithm does not require any extra space for sorting the input array. Thus its
auxiliary space requirement is O(1).
Answer: b
Explanation: Best case time complexity of permutation sort occurs when the input array is already sorted. So
in such a case we only need to check whether all the elements are sorted which can be done in O(n) time.
Answer: c
Explanation: There is no upper bound to the worst case of this algorithm. It can go on to take a very large
amount of time if the array has many elements. So the worst case of this algorithm can be taken as
O(infinity).
advertisement
6. Which of the following sorting algorithm is not stable __________
a) insertion sort
b) bubble sort
c) merge sort
d) bogosort
Answer: d
Explanation: Out of the given algorithms only bogosort is not stable. This is because it creates permutations
of the input array in order to obtain the sorted version. So there is no guarantee that the sorted version
obtained by such a method gives a stable output.
Answer: b
Explanation: Out of the given algorithms only permutation sort is an in-place sorting algorithm. It is because
the permutation sort algorithm does not require any extra space for sorting the input array.
8. Sleep sort should be preferred over permutation sort as it has better time complexity.
a) true
b) false
Answer: b
Explanation: If we sort an array using sleep sort then there is no guarantee that the output we get is correctly
sorted. So even though sleep sort is better than bogosort in time complexity but it cannot be preferred due to
its inaccuracy.
Answer: b
Explanation: For calculating the average we first need to calculate the number of possible permutations an
array of size n can have. This will be equal to n!. As each permutation also needs to be checked whether it is
sorted or not so this takes another n time. Thus overall time complexity becomes O(n*n!).
10. Which of the following code correctly implements the permutation sort algorithm?
a)
b)
c)
d)
Answer: a
Explanation: To implement permutation sort algorithm we need to shuffle the input array until we get the
sorted
1. Which of the following is an advantage of recursive bubble sort over its iterative version?
a) it has better time complexity
b) it has better space complexity
c) it is easy to implement
d) it has no significant advantage
Answer: d
Explanation: Recursive bubble sort has no significant advantage over iterative bubble sort. It is just a
different way to implement the same.
Answer: c
Explanation: Bubble sort is also referred to as sinking sort. It continuously compares the value of adjacent
elements as it traverses through an array and swaps the elements which are out of order.
3. What will be the recurrence relation of the code of recursive bubble sort?
a) T(n) = 2T(n/2) + n
b) T(n) = 2T(n/2) + c
c) T(n) = T(n-1) + n
d) T(n) = T(n-1) + c
Answer: c
Explanation: The recurrence relation of the code of recursive bubble sort is T(n) = T(n-1) + n. It can be
solved by the method of substitution and is found to be equal to n2.
Answer: b
Explanation: Odd even sort is a variation of bubble sort. But unlike bubble sort, odd even sort traverses the
array in two phases- odd phase and even phase.
Answer: a
Explanation: In bubble sort, we need to compare elements in order to find the minimum element in each
iteration. So we can say that it uses comparisons in order to sort the array. Thus it qualifies as a comparison
based sort.
Answer: c
Explanation: The overall recurrence relation of recursive bubble sort is given by T(n) = T(n-1) + n. It is
found to be equal to O(n2).
advertisement
Answer: a
Explanation: The best case time complexity of recursive bubble sort is O(n). It occurs in the case when the
input is already/almost sorted.
10. What are the number of swaps required to sort the array arr={1, 2, 4, 3, 7, 5, 6} using recursive bubble
sort?
a) 0
b) 1
c) 2
d) 3
Answer: d
Explanation: The first swap takes place between 4 and 3 then the second swap takes place between 7 and 5
and then finally 6 and 7 are swapped which sorts our array.
11. What will be the base case for the code of recursive bubble sort?
a)
if(n < 1)
return;
b)
if(n == 0)
return;
c)
if(n == 1)
return;
d)
If(n == 2)
return;
Answer: c
Explanation: The most appropriate condition for the base case of recursive bubble sort is when n equal 1
then return. It is because we know that an array with only 1 element is always sorted.
Answer: b
Explanation: The auxiliary space required by recursive bubble sort is O(1). So it qualifies as an in-place
sorting algorithm.
Answer: a
Explanation: Bubble sort is an adaptive algorithm. It is because the time complexity of the algorithm
improves when the input array is almost sorted.
Answer: a
Explanation: Out of the given options recursive bubble sort is the only algorithm which is in place. It is
because the auxiliary space required by recursive bubble sort is O(1).
b)
c)
Answer: a
Explanation: The base case of the recursive bubble sort should be 1 when equal 1 then return. It is because
we know that an array with only 1 element is always sorted. Also, we need to swap the adjacent eleme
1. Which of the following is an advantage of binary insertion sort over its standard version?
a) it has better time complexity
b) it has better space complexity
c) it makes less number of comparisons
d) it has no significant advantage
Answer: c
Explanation: Binary insertion sort makes less number of comparisons as compared to the standard version of
insertion sort. Binary insertion sort makes log n comparisons in the worst case as compared to n
comparisons made in the standard version.
Answer: a
Explanation: Binary Insertion sort does not require the entire input data at the beginning itself in order to
sort the array. It rather creates a partial solution in every step, so future elements are not required to be
considered. Hence it is an online sorting algorithm.
3. How many comparisons will be made in the worst case when an array of size n will be sorted by using a
binary insertion sort algorithm?
a) n
b) 1
c) log n
d) n log n
Answer: c
Explanation: Binary insertion sort makes log n comparisons in the worst case. Whereas the standard version
makes n comparisons in the worst case.
Answer: c
Explanation: Out of the given options binary insertion sort is the only algorithm which is stable. It is because
the elements with identical values appear in the same order in the output array as they were in the input
array.
Answer: b
Explanation: Binary insertion sort makes use of a binary search algorithm. It is used to find the correct index
in the array where the element should be inserted.
Answer: a
Explanation: In insertion sort, we need to compare elements in order to find the minimum element in each
iteration. So we can say that it uses comparisons in order to sort the array. Thus it qualifies as a comparison
based sort.
Answer: c
Explanation: The time complexity does not change when we use binary insertion sort in place of standard
insertion sort. So the average case time complexity is O(n2).
advertisement
Answer: a
Explanation: The best case time complexity of binary insertion sort is O(n). It occurs in the case when the
input is already/almost sorted.
Answer: c
Explanation: The time complexity does not change when we use binary insertion sort in place of standard
insertion sort. So the worst case time complexity is O(n2).
Answer: d
Explanation: Binary insertion sort has the advantage that it takes less number of comparisons in the worst
case as compared to the standard version. In the best case, both standard insertion sort and binary insertion
sort makes only 1 comparison.
11. What will be the base case in the function of binary search used in the code of binary insertion sort?
(high and low are the rightmost and leftmost index of array respectively and item is the element whose
correct position is to be determined by the binary search function)
a)
If(high<=low)
{
If(Item>a[low])
return low+1;
return low;
}
b)
If(high>=low)
{
If(Item<a[low])
return low+1;
return low;
}
c)
If(high<=low)
{
If(Item<a[low])
return low;
return low+1;
}
d)
If(high<=low)
{
If(Item>a[low])
return low;
return low+1;
}
Answer: c
Explanation: The base case of binary search has to be made such that even when the element is not found in
the array the function still returns the required index back to the function of insertion sort.
Answer: b
Explanation: The auxiliary space required by a binary insertion sort is O(1). So it qualifies as an in place
sorting algorithm.
Answer: a
Explanation: Binary insertion sort is an adaptive algorithm. It is because the time complexity of the
algorithm improves when the input array is almost sorted.
Answer: a
Explanation: Out of the given options binary insertion sort is the only algorithm which is in place. It is
because the auxiliary space required by recursive bubble sort is O(1).
b)
c)
d)
Answer: a
Explanation: The code of
1. Which of the following is an advantage of recursive insertion sort over its iterative version?
a) it has better time complexity
b) it has better space complexity
c) it is easy to implement
d) it has no significant advantage
Answer: d
Explanation: Recursive insertion sort has no significant advantage over iterative insertion sort. It is just a
different way to implement the same.
Answer: a
Explanation: Insertion sort does not require the entire input data in the beginning itself in order to sort the
array. It rather creates a partial solution in every step, so future elements are not required to be considered.
Hence it is an online sorting algorithm.
3. What will be the recurrence relation of the code of recursive insertion sort?
a) T(n) = 2T(n/2) + n
b) T(n) = 2T(n/2) + c
c) T(n) = T(n-1) + n
d) T(n) = T(n-1) + c
Answer: c
Explanation: The recurrence relation of the code of recursive insertion sort is T(n) = T(n-1) + n. It can be
solved by the method of substitution and is found to be equal to n2.
Answer: c
Explanation: Out of the given options insertion sort is the only algorithm which is stable. It is because the
elements with identical values appear in the same order in the output array as they were in the input array.
Answer: a
Explanation: In insertion sort, we need to compare elements in order to find the minimum element in each
iteration. So we can say that it uses comparisons in order to sort the array. Thus it qualifies as a comparison
based sort.
Answer: c
Explanation: The overall recurrence relation of recursive insertion sort is given by T(n) = T(n-1) + n. It is
found to be equal to O(n2).
advertisement
Answer: a
Explanation: The best case time complexity of recursive insertion sort is O(n). It occurs in the case when the
input is already/almost sorted.
Answer: c
Explanation: The overall recurrence relation of recursive insertion sort is given by T(n) = T(n-1) + n. It is
found to be equal to O(n2).
10. How many swaps will be required in the worst case to sort an array having n elements using binary
insertion sort?
a) n
b) 1
c) n * log n
d) log n
Answer: d
Explanation: In a normal insertion sort at most n comparisons are required to sort the array. But if we also
implement the concept of a binary sort in insertion sort then we can sort by having log n comparisons only.
11. What will be the base case for the code of recursive insertion sort ?
a)
if(n < 1)
return;
b)
if(n == 0)
return;
c)
if(n <= 1)
return;
d)
If(n == 2)
return;
Answer: c
Explanation: The most appropriate condition for the base case of recursive insertion sort is when n is less
than or equal 1 then return. It is because we know that an array with only 1 element is always sorted.
Answer: b
Explanation: The auxiliary space required by recursive insertion sort is O(1). So it qualifies as an in place
sorting algorithm.
Answer: a
Explanation: Insertion sort is an adaptive algorithm. It is because the time complexity of the algorithm
improves when the input array is almost sorted.
Answer: a
Explanation: Out of the given options recursive insertion sort is the only algorithm which is in place. It is
because the auxiliary space required by recursive bubble sort is O(1).
b)
c)
d)
Answer: a
Explanation: T
1. Which of the following data structure is required for the implementation of tree sort?
a) any ordinary tree
b) balanced tree
c) binary search tree
d) unbalanced tree
Answer: c
Explanation: Tree sort uses a binary search tree for sorting the given elements. Tree sort can also be
performed by using an unbalanced binary search tree.
Answer: a
Explanation: Tree sort does not require the entire input data at the beginning itself in order to sort the array.
It rather creates a partial solution in every step, so future elements are not required to be considered. Hence
it is an online sorting algorithm.
3. Which of the following traversal in a binary search tree results in a sorted output?
a) in order traversal
b) pre order traversal
c) post order traversal
d) breadth first traversal
Answer: a
Explanation: Tree sort uses a binary search tree for sorting the given elements. First a BST is formed by
using the input data elements and then the BST is traversed in an in order fashion which gives a sorted
output.
4. Which of the following sorting algorithm is stable?
a) Selection sort
b) Quick sort
c) Tree sort
d) Heap sort
Answer: c
Explanation: Out of the given options Tree sort is the only algorithm which is stable. It is because the
elements with identical values appear in the same order in the output array as they were in the input array.
Answer: b
Explanation: Tree sort makes use of a binary search tree. It is because every time when a BST is traversed in
an in order fashion it gives a sorted output.
advertisement
Answer: a
Explanation: In tree sort, we need to compare elements as we insert them in the binary search tree. Thus it
qualifies as a comparison based sort.
Answer: b
Explanation: As on an average every element takes log n time for insertion in a binary search tree so for n
elements O(n log n) time will be required on an average.
Answer: b
Explanation: The best case time complexity of tree sort is the same as its average case complexity. So best
case time complexity is O(n log n).
9. What is the worst case time complexity of tree sort (when implemented with a balanced tree)?
a) O(n)
b) O(n log n)
c) O(n2)
d) O(log n)
Answer: b
Explanation: The worst case time complexity of tree sort depends on whether the tree used in the
implementation is balanced or not. If the tree is balanced then the worst case complexity is O(n log n).
10. What is the worst case time complexity of tree sort (when implemented with an unbalanced tree)?
a) O(n)
b) O(n log n)
c) O(n2)
d) O(log n)
Answer: c
Explanation: The worst case time complexity of tree sort depends on whether the tree used in the
implementation is balanced or not. If the tree is unbalanced then the worst case complexity is O(n2).
Answer: b
Explanation: Tree sort requires auxiliary space for maintaining a binary search tree. So the auxiliary space
complexity of tree sort is O(n).
12. In which of the following case does a tree sort become adaptive?
a) when implemented with an unbalanced tree
b) when implemented with a balanced tree
c) when implemented with a splay tree as BST
d) when implemented with AVL tree as BST
Answer: c
Explanation: Tree sort becomes an adaptive sort when it is implemented with a splay tree as a BST. In such
a case the best case time complexity is better than (n log n).
Answer: b
Explanation: Every implementation of tree sort is not adaptive. It becomes adaptive only when implemented
with a splay tree as BST.
14. Which of the following sorting algorithm is not in place?
a) insertion sort
b) quick sort
c) tree sort
d) gnome sort
Answer: c
Explanation: Out of the given options tree sort is the only algorithm which is not in place. It is because the
auxiliary space required by tree sort is O(n).
15. The worst case time complexity of tree sort remains unaffected when implemented with an unbalanced
tree or a balanced tree.
a) True
b) False
Answer: b
Explanation: The time complexity of tree sort is affected when implemented with an unbalanced tree or a
balanced tree. In case of a balanced tree it is O(n log n) and in case of unbalanced tree it is O(n2).
Answer: a
Explanation: Tree sort has a linear time complexity O(n) which makes it inefficient. This the main reason
why sorting algorithms like quick sort, heap sort etc. are preferred over it.
17. Which of the following version of tree sort will have the highest worst case time complexity?
a) using AVL tree as BST
b) using red black tree as BST
c) using splay tree as BST
d) using ordinary BST
Answer: d
Explanation: Out of the given options tree sort has the highest worst case time complexity with ordinary BS
Answer: a
Explanation: The string matching algorithm which was proposed by Rabin and Karp, generalizes to other
algorithms and for two-dimensional pattern matching problems.
Answer: c
Explanation: The for loop in the pre-processing algorithm runs for m(length of the pattern) times. Hence the
pre-processing time is Theta(m).
Answer: a
Explanation: Rabin Karp Algorithm makes use of elementary theoretic number notions such as the
equivalence of two numbers modulo a third number.
4. What is the basic formula applied in Rabin Karp Algorithm to get the computation time as Theta(m)?
a) Halving rule
b) Horner’s rule
c) Summation lemma
d) Cancellation lemma
Answer: b
Explanation: The pattern can be evaluated in time Theta(m) using Horner’s rule:
p = P[m] + 10(P[m-1] + 10(P[m-2] +…+ 10(P[2]+10P[1])…)).
Answer: c
Explanation: The worst case running time of Rabin Karp Algorithm is Theta(n-m+1)m). We write Theta(n-
m+1) instead of Theta(n-m) because there are n-m+1 different values that the given text takes on.
Answer: a
Explanation: Since Rabin-Karp algorithm is a pattern detecting algorithm in a text or string, it can be used
for detecting plagiarism in a sentence.
7. If n is the length of text(T) and m is the length of the pattern(P) identify the correct pre-processing
algorithm. (where q is a suitable modulus to reduce the complexity)
p=0; t0=0;
a)
advertisement
for i=1 to n
do t0=(dt0 + P[i])mod q
p=(dp+T[i])mod q
b)
for i=1 to n
do p=(dp + P[i])mod q
t0=(dt0+T[i])mod q
c)
for i=1 to m
do t0=(dp + P[i])mod q
p=(dt0+T[i])mod q
d)
for i=1 to m
do p=(dp + P[i])mod q
t0=(dt0+T[i])mod q
Answer: d
Explanation: The pre-processing algorithm runs m (the length of pattern) times. This algorithm is used to
compute p as the value of P[1….m] mod q and t0 as the value of T[1….m]mod q.
8. If n is the length of text(T) and m is the length of the pattern(P) identify the correct matching algorithm.
a)
for s=0 to n
do if p=t0
then if P[1..m]=T[s+1..s+m]
then print “Pattern occurs with shift” s
b)
c)
for s=0 to m
do if p=ts
then if P[1..m]=T[s+1..s+m]
then print “Pattern occurs with shift” s
d)
Answer: b
Explanation: The matching algorithm runs for n-m times. Rabin Karp algorithm explicitly verifies every
valid shift. If the required pattern matches with the given text then the algorithm prints pattern found as
result.
Answer: c
Explanation: If the modulo value(q) is large enough then the spurious hits occur infrequently enough that the
cost of extra checking is low.
10. Given a pattern of length-5 window, find the suitable modulo value.
4 3 2 5 0
a) 13
b) 14
c) 12
d) 11
Answer: a
Explanation: The modulus q is typically chosen as a prime number that is large enough to reduce the
complexity when p is very large.
11. Given a pattern of length- 5 window, find the valid match in the given text.
Pattern: 2 1 9 3 6
Modulus: 21
Index: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
Text: 9 2 7 2 1 8 3 0 5 7 1 2 1 2 1 9 3 6 2 3 9 7
a) 11-16
b) 3-8
c) 13-18
d) 15-20
Answer: c
Explanation: The pattern 2 1 9 3 6 occurs in the text starting from position 13 to 18. In the given pattern
value is computed as 12 by having the modulus as 21. The same text string values are computed for each
possible position of a 5 length window.
12. Given a pattern of length- 5 window, find the spurious hit in the given text string.
Pattern: 3 1 4 1 5
Modulus: 13
Index: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Text: 2 3 5 9 0 2 3 1 4 1 5 2 6 7 3 9 9 2 1 3 9
a) 6-10
b) 12-16
c) 3-7
d) 13-17
Answer: d
Explanation: The sub string in the range 13-17, 6 7 3 9 9 produces the same value 7 as the given pattern. But
the pattern numbers don’t match with sub string identified, hence it is a spurious hit.
13. If the expected number of valid shifts is small and modulus is larger than the length of pattern what is the
matching time of Rabin Karp Algorithm?
a) Theta(m)
b) Big-Oh(n+m)
c) Theta(n-m)
d) Big-Oh(n)
Answer: b
Explanation: When the number of valid shifts(v) is Big-Oh(1) and q>=m then the matching time is given by
O(n)+O(m(v+n/q)) is simplified as O(n+m).
Answer: a
Explanation: The basic principle employed in Rabin Karp algorithm is hashing. In the given text every
substring is converted to a hash value and compared with the hash value of the pattern.
Answer: c
Explanation: Rabin Karp algorithm was invented by Richard Karp and Michael Rabin in the year 1987 for
searching a pat
Answer: c
Explanation: Quick search algorithm is the fastest algorithm in string matching field whereas Linear search
algorithm searches for an element in an array of elements.
2. Which of the following algorithms formed the basis for the Quick search algorithm?
a) Boyer-Moore’s algorithm
b) Parallel string matching algorithm
c) Binary Search algorithm
d) Linear Search algorithm
Answer: a
Explanation: Quick search algorithm was originally formed to overcome the drawbacks of Boyer-Moore’s
algorithm and also for increased speed and efficiency.
Answer: c
Explanation: The time complexity of the Quick search algorithm was found to be O(m+n) and is proved to
be faster than Boyer-Moore’s algorithm.
Answer: b
Explanation: Quick search algorithm uses only bad character shift tables and it is one of the reasons for its
increased speed than Boyer-Moore’s algorithm.
Answer: a
Explanation: The space complexity of quick search algorithm is mathematically found to be O(n) where n
represents the input size.
advertisement
6. Quick search algorithm starts searching from the right most character to the left.
a) true
b) false
Answer: b
Explanation: Quick search algorithm starts searching from the left most character to the right and it uses
only bad character shift tables.
Answer: d
Explanation: Boyer-Moore’s search algorithm uses both good and bad character shift tables whereas quick
search algorithm uses only bad character shift tables.
8. What is the worst case running time in searching phase of Boyer-Moore’s algorithm?
a) O(n)
b) O(log n)
c) O(m+n)
d) O(mn)
Answer: d
Explanation: If the pattern occurs in the text, the worst case running time of Boyer-Moore’s algorithm is
found to be O(mn).
9. The searching phase in quick search algorithm has good practical behaviour.
a) true
b) false
Answer: a
Explanation: During the searching phase, the comparison between pattern and text characters can be done in
any order. It has a quadratic worst case behaviour and good practical behaviour.
10. Given input string = “ABCDABCATRYCARCABCSRT” and pattern string = “CAT”. Find the first
index of the pattern match using quick search algorithm.
a) 2
b) 6
c) 11
d) 14
Answer: b
Explanation: By using quick search algorithm, the given input text string is preprocessed and starts its search
from the left most ch
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
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.
advertisement
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
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
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
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)
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
Explana
Answer: b
Explanation: Strassen’s Algorithm for matrix multiplication is a recursive algorithm since the present output
depends on previous outputs and inputs.
Answer: a
Explanation: Strassen’s matrix algorithm requires only 7 recursive multiplications of n/2 x n/2 matrix and
Theta(n2) scalar additions and subtractions yielding the running time as O(n2.81).
Answer: d
Explanation: The traditional matrix multiplication algorithm takes O(n3) time. The number of recursive
multiplications involved in this algorithm is 8.
Answer: c
Explanation: Strassen’s matrix multiplication algorithm follows divide and conquer technique. In this
algorithm the input matrices are divided into n/2 x n/2 sub matrices and then the recurrence relation is
applied.
5. The number of scalar additions and subtractions used in Strassen’s matrix multiplication algorithm is
________
a) O(n2.81)
b) Theta(n2)
c) Theta(n)
d) O(n3)
Answer: b
Explanation: Using Theta(n2) scalar additions and subtractions, 14 matrices are computed each of which is
n/2 x n/2. Then seven matrix products are computed recursively.
advertisement
6. Running time of Strassen’s algorithm is better than the naïve Theta(n3) method.
a) True
b) False
Answer: a
Explanation: Strassen’s Algorithm requires only 7 recursive multiplications when compared with the naïve
Theta(n3) method which reuires 9 recursive multiplications to compute the product.
for i=1 to n do
for j=1 to n do
Z[i][j]=0;
for k=1 to n do
___________________________
Answer: a
Explanation: In the naïve method of matrix multiplication the number of iterating statements involved are 3,
because of the presence of rows and columns. The element in each row of one matrix is multiplied with each
element in the column of the second matrix. The computed value is placed in the new matrix Z[i][j].
Answer: a
Explanation: The recurrence relation used in Strassen’s algorithm is 7T(n/2) + Theta(n2) since there are only
7 recursive multiplications and Theta(n2) scalar additions and subtractions involved for computing the
product.
10. Who discussed techniques for reducing the memory requirements for Strassen’s algorithm?
a) Strassen
b) Lederman
c) Bailey
d) Higham
Answer: c
Explanation: The submatrices formed at the levels of recursion consume space. Hence in order to overcome
that Bailey discussed techniques for reducing the memory required.
11. What is the formula to calculate the element present in second row, first column of the product matrix?
a) M1+M7
b) M1+M3
c) M2+M4 – M5 + M7
d) M2+M4
Answer: d
Explanation: The element at second row, first column can be found by the formula M2 + M4, where M2 and
M4 can be calculated by
M2= (A(2,1) + A(2,2)) B(1,1)
M4=A(2,2)(B(1,2) – B(1,1)).
Answer: a
Explanation: Strassen’s matrix multiplication algorithm was first published by Volker Strassen in the year
1969 and proved that the n3 general matrix multiplication algorithm wasn’t optimal.
13. How many iterating statements are involved in the naïve method of matrix multiplication?
a) 1
b) 2
c) 3
d) 4
Answer: c
Explanation: In the naïve method of matrix multiplication the number of iterating statements involved are 3,
because of the presence of rows and columns in a matrix. The element in each row of the first matrix is
multiplied with each element in the column of the second matrix.
Answer: b
Explanation: Strassen’s algorithm is too numerically unstable for some applications. The computed result
C=AB satisfies the inequality with a unit roundoff error which corresponds to strong stability
inequality(obtained by replacing matrix norms with absolute values of the matrix elements).
15. Compute the product matrix using Strassen’s matrix multiplication algorithm.
Given a11=1; a12=3;a21=5;a22=7
b11=8;b12=4;b21=6;b22=2
a) c11=20;c12=12;c21=100;c22=15
b) c11=22;c12=8;c21=90;c22=32
c) c11=15;c12=7;c21=80;c22=34
d) c11=26;c12=10;c21=82;c22=34
Answer: d
Explanation: The solution can be obtained by
C11=1*8 + 3*6 =8+18=26
C12=1*4 + 3*2 =4
Answer: a
Explanation: A pseudo random number generator generates random numbers with the help of a
mathematical formula. We can seed the random number generator with a different value everytime if we
want unique random numbers to be generated.
Answer: a
Explanation: The return type of rand () is int. It can generate random numbers from 0 to RAND_MAX.
3. What is the purpose of using function srand()?
a) to set the seed of rand() function
b) to generate random numbers
c) to enable rand() function
d) to improve efficiency of rand()
Answer: a
Explanation: The function srand() sets the seed of rand(). It can be used to generate a unique set of random
numbers every time.
Answer: a
Explanation: The function rand() generates random numbers in the range 0 to RAND_MAX. The value of
RAND_MAX is minimum 32,767.
5.What is the correct formula for generating random numbers in the range (lower,upper) using rand()?
a) rand() % (upper – lower)
b) rand() + lower
c) (rand()%(upper-lower)) + lower
d) (rand()%(upper-lower+1)) + lower
Answer: d
Explanation: The correct formula for generating random numbers in the range (lower,upper) using rand() is
(rand()%(upper-lower+1)) + lower. The function rand() generates random numbers in the range 0 to
RAND_MAX.
6. Which of the following will generate random numbers in the range 1-100 (both inclusive)?
a) rand() % 100
b) rand() % 101
c) (rand() % (101)) + 1
d) (rand() % (100)) + 1
Answer: d
Explanation: Formula for generating random numbers in the range (lower,upper) using rand() is (rand()%
(upper-lower+1)) + lower. So the correct answer will be (rand() % (100)) + 1.
Answer: b
Explanation: The value of RAND_MAX varies according to implementation. But it is guaranteed to be at
least 32767.
advertisement
8. Function rand() generates unique random numbers every time.
a) true
b) false
Answer: b
Explanation: Function rand() does not generate unique random numbers every time. For achieving this we
have to use srand() along with rand().
9. What is the default value of seed if function rand() is called before srand()?
a) srand(0)
b) srand(1)
c) srand(time(null))
d) srand(-1)
Answer: b
Explanation: If srand() is not called before the call to the function rand() then the value of seed is taken as
srand(1) by default. We should use srand() before rand() in order to use our own seed.
10. Pseudo random number generators can be used for data encryption.
a) true
b) false
Answer: b
Explanation: Pseudo random number generators cannot be used for data encryption as the random numbers
generated by them are predictable. For data encryption the numbers should be absolutely unpredictable.
#include <stdlib.h>
int main()
{
srand(0);
printf("%d\n", rand());
return 0;
}
a) compilation error
b) random number between 0 to RAND_MAX
c) cannot be predicted
d) 0
Answer: b
Explanation: The function rand() generates random numbers in the range 0 to RAND_MAX. The function
srand() seeds rand(). We get unique set of random numbers if rand() is seeded with a different value every
time.
#include <stdlib.h>
int main()
{
srand(0);
printf("%d\n", rand()%50);
return 0;
}
a) compilation error
b) random number between 0 to 50 (both inclusive)
c) random number between 0 to 51 (both inclusive)
d) random number between 0 to 49 (both inclusive)
Answer: d
Explanation: Formula for generating random numbers in the range (lower,upper) using rand() is (rand()%
(upper-lower+1)) + lower. So the given code will generate random numbers between 0 to 49.
14. Which of the following code will generate unique random numbers every time?
a)
#include <stdlib.h>
int main()
{
srand(0);
printf("%d\n", rand()%50);
return 0;
}
b)
#include <stdlib.h>
int main()
{
srand(time(0));
printf("%d\n", rand()%50);
return 0;
}
c)
#include <stdlib.h>
int main()
{
srand(1);
printf("%d\n", rand()%50);
return 0;
}
d)
#include <stdlib.h>
int main()
{
printf("%d\n", rand()%50);
return 0;
}
Answer: b
Explanation: The function rand() generates random numbers in the range 0 to RAND_MAX. The function
srand() seeds rand(). We get a unique set of random numbers if rand() is seeded with a different value every
time. This can be achieved by using srand(time(0)).
#include <stdlib.h>
int main()
{
printf("%d\n", srand());
return 0;
}
b)
#include <stdlib.h>
int main()
{
srand(time(0));
printf("%d\n", rand()%50);
return 0;
}
c)
#include <stdlib.h>
int main()
{
srand(1);
return 0;
}
d)
#include <stdlib.h>
int main()
{
printf("%d\n", rand()%50);
return 0;
}
Answer: a
Explanatio
Answer: c
Explanation: No.of permutations for an array of size n will be given by the formula nPn. So for the given
problem, we have 3P3=6 or 3!=6.
3. What will be the lexicographical order of permutations formed from the array arr={1,2,3}?
a) {{2,1,3},{3,2,1},{3,1,2},{2,3,1},{1,2,3},{1,3,2}}
b) {{1,2,3},{1,3,2},{2,3,1},{2,1,3},{3,2,1},{3,1,2}}
c) {{1,2,3},{1,3,2},{2,1,3},{2,3,1},{3,1,2},{3,2,1}}
d) {{2,1,3},{3,1,2},{3,2,1},{2,3,1},{1,2,3},{1,3,2}}
Answer: c
Explanation: The number of permutations for the problem will be 6 according to the formula 3P3. When
ordered in lexicographical manner these will be {{1,2,3},{1,3,2},{2,1,3},{2,3,1},{3,1,2},{3,2,1}}.
4. What is the name given to the algorithm depicted in the pseudo code below?
a) bubble sort
b) heap sort
c) heap’s algorithm
d) prim’s algorithm
Answer: c
Explanation: The given algorithm is called Heap’s algorithm. It is used for generating permutations of a
given list.
advertisement
Answer: d
Explanation: The recurrence relation for the heap’s algorithm is given by the expression T(n)=n * T(n-1). It
is calculated by using substitution method. It is found to be equal to O(n!).
#include <stdio.h>
#include <string.h>
#include<iostream>
using namespace std;
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void func(char *a, int l, int r)
{
int i;
if (l == r)
cout<<a<<” ,”;
else
{
for (i = l; i <= r; i++)
{
swap((a+l), (a+i));
func(a, l+1, r);
swap((a+l), (a+i));
}
}
}
int main()
{
char str[] = "AB";
int n = strlen(str);
func(str, 0, n-1);
return 0;
}
a) AB,BA,
b) BA,AB,
c) AB,BA
d) BA,AB,
Answer: a
Explanation: The given code prints the permutations of the an array. So there will be 2 permutations for an
array of 2 elements. Note that the comma is printed even for the last permutation.
#include <stdio.h>
#include <string.h>
#include<iostream>
using namespace std;
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void func(char *a, int l, int r)
{
int i;
if (l == r)
cout<<a<<” ,”;
else
{
for (i = l; i <= r; i++)
{
swap((a+l), (a+i));
func(a, l+1, r);
swap((a+l), (a+i));
}
}
}
int main()
{
char str[] = "AB";
int n = strlen(str);
func(str, 0, n-1);
return 0;
}
a) O(n2)
b) O(n * n!)
c) O(n!)
d) O(n log n)
Answer: b
Explanation: The recurrence relation for the heap’s algorithm is given by the expression T(n)=n * T(n-1).
But as each permutations takes n time to be printed so the overall complexity will be O(n*n!).
#include <iostream>
#include<string>
using namespace std;
void func1(string input,string output)
{
if(input.length()==0)
{
cout<<output<<",";
return;
}
for(int i=0;i<=output.length();i++)
func1(input.substr(1),output.substr(0,i) + input[0] + output.substr(i));
}
int main()
{
char str[] = "AB";
func1(str, "");
return 0;
}
a) AA,BA,
b) AB,BA,
c) BA,AB,
d) AB,AB,
Answer: c
Explanation: The given code prints the permutations of the an array. So there will be 2 permutations for an
array of 2 elements. In this code the difference is that BA is printed before AB. Note that the comma is
printed even for the last permutation.
#include <stdio.h>
#include <string.h>
#include<iostream>
using namespace std;
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void func(char *a, int l, int r)
{
int i;
if (l == r)
cout<<a<<” ,”;
else
{
for (i = l; i <= r; i++)
{
swap((a+l), (a+i));
func(a, l+1, r);
swap((a+l), (a+i));
}
}
}
int main()
{
char str[] = "AA";
int n = strlen(str);
func(str, 0, n-1);
return 0;
}
a) AA,
b) AA,AA
c) A,A
d) AA,AA,
Answer: d
Explanation: The given code prints the permutations of the given array but it is not able to handle duplicates
due to which it prints 2P2 permutations even in this case. So the output becomes AA,AA,.
11. What will be the output of the code that generates permutations and also has the ability to handle
duplicates, for the input str[]=”AA”?
a) AA
b) AA,AA
c) A,A
d) A
Answer: a
Explanation: If a code is able to handle duplicates then the two A’s are not considered to be different
elements due to whic
Answer: a
Explanation: Lexicographical order is also known as dictionary order. It is a generalized method of the way
words are alphabetically ordered in a dictionary.
2. How many combinations of 2 elements will be formed from the array arr={1,2,3}?
a) 1
b) 2
c) 3
d) 4
Answer: c
Explanation: No.of combinations of r elements for an array of size n will be given by the formula nCr. So
for the given problem, we have 3C2=3.
3. What will be the lexicographical order of combinations of 2 elements each formed from the array
arr={1,2,3}?
a) {{2,1},{3,2},{3,1}}
b) {{1,2},{2,3},{1,3}}
c) {{1,2},{1,3},{2,3}}
d) {{2,1},{3,1},{3,2}}
Answer: c
Explanation: The number of combinations for the problem will be 3 according to the formula 3C2. When
ordered in lexicographical manner these will be {{1,2},{1,3},{2,3}}.
4. What will be the auxiliary space requirement (excluding call stack) of the program to print combinations
of r elements each from array of size n?
a) O(n*r)
b) O(n/r)
c) O(n)
d) O(r)
Answer: d
Explanation: Code to print combinations will require an auxiliary space of O(r) other than call stack
memory. This memory is required by an array that is used for storing combinations formed.
Answer: b
Explanation: Code to print combinations will require an auxiliary space of O(r) other than call stack
memory. So it is not an in-place algorithm.
Answer: d
Explanation: The recurrence relation of the code to print combinations will be T(n)=2T(n-1)+k. It is found to
be equal to O(2n).
advertisement
#include<stdio.h>
void combination(int arr[],int n,int r,int index,int aux[],int i);
void print(int arr[], int n, int r)
{
int aux[r];
combination(arr, n, r, 0, aux, 0);
}
void combination(int arr[], int n, int r, int index, int aux[], int i)
{
if (index == r)
{
for (int j=0; j<r; j++)
printf("%d ",aux[j]);
printf(", ");
return;
}
if (i >= n)
return;
aux[index] = arr[i];
combination(arr, n, r, index+1, aux, i+1);
combination(arr, n, r, index, aux, i+1);
}
int main()
{
int arr[] = {1, 2,2};
int r = 2;
int n = sizeof(arr)/sizeof(arr[0]);
print(arr, n, r);
return 0;
}
a) 1 2, 1 2, 2 2
b) 1 2, 1 2, 2 2 ,
c) 1 2, 2 1, 2 2 ,
d) 1 2, 2 1, 2 2
Answer: b
Explanation: The given code prints the combinations of the given array in lexicographical order.The given
code considers the duplicate 2s as different entities.Note that the comma is printed even for the last
combination.
#include <stdio.h>
void combination(int arr[], int aux[], int start, int end, int index, int r);
void print(int arr[], int n, int r)
{
int aux[r];
combination(arr, aux, 0, n-1, 0, r);
}
void combination(int arr[], int aux[], int start, int end,
int index, int r)
{
if (index <= r)
{
for (int j=0; j<r; j++)
printf("%d ", aux[j]);
printf(", ");
return;
}
for (int i=start; i<=end && end-i+1 >= r-index; i++)
{
aux[index] = arr[i];
combination(arr, aux, i+1, end, index+1, r);
}
}
int main()
{
int arr[] = {1, 2, 3};
int r = 2;
int n = sizeof(arr)/sizeof(arr[0]);
print(arr, n, r);
}
b)
#include <stdio.h>
void combination(int arr[], int aux[], int start, int end,
int index, int r);
void print(int arr[], int n, int r)
{
int aux[r];
combination(arr, aux, 0, n-1, 0, r);
}
void combination(int arr[], int aux[], int start, int end,
int index, int r)
{
if (index == r)
{
for (int j=0; j<r; j++)
printf("%d ", aux[j]);
printf(", ");
return;
}
for (int i=start; i<=end && end-i+1 >= r-index; i++)
{
aux[index] = arr[i];
combination(arr, aux, i+1, end, index+1, r);
}
}
int main()
{
int arr[] = {1, 2, 3};
int r = 2;
int n = sizeof(arr)/sizeof(arr[0]);
print(arr, n, r);
}
c)
#include <stdio.h>
void combination(int arr[], int aux[], int start, int end,
int index, int r);
void print(int arr[], int n, int r)
{
int aux[r];
combination(arr, aux, 0, n-1, 0, r);
}
void combination(int arr[], int aux[], int start, int end,
int index, int r)
{
if (index == r)
{
for (int j=0; j<r; j++)
printf("%d ", aux[j]);
printf(", ");
return;
}
for (int i=start; i<=end ; i++)
{
aux[index] = arr[i];
combination(arr, aux, i+1, end, index+1, r);
}
}
int main()
{
int arr[] = {1, 2, 3};
int r = 2;
int n = sizeof(arr)/sizeof(arr[0]);
print(arr, n, r);
}
d)
#include <stdio.h>
void combination(int arr[], int aux[], int start, int end,
int index, int r);
void print(int arr[], int n, int r)
{
int aux[r];
combination(arr, aux, 0, n-1, 0, r);
}
void combination(int arr[], int aux[], int start, int end,
int index, int r)
{
if (index <= r)
{
for (int j=0; j<r; j++)
printf("%d ", aux[j]);
printf(", ");
return;
}
for (int i=start; i<=end; i++)
{
aux[index] = arr[i];
combination(arr, aux, i+1, end, index+1, r);
}
}
int main()
{
int arr[] = {1, 2, 3};
int r = 2;
int n = sizeof(arr)/sizeof(arr[0]);
print(arr, n, r);
}
Answer: b
Explanation: In the code we start from first index (index = 0) in array aux and one by one fix elements at this
index and recur for remaining indexes. Finally, when index becomes equal to r we print the combination.
#include<stdio.h>
void combination(int arr[],int n,int r,int index,int aux[],int i);
void print(int arr[], int n, int r)
{
int aux[r];
combination(arr, n, r, 0, aux, 0);
}
void combination(int arr[], int n, int r, int index, int aux[], int i)
{
if (index == r)
{
for (int j=0; j<r; j++)
printf("%d ",aux[j]);
printf(", ");
return;
}
if (i >= n)
return;
aux[index] = arr[i];
combination(arr, n, r, index+1, aux, i+1);
combination(arr, n, r, index, aux, i+1);
}
int main()
{
int arr[] = {1, 2,2};
int r = 2;
int n = sizeof(arr)/sizeof(arr[0]);
print(arr, n, r);
return 0;
}
b)
#include<stdio.h>
void combination(int arr[],int n,int r,int index,int aux[],int i);
void print(int arr[], int n, int r)
{
int aux[r];
combination(arr, n, r, 0, aux, 0);
}
void combination(int arr[], int n, int r, int index, int aux[], int i)
{
if (index == r)
{
for (int j=0; j<r; j++)
printf("%d ",aux[j]);
printf(", ");
return;
}
if (i >= n)
return;
aux[index] = arr[i];
combination(arr, n, r, index+1, aux, i+1);
combination(arr, n, r, index+1, aux, i+1);
}
int main()
{
int arr[] = {1, 2,2};
int r = 2;
int n = sizeof(arr)/sizeof(arr[0]);
print(arr, n, r);
return 0;
}
c)
#include<stdio.h>
void combination(int arr[],int n,int r,int index,int aux[],int i);
void print(int arr[], int n, int r)
{
int aux[r];
combination(arr, n, r, 0, aux, 0);
}
void combination(int arr[], int n, int r, int index, int aux[], int i)
{
if (index == r)
{
for (int j=0; j<r; j++)
printf("%d ",aux[j]);
printf(", ");
return;
}
if (i >= n)
return;
aux[index] = arr[i];
combination(arr, n, r, index-1, aux, i+1);
combination(arr, n, r, index, aux, i+1);
}
int main()
{
int arr[] = {1, 2,2};
int r = 2;
int n = sizeof(arr)/sizeof(arr[0]);
print(arr, n, r);
return 0;
}
d)
#include<stdio.h>
void combination(int arr[],int n,int r,int index,int aux[],int i);
void print(int arr[], int n, int r)
{
int aux[r];
combination(arr, n, r, 0, aux, 0);
}
void combination(int arr[], int n, int r, int index, int aux[], int i)
{
if (index == r)
{
for (int j=0; j<r; j++)
printf("%d ",aux[j]);
printf(", ");
return;
}
if (i >= n)
return;
aux[index] = arr[i];
combination(arr, n, r, index, aux, i+1);
combination(arr, n, r, index+1, aux, i+1);
}
int main()
{
int arr[] = {1, 2,2};
int r = 2;
int n = sizeof(arr)/sizeof(arr[0]);
print(arr, n, r);
return 0;
}
Answer: a
Explanation: In this method we consider each method one by one and recur for two cases.In first case we
include that element in our array and in second case we don’t .When the number of elements in the array
aux[] becomes equal to r then we print that combination.
#include <stdio.h>
void combination(int arr[], int aux[], int start, int end, int index, int r);
void print(int arr[], int n, int r)
{
int aux[r];
combination(arr, aux, 0, n-1, 0, r);
}
void combination(int arr[], int aux[], int start, int end, int index, int r)
{
if (index == r)
{
for (int j=0; j<r; j++)
printf("%d ", aux[j]);
printf(", ");
return;
}
for (int i=start; i<=end && end-i+1 >= r-index; i++)
{ aux[index] = arr[i];
combination(arr, aux, i+1, end, index+1, r);
}
}
int main()
{
int arr[] = {1, 2, 3};
int r = 2;
int n = sizeof(arr)/sizeof(arr[0]);
print(arr, n, r);
}
a) 1 2, 1 3, 2 3
b) 1 3,1 2,2 3,
c) 1 2, 1 3, 2 3,
d) 1 2,1 3,2 3,
Answer: c
Explanation: The given code prints the combinations of the given array in lexicographical order.Note that
the comma is printed even for the last combination.
#include <stdio.h>
#include <stdlib.h>
void combination(int arr[], int aux[], int start, int end, int index, int r);
int compare (const void * a, const void * b)
{ return ( *(int*)a - *(int*)b ); }
void print(int arr[], int n, int r)
{
int aux[r];
qsort (arr, n, sizeof(int), compare);
combination(arr, aux, 0, n-1, 0, r);
}
void combination(int arr[], int aux[], int start, int end, int index, int r)
{
if (index == r)
{
for (int i=0; i<r; i++)
printf("%d " ,aux[i]);
printf(", ");
return;
}
for (int i=start; i<=end && end-i+1 >= r-index; i++)
{
aux[index] = arr[i];
combination(arr, aux, i+1, end, index+1, r);
while (arr[i] == arr[i+1])
i++;
}
}
int main()
{
int arr[] = {1, 2, 2};
int r = 2;
int n = sizeof(arr)/sizeof(arr[0]);
print(arr, n, r);
}
a) 1 2, 1 2,2 2,
b) 1 2, 2 1, 2 2,
c) 1 2, 2 2,
d) 1 2, 2 2, 2 1,
Answer: c
Explanation:The giv
Answer: c
Explanation: Integer partition is the way of representing an integer as sum of positive integers. Partitions
differing only in their order are considered to be same.
Answer: b
Explanation: We need to find the combinations of positive integers which give 3 as their sum. These will be
{3}, {2,1}, {1,1,1}. Thus the correct answer is 3.
Answer: a
Explanation: Number theory is a branch of mathematics that deals with the study of integers. Partitioning of
a number comes under the study of number theory.
Answer: b
Explanation: Ramanujan’s congruence are some relations found for the no. of partitions of an integer.
According to it, the number of partitions of an integer is divisible by 5 if that integer is 4 more than a
multiple of 5.
#include<iostream>
using namespace std;
void printArray(int p[], int n)
{
for (int i = 0; i <= n-1; i++)
cout << p[i] << " ";
cout << endl;
}
void func1(int n)
{
int p[n];
int k = 0;
p[k] = n;
while (true)
{
printArray(p, k+1);
int rem_val = 0;
while (k >= 0 && p[k] == 1)
{
rem_val += p[k];
k--;
}
if (k < 0) return;
p[k]--;
rem_val++;
while (rem_val > p[k])
{
p[k+1] = p[k];
rem_val = rem_val - p[k];
k++;
}
p[k+1] = rem_val;
k++;
}
}
int main()
{
int n=3;
func1(n);
return 0;
}
a)
3
1 2
1 1 1
Join [email protected]
b)
1 1 1
2 1
3
c)
1 1 1
1 2
3
d)
3
2 1
1 1 1
Answer: d
Explanation: The given code prints the partition of a number in decreasing order. This code uses the
approach of dynamic programming.
Answer: b
Explanation: Partitions differing in order are considered to be same. Thus 2 1 and 1 2 are considered to be
same when we generate partitions of integer 3.
#include<iostream>
using namespace std;
void printArray(int p[], int n)
{
for (int i = 0; i <= n-1; i++)
cout << p[i] << " ";
cout << endl;
}
void func1(int n)
{
int p[n];
int k = 0;
p[k] = n;
while (true)
{
printArray(p, k+1);
int rem_val = 0;
while (k >= 0 && p[k] == 1)
{
rem_val += p[k];
k--;
}
if (k < 0) return;
p[k]--;
rem_val++;
while (rem_val > p[k])
{
p[k+1] = p[k];
rem_val = rem_val - p[k];
k++;
}
p[k+1] = rem_val;
k++;
}
}
int main()
{
int n;
cin>>n;
func1(n);
return 0;
}
a) greedy approach
b) dynamic programming
c) recursion(divide and conquer)
d) backtracking
Answer: b
Explanation: The given code prints the partition of a number in decreasing order. This code uses the
approach of dynamic programming. We can also use recursion for fulfilling the same purpose.
#include<iostream>
using namespace std;
int list[200];
void func(int n, int m = 0)
{
int i;
if(n == 0)
{
for(i = 0; i < m; ++i)
printf("%d ", list[i]);
printf("\n");
return;
}
for(i = n; i > 0; --i)
{
if(m == 0 || i <= list[m - 1])
{
list[m] = i;
func(n - i, m + 1);
}
}
}
int main()
{
int n=3;
func(n,0);
return 0;
}
a)
3
2 1
1 1 1
b)
1 1 1
2 1
3
c)
1 1 1
1 2
3
d)
3
1 2
1 1 1
Answer: a
Explanation: The given code prints the partition of a number in decreasing order. This code uses the
approach of recursion. The same purpose can be fulfilled by using dynamic programming.
10. Which of the following correctly represents the code to print partitions of a number?
a)
#include<iostream>
using namespace std;
int print[200];
void partitn(int n,int k,int idx)
{
if(n==0)
{
for(int i=0;i<idx;i++)
cout<<print[i]<<" ";
cout<<endl;
return ;
}
for(int i=k;i>0;i--)
{
if(i>n)continue;
print[idx]=i;
partitn(n-i,i,idx+1);
}
}
int main()
{
int n;
cin>>n;
partitn(n,n,0);
return 0;
}
b)
#include<iostream>
using namespace std;
int print[200];
void partitn(int n,int k,int idx)
{
if(n==0)
{
for(int i=0;i<idx;i++)
cout<<print[i]<<" ";
cout<<endl;
return ;
}
for(int i=k;i>0;i--)
{
if(i>n)continue;
print[idx]=i;
partitn(n-i,i,idx+1);
}
}
int main()
{
int n;
cin>>n;
partitn(n,0,0);
return 0;
}
c)
#include<iostream>
using namespace std;
int print[200];
void partitn(int n,int k,int idx)
{
if(n==0)
{
for(int i=0;i<idx;i++)
cout<<print[i]<<" ";
cout<<endl;
return ;
}
for(int i=k;i>0;i--)
{
print[idx]=i;
partitn(n-i,i,idx+1);
}
}
int main()
{
int n;
cin>>n;
partitn(n,0,0);
return 0;
}
d)
#include<iostream>
using namespace std;
int print[200];
void partitn(int n,int k,int idx)
{
if(n==0)
{
for(int i=0;i<idx;i++)
cout<<print[i]<<" ";
cout<<endl;
return ;
}
for(int i=k;i>0;i--)
{
print[idx]=i;
partitn(n-i,i,idx+1);
}
}
int main()
{
int n;
cin>>n;
partitn(n,n,0);
return 0;
}
Answer: a
Explanation: In t
Answer: b
Explanation: Power set of a set is defined as the set of all subsets. Ex- S={1,2} then P={{},{1},{2}{1,2}}.
Answer: d
Explanation: Power set of a set is defined as the set of all subsets. Number of elements in the power set of a
set having n elements is given as 2n. Thus, here number of elements will be 23=8.
Answer: c
Explanation: For finding the number of elements in the power set of the given set we need to remove
duplicates. So we will be left with 6 unique elements which will be P={{},{1},{2},{1,2},{2,2},{1,2,2}}.
Answer: c
Explanation: As the value of 1 << i is 2i so the given function checks whether the ith bit of N is set or not. If
it is set then the function returns true.
5. What will be the output for the following code?
advertisement
#include <stdio.h>
#include <math.h>
void PowerSet(char *set, int set_size)
{
unsigned int pow_size = pow(2, set_size);
int count, j;
for(count = 0; count < pow_size; count++)
{
for(j = 0; j < set_size; j++)
{
if(count & (1<<j))
printf("%c", set[j]);
}
printf(",");
}
}
int main()
{
char strset[] = {'a','b','c'};
PowerSet(strset, 3);
return 0;
}
a) a,b,ab,c,ac,bc,abc,
b) a,b,ab,c,ac,bc,abc
c) ,a,b,ab,c,ac,bc,abc,
d) ,abc,bc,ac,c,ab,b,a,
Answer: c
Explanation: The given code prints the elements of power set of the given set strset[]. It uses binary counter
of appropriate length in order to print corresponding subsets of the given set.
#include <stdio.h>
#include <math.h>
void PowerSet(char *set, int set_size)
{
unsigned int pow_size = pow(2, set_size);
int count, j;
for(count = 0; count < pow_size; count++)
{
for(j = 0; j < set_size; j++)
{
if(count & (1<<j))
printf("%c", set[j]);
}
printf(",");
}
}
int main()
{
char strset[] = {'a','b','c'};
PowerSet(strset, 3);
return 0;
}
a) O(n 2n)
b) O(n2)
c) O(n log n)
d) O(2n) (n is the size of set)
Answer: a
Explanation: In the given code we have a nested for loop. In this loop the outer loop runs 2n times and the
inner loop runs n times. So the overall time complexity becomes n2n.
#include <stdio.h>
#include <math.h>
void PowerSet(char *set, int set_size)
{
unsigned int pow_size = pow(2, set_size);
int count, j;
for(count = 0; count < pow_size; count++)
{
for(j = 0; j < set_size; j++)
{
if(count & (1<<j))
printf("%c", set[j]);
}
printf(",");
}
}
int main()
{
char strset[] = {'a','b','c'};
PowerSet(strset, 3);
return 0;
}
a) O(n)
b) O(1)
c) O(n log n)
d) O(2n) (n is the size of set)
Answer: b
Explanation: The given code prints the elements of power set of the given set strset[]. As this code does not
require any extra space for generating the output so its auxiliary space requirement will be O(1).
8. Which of the following code prints the power set of a given set?
a)
#include<iostream>
using namespace std;
void Set(string str, int index = 0,
string curr = "")
{
int n = str.size();
if (index == n)
{
cout << curr << endl;
return;
}
Set(str, index , curr + str[index]);
Set(str, index + 1, curr);
}
int main()
{
string str = "ab";
Set(str);
return 0;
}
b)
#include<iostream>
using namespace std;
void Set(string str, int index = 0,
string curr = "")
{
int n = str.size();
if (index == n)
{
cout << curr << endl;
return;
}
Set(str, index + 1, curr + str[index]);
Set(str, index , curr);
}
int main()
{
string str = "ab";
Set(str);
return 0;
}
c)
#include<iostream>
using namespace std;
void Set(string str, int index = 0,
string curr = "")
{
int n = str.size();
if (index == n)
{
cout << curr << endl;
return;
}
Set(str, index + 1, curr + str[index]);
Set(str, index + 1, curr);
}
int main()
{
string str = "ab";
Set(str);
return 0;
}
d)
#include<iostream>
using namespace std;
void Set(string str, int index = 0,
string curr = "")
{
int n = str.size();
if (index == n) {
cout << curr << endl;
return;
}
Set(str, index , curr+str);
Set(str, index + 1, curr);
}
int main()
{
string str = "ab";
Set(str);
return 0;
}
Answer: c
Explanation: In the correct version we are taking two cases for each element. In the first case the element is
included in the subset and in the second case it is not included. So in this manner, we find all the subsets of
the given set.
9. The number of elements in the power set increases when there are duplicates present in the set.
a) True
b) False
Answer: b
Explanation: In case when duplicates are present in the set then the number of elements in the power set
decreases. It is because we remove subsets with identical elements.
10. What of the following code prints the power set of a given set?
a)
#include <bits/stdc++.h>
using namespace std;
void Set(string str, int ind = -1,
string curr = "")
{
int n = str.size();
if (ind == n)
return;
cout << curr << ",";
for (int i = ind+ 1; i < n; i++)
{
curr += str[i];
Set(str, i, curr);
curr.erase(curr.size() - 1);
}
return;
}
int main()
{
string str = "abc";
Set(str);
return 0;
}
b)
#include <bits/stdc++.h>
using namespace std;
void Set(string str, int ind = -1,
string curr = "")
{
int n = str.size();
if (ind == 0)
return;
cout << curr << ",";
for (int i = ind+ 1; i < n; i++)
{
curr += str[i];
Set(str, i, curr);
curr.erase(curr.size() - 1);
}
return;
}
int main()
{
string str = "abc";
Set(str);
return 0;
}
c)
#include <bits/stdc++.h>
using namespace std;
void Set(string str, int ind = -1,
string curr = "")
{
int n = str.size();
if (ind == n)
return;
cout << curr << ",";
for (int i = ind+ 1; i < n; i++)
{
curr += str[i];
Set(str, i, curr);
curr.erase(curr.size() -2);
}
return;
}
int main()
{
string str = "abc";
Set(str);
return 0;
}
d)
#include <bits/stdc++.h>
using namespace std;
void Set(string str, int ind = -1,
string curr = "")
{
int n = str.size();
if (ind == n)
return;
cout << str << ",";
for (int i = ind+ 1; i < n; i++)
{
curr += str[i];
Set(str, i, curr);
curr.erase(curr.size() - 1);
}
return;
}
int main()
{
string str = "abc";
Set(str);
return 0;
}
Answer: a
Explanation: In the correct version of the code we are fixing a prefix and generate all corresponding subsets.
Then
1. Which one of the following problem types does inclusion-exclusion principle belong to?
a) Numerical problems
b) Graph problems
c) String processing problems
d) Combinatorial problems
Answer: d
Explanation: Inclusion-Exclusion principle is a kind of combinatorial problem. It is a counting technique to
obtain the number of elements present in sets( two, three , etc.,).
2. Which of the following is a correct representation of inclusion exclusion principle (|A,B| represents
intersection of sets A,B)?
a) |A U B|=|A|+|B|-|A,B|
b) |A,B|=|A|+|B|-|A U B|
c) |A U B|=|A|+|B|+|A,B|
d) |A,B|=|A|+|B|+|A U B|
Answer: a
Explanation: The formula for computing the union of two sets according to inclusion-exclusion principle is |
A U B|=|A|+|B|-|A,B| where |A,B| represents the intersection of the sets A and B.
3. ____________ is one of the most useful principles of enumeration in combinationatorics and discrete
probability.
a) Inclusion-exclusion principle
b) Quick search algorithm
c) Euclid’s algorithm
d) Set theory
Answer: a
Explanation: Inclusion-exclusion principle serves as one of the most useful principles of enumeration in
combinationatorics and discrete probability because it provides simple formula for generalizing results.
Answer: d
Explanation: Counting intersections, Graph coloring and Matching of bipartite graphs are all examples of
inclusion-exclusion principle whereas maximum flow problem is solved using Ford-Fulkerson algorithm.
Answer: a
Explanation: The concept of inclusion- exclusion principle was initially invented by Abraham de Moivre in
1718 but it was published first by Daniel Silva in his paper in 1854.
advertisement
Answer: b
Explanation: According to inclusion-exclusion principle, a n-tuple wise intersection is included if n is odd
and excluded if n is even.
7. With reference to the given Venn diagram, what is the formula for computing |AUBUC| (where |x, y|
represents intersection of sets x and y)?
a) |A U B U C|=|A|+|B|+|C|-|A,B|-|A,C|-|B,C|+|A, B,C|
b) |A, B,C|=|A|+|B|+|C|-|A U B|-|A U C|-|B U C|+|A U B U C|
c) |A, B,C|=|A|+|B|+|C|+|A,B|-|A,C|+|B,C|+|A U B U C|
d) |A U B U C|=|A|+|B|+|C| + |A,B| + |A,C| + |B,C|+|A, B,C|
Answer: a
Explanation: The formula for computing the union of three sets using inclusion-exclusion principle is|A U B
U C|=|A|+|B|+|C|-|A,B|-|A,C|-|B,C|+|A, B,C| where |A,B|, |B,C|, |A,C|, |A,B,C| represents the intersection of
the sets A and B, B and C, A and C, A, B and C respectively.
8. Which of the following statement is incorrect with respect to generalizing the solution using the inclusion-
exclusion principle?
a) including cardinalities of sets
b) excluding cardinalities of pairwise intersections
c) excluding cardinalities of triple-wise intersections
d) excluding cardinalities of quadraple-wise intersections
Answer: c
Explanation: According to inclusion-exclusion principle, an intersection is included if the intersecting
elements are odd and excluded, if the intersecting elements are even. Hence triple-wise intersections should
be included.
9. Counting intersections can be done using the inclusion-exclusion principle only if it is combined with De
Morgan’s laws of complementing.
a) true
b) false
Answer: a
Explanation: The application of counting intersections can be fulfiled if and only if it is combined with De
Morgan laws to count the cardinality of intersection of sets.
10. Using the inclusion-exclusion principle, find the number of integers from a set of 1-100 that are not
divisible by 2, 3 and 5.
a) 22
b) 25
c) 26
d) 33
Answer: c
Explanation: Consider sample space S={1,…100}. Consider three subsets A, B, C that have elements that
are divisible by 2, 3, 5 respectively. Find integers that are divisible by A and B, B and C, A and C. Then find
the integers that are divisible by A, B, C. Applying the inclusion-exclusion principle, 100 − (50 + 33 + 20) +
(16 + 10 + 6) − 3 = 26.
11. ____________ is an arithmetic function that calculates the total number of positive integers less than or
equal to some number n, that are relatively prime to n.
a) Euler’s phi function
b) Euler’s omega function
c) Cauchy’s totient function
d) Legrange’s function
Answer: a
Explanation: Euler’s phi function is an arithmetic function that calculates the total number of positive
integers less than or equal to some number n, that are relatively prime to n. The inclusion-exclusion
principle is used to obtain a formula for Euler’s phi function.
12. Let A={1,2,3} B={2,3,4} C={1,3,5} D={2,3}. Find the cardinality of sum of all the sets.
a) 6
b) 5
c) 4
d) 7
Answer: b
Explanation: First, include the cardinalities of all the sets. Then, exclude the cardinalities of even
intersections. Then
2. What is the shortest distance between the line given by ax + by + c = 0 and the point (x1,y1)?
a)
b)
c)
d) ax1+by1+c
Answer: a
Explanation: The shortest distance between a line and a point is given by the formula (ax1+by1+c)/(√a2+b2).
This formula can be derived using the formula of area of a triangle.
3. What is the shortest distance between the line given by -2x + 3y + 4 = 0 and the point (5,6)?
a) 4.5 units
b) 5.4 units
c) 4.3 units
d) 3.3 units
Answer: d
Explanation: The shortest distance between a line and a point is given by the formula (ax1+by1+c)/(√a2+b2).
Using this formula we get the answer 3.3 units.
4. What is the general formula for finding the shortest distance between two parallel lines given by
ax+by+c1=0 and ax+by+c2=0?
a)
b)
c)
d) c1+c2
Answer: b
Explanation: The general formula for finding the shortest distance between two parallel lines given by
ax+by+c1 and ax+by+c2 is (c1-c2)/(√a2+b2). We can find this by considering the distance of any one point
on one of the line to the other line.
Answer: d
Explanation: As the given lines are parallel so the distance between them can be calculated by using the
formula (c1-c2)/(√a2+b2). So we get the distance as 0.4 unit.
advertisement
Answer: a
Explanation: The slope of a line given by the equation ax + by + c=0 has the slope of -a/b. So two lines
having the same ratio of the coefficient of x and y will be parallel to each other.
Answer: b
Explanation: The slope of a line given by the equation ax + by + c=0 has the slope of -a/b. So the slope of
the given line will be -2.
8. What will be the co-ordinates of foot of perpendicular line drawn from the point (-1,3) to the line 3x-4y-
16=0?
a) (1/5,2/5)
b) (2/25,5/25)
c) (68/25,-49/25)
d) (-49/25,68/25)
Answer: c
Explanation: The foot of perpendicular can be found by equating the distance between the two points and
the distance between point and line. This is found to be (68/25,-49/25).
9. Which of the following is used to find the absolute value of the argument in C++?
a) abs()
b) fabs()
c) mod()
d) ab()
Answer: b
Explanation: In C++ the absolute value of an argument can be found by using the function fabs(). It is
available under the header file math.h.
10. What will be the slope of the line perpendicular to the line 6x-3y-16=0?
a) 1/2
b) -1/2
c) 2
d) -2
Answer: b
Explanation: For two lines to be perpendicular the product of their slopes should be equal to -1. So as the
slope of given line is 2 so the slope of line perpendicular to it will be -1/2.
#include<math.h>
#include<iostream>
using namespace std;
void distance(float x, float y, float a, float b, float c)
{
float d = fabs((a * x + b * y + c)) / (sqrt(a * a + b * b));
cout<<d;
return;
}
int main()
{
float x = -2;
float y = -3;
float a = 5;
float b = -2;
float c = - 4;
distance(x, y, a, b, c);
return 0;
}
a) 2.8
b) 1.8
c) 1.4
d) 2.4
Answer: c
Explanation: The
Answer: a
Explanation: Closest pair problem arises in two most important areas- computational geometry and
operational research.
2. Which approach is based on computing the distance between each pair of distinct points and finding a pair
with the smallest distance?
a) Brute force
b) Exhaustive search
c) Divide and conquer
d) Branch and bound
Answer: a
Explanation: Brute force is a straight forward approach that solves closest pair problem using that algorithm.
3. What is the runtime efficiency of using brute force technique for the closest pair problem?
a) O(N)
b) O(N log N)
c) O(N2)
d) O(N3 log N)
Answer: c
Explanation: The efficiency of closest pair algorithm by brute force technique is mathematically found to be
O(N2).
4. The most important condition for which closest pair is calculated for the points (pi, pj) is?
a) i>j
b) i!=j
c) i=j
d) i<j
Answer: d
Explanation: To avoid computing the distance between the same pair of points twice, we consider only the
pair of points (pi, pj) for which i<j.
5. What is the basic operation of closest pair algorithm using brute force technique?
a) Euclidean distance
b) Radius
c) Area
d) Manhattan distance
Answer: a
Explanation: The basic operation of closest pair algorithm is Euclidean distance and its formula is given by
d=√(xi-xj)2+(yi-yj)2.
advertisement
Answer: b
Explanation: In older times, Euclidean distance metric is also called a Pythagoras metric which is the length
of the line segment connecting two points.
7. Which of the following strategies does the following diagram depict?
Answer: b
Explanation: Brute force is a straight forward approach to solve critical problems. Here, we use brute force
technique to find the closest distance between p1 and p2.
Answer: a
Explanation: Manhattan distance is an alternative way to calculate distance. It is the distance between two
points measured along axes at right angles.
9. What is the optimal time required for solving the closest pair problem using divide and conquer approach?
a) O(N)
b) O(log N)
c) O(N log N)
d) O(N2)
Answer: c
Explanation: The optimal time for solving using a divide and conquer approach is mathematically found to
be O(N log N).
10. In divide and conquer, the time is taken for merging the subproblems is?
a) O(N)
b) O(N log N)
c) O(N2)
d) O(log N)
Answer: b
Explanation: The time taken for merging the smaller subproblems in a divide and conquer approach is
mathematically found to be O(N log N).
11. The optimal time obtained through divide and conquer approach using merge sort is the best case
efficiency.
a) true
b) false
Answer: a
Explanation: The optimal time obtained through divide and conquer approach is the best class efficiency and
it is given by Ω(N log N).
12. Which of the following strategies does the following diagram depict?
a) Brute force
b) Divide and conquer
c) Exhaustive search
d) Branch and bound
Answer: b
Explanation: The above diagram depicts the implementation of divide and conquer. The problem is divided
into sub problems and are separated by a line.
a) p1 and p11
b) p3 and p8
c) p2 and p3
d) p9 and p10
Answer: c
Explanation: Fro
Answer: b
Explanation: Cross product is also known as a vector product. It is a mathematical operation that is
performed on 2 vectors in 3D plane.
3. What is the magnitude of resultant of cross product of two parallel vectors a and b?
a) |a|.|b|
b) |a|.|b| cos(180)
c) |a|.|b| sin(180)
d) 1
Answer: c
Explanation: The resultant of cross product of 2 parallel vectors is always 0 as the angle between them is 0
or 180 degrees. So the answer is |a|.|b| sin(180).
4. What is the general formula for finding the magnitude of the cross product of two vectors a and b with
angle θ between them?
a) |a|.|b|
b) |a|.|b| cos(θ)
c) |a|.|b| sin(θ)
d) |a|.|b| tan(θ)
Answer: c
Explanation: The general formula for finding the magnitude of cross product of two vectors is |a|.|b| sin(θ).
Its direction is perpendicular to the plane containing a and b.
Answer: a
Explanation: The concept of cross product find its application in the field of computer graphics. It can be
used to find the winding of polygon about a point.
advertisement
Answer: c
Explanation: Cross product of two vectors can be used to find the area of parallelogram. For this, we need to
consider the vectors as the adjacent sides of the parallelogram.
8. The resultant vector from the cross product of two vectors is _____________
a) perpendicular to any one of the two vectors involved in cross product
b) perpendicular to the plane containing both vectors
c) parallel to to any one of the two vectors involved in cross product
d) parallel to the plane containing both vectors
Answer: b
Explanation: The resultant vector from the cross product of two vectors is perpendicular to the plane
containing both vectors. In other words, it should be perpendicular to both the vectors involved in the cross
product.
Answer: c
Explanation: We can find the cross product of the given vectors by solving the determinant.
10. What will be the cross product of the vectors 2i + 3j + k and 6i + 9j + 3k?
a) i + 2j + k
b) i – j – 5k
c) 0
d) 2i – j – 5k
Answer: c
Explanation: The given vectors are parallel to each other. The cross product of parallel vectors is 0 because
sin(0) is 0.
#include <bits/stdc++.h>
using namespace std;
void crossP(int A[], int B[], int cross[])
{
cross[0] = A[1] * B[2] - A[2] * B[1];
cross[1] = A[0] * B[2] - A[2] * B[0];
cross[2] = A[0] * B[1] - A[1] * B[0];
}
int main()
{
int A[] = { 1, 2, 4 };
int B[] = { 2, 3, 2 };
int cross[3];
crossP(A, B, cross);
for (int i = 0; i < 3; i++)
cout << cross[i] << " ";
return 0;
}
a) 1 2 5
b) -1 -5 -3
c) -6 -8 -1
d) -8 -6 -1
Answer: d
Explanation: The given code calculates the cross product of the vectors stored in arrays A and B
respectively. So the output will be -8 -6 -1.
12. Which of the following operation will give a vector that is perpendicular to both vectors a and b?
a) a x b
b) a.b
c) b x a
d) both a x b and b x a
Answer: d
Explanation: The res
Answer: b
Explanation: Quick hull is a method of constructing a smallest convex polygon out of n given points in a
plane.
Answer: b
Explanation: Most commonly, two approaches are adopted to solve quick hull problem- brute force
approach and divide and conquer approach.
Answer: b
Explanation: The average case complexity of quickhull algorithm using divide and conquer approach is
mathematically found to be O(N log N).
Answer: c
Explanation: The worst case complexity of quickhull algorithm using divide and conquer approach is
mathematically found to be O(N2).
advertisement
a) closest pair
b) convex hull
c) concave hull
d) path compression
Answer: b
Explanation: The above diagram is a depiction of convex hull, also known as quick hull, since it encloses n
points into a convex polygon.
7. Which of the following statement is not related to quickhull algorithm?
a) finding points with minimum and maximum coordinates
b) dividing the subset of points by a line
c) eliminating points within a formed triangle
d) finding the shortest distance between two points
Answer: d
Explanation: Finding the shortest distance between two points belongs to closest pair algorithm while the
rest is quickhull.
8. The quick hull algorithm runs faster if the input uses non- extreme points.
a) true
b) false
Answer: a
Explanation: It is proved that the quick hull algorithm runs faster if the input uses non-extreme points and
also, if it uses less memory.
Answer: b
Explanation: Quick hull problem and closest pair algorithms are some of the examples of computational
problems.
Answer: d
Explanation: Quickhull algorithm is similar to a quick sort algorithm with respect to the run time average
case and worst case efficiencies.
Answer: a
Explanation: Eddy formulated quick hull algorithm. Graham invented graham scan. Andrew formulated
Andrew’s algorithm and Chan invented Chan’s algorithm.
12. The time is taken to find the ‘n’ points that lie in a convex quadrilateral is?
a) O(N)
b) O(N log N)
c) O(N2)
d) O(log N)
Answer: a
Explanatio
Answer: b
Explanation: Chan’s algorithm is an output-sensitive algorithm used to compute the convex hull set of n
points in a 2D or 3D space. Closest pair algorithm is used to compute the closest distance between two
points.
Answer: c
Explanation: The running time of Chan’s algorithm is calculated to be O(n log h) where h is the number of
vertices of the convex hull.
Answer: a
Explanation: Chan’s algorithm was formulated by Timothy Chan. Kirkpatrick and Seidel formulated the
Kirkpatrick-Seidel algorithm. Frank Nielsen developed a paradigm relating to Chan’s algorithm.
4. The running time of Chan’s algorithm is obtained from combining two algorithms.
a) True
b) False
Answer: a
Explanation: The O(n log h) running time of Chan’s algorithm is obtained by combining the running time of
Graham’s scan [O(n log n)] and Jarvis match [O(nh)].
5. Which of the following is called the “ultimate planar convex hull algorithm”?
a) Chan’s algorithm
b) Kirkpatrick-Seidel algorithm
c) Gift wrapping algorithm
d) Jarvis algorithm
Answer: b
Explanation: Kirkpatrick-Seidel algorithm is called as the ultimate planar convex hull algorithm. Its running
time is the same as that of Chan’s algorithm (i.e.) O(n log h).
Join Sanfoundry@YouTube
Answer: a
Explanation: Chan’s algorithm is very practical for moderate sized problems whereas Kirkpatrick-Seidel
algorithm is not. Although, they both have the same running time. Gift wrapping algorithm is a non-output
sensitive algorithm and has a longer running time.
Answer: b
Explanation: Hershberger’s algorithm is an output sensitive algorithm whose running time was originally
O(n log n). He used Chan’s algorithm to speed up to O(n log h) where h is the number of edges.
Answer: b
Explanation: Chan’s algorithm implies that the convex hulls of larger points can be arrived at by merging
previously calculated convex hulls. It makes the algorithm simpler instead of recomputing every time from
scratch.
9. Which of the following factors account more to the cost of Chan’s algorithm?
a) computing a single convex hull
b) locating points that constitute a hull
c) computing convex hull in groups
d) merging convex hulls
Answer: c
Explanation: The majority of the cost of the algorithm lies in the pre-processing (i.e.) computing convex hull
in groups. To reduce cost, we reuse convex hulls from previous iterations.
10. Chan’s algorithm can be used to compute the lower envelope of a trapezoid.
a) true
b) false
Answer: a
Explanation: An ex
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.
advertisement
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.
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
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.
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
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.
advertisement
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.
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 Brea
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.
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.
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. W
1. Branch and bound is a __________
a) problem solving technique
b) data structure
c) sorting algorithm
d) type of tree
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. This
leads 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.
advertisement
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.
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 ca
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
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?
a) Graph M has no minimum spanning tree
b) Graph M has a unique minimum spanning trees of cost 2
c) Graph M has 3 distinct minimum spanning trees, each of cost 2
d) Graph M has 3 spanning trees of different costs
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.
advertisement
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
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
Answer: a
Explanation: A subgraph is a graph formed from a subset of the vertices and edges of the original graph.
And the subset of vertices includes all endpoints of the subset of the edges. So, we can say MST of a graph
is a subgraph when all weights in the original graph are positive.
8. Consider the graph shown below. Which of the following are the edges in the MST of the given graph?
a) (a-c)(c-d)(d-b)(d-b)
b) (c-a)(a-d)(d-b)(d-e)
c) (a-d)(d-c)(d-b)(d-e)
d) (c-a)(a-d)(d-c)(d-b)(d-e)
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
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 propert
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
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
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)
Answer: a
Explanation: Using Krushkal’s algorithm on the given graph, the generated minimum spanning tree is
shown below.
So, the edges in the MST are, (B-E)(G-E)(E-F)(D-F).
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.
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
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: 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).
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
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)
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.
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.
advertisement
6. Kruskal’s algorithm is best suited for the sparse graphs than the prim’s algorithm.
a) True
b) False
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)
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
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: Pr
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
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)
advertisement
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; }
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
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
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)
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
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
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.
Answer: b
Explanation: In the normal execution of Dijkstra’s Algorithm, the while loop gets executed V times. The
change in the while loop statement causes it to execute only V – 1 times.
13. Consider the following graph.
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
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.
Answer: a
Explanation: The Bellmann Ford algorithm returns Boolean value whether there is a negative weight cycle
that is reachable from the source.
Answer: d
Explanation: Bellmann ford algorithm is used for finding solutions for single source shortest path problems.
If the graph has no negative cycles that are reachable from the source then the algorithm produces the
shortest paths and their weights.
3. Bellmann Ford algorithm is used to indicate whether the graph has negative weight cycles or not.
a) True
b) False
Answer: a
Explanation: Bellmann Ford algorithm returns true if the graph does not have any negative weight cycles
and returns false when the graph has negative weight cycles.
4. How many solution/solutions are available for a graph having negative weight cycle?
a) One solution
b) Two solutions
c) No solution
d) Infinite solutions
Answer: c
Explanation: If the graph has any negative weight cycle then the algorithm indicates that no solution exists
for that graph.
Answer: d
Explanation: Bellmann Ford algorithm runs in time O(VE), since the initialization takes O(V) for each of V-
1 passes and the for loop in the algorithm takes O(E) time. Hence the total time taken by the algorithm is
O(VE).
advertisement
6. How many times the for loop in the Bellmann Ford Algorithm gets executed?
a) V times
b) V-1
c) E
d) E-1
Answer: b
Explanation: The for loop in the Bellmann Ford Algorithm gets executed for V-1 times. After making V-1
passes, the algorithm checks for a negative weight cycle and returns appropriate boolean value.
Answer: a
Explanation: The running time of Bellmann Ford Algorithm is O(VE) whereas Dijikstra’s Algorithm has
running time of only O(V2).
b)
c)
d)
for i=1 to V[g]-1
do for each edge (u,v) in E[g]
do Relax(u,v,w)
return True
Answer: a
Explanation: After initialization, the algorithm makes v-1 passes over the edges of the graph. Each pass is
one iteration of the for loop and consists of relaxing each edge of the graph once. Then it checks for the
negative weight cycle and returns an appropriate Boolean value.
Answer: d
Explanation: Relaxation methods which are also called as iterative methods in which an approximation to
the correct distance is replaced progressively by more accurate values till an optimum solution is found.
Answer: c
Explanation: Bellmann Ford Algorithm can be applied for all directed and weighted graphs. The weight
function in the graph may either be positive or negative.
Answer: b
Explanation: Alfonso Shimbe proposed Bellmann Ford algorithm in the year 1955. Later it was published by
Richard Bellmann in 1957 and Lester Ford Jr in the year 1956. Hence it is called Bellmann Ford Algorithm.
12. Consider the following graph. What is the minimum cost to travel from node A to node C?
a) 5
b) 2
c) 1
d) 3
Answer: b
Explanation: The minimum cost to travel from node A to node C is 2.
A-D, cost=1
D-B, cost=-2
B-C, cost=3
Hence the total cost is 2.
13. In the given graph, identify the path that has minimum cost to travel from node a to node f.
a) a-b-c-f
b) a-d-e-f
c) a-d-b-c-f
d) a-d-b-c-e-f
Answer: d
Explanation: The minimum cost taken by the path a-d-b-c-e-f is 4.
a-d, cost=2
d-b, cost=-2
b-c, cost=1
c-e, cost= 2
e-f, cost=1
Hence the total cost is 4.
Answer: a
Explanation: In Bellmann Ford Algorithm the shortest paths are calculated in bottom up manner which is
similar to other dynamic programming problems.
Answer: c
Explanation: When the total weight of the graph sums up to a negative number then the graph is said to have
a negati
Answer: a
Explanation: Floyd Warshall’s Algorithm is used for solving all pair shortest path problems. It means the
algorithm is used for finding the shortest paths between all pairs of vertices in a graph.
Answer: c
Explanation: Floyd Warshall Algorithm can be applied in directed graphs. From a given directed graph, an
adjacency matrix is framed and then all pair shortest path is computed by the Floyd Warshall Algorithm.
Answer: b
Explanation: Floyd Warshall Algorithm follows dynamic programming approach because the all pair
shortest paths are computed in bottom up manner.
Answer: d
Explanation: One of the ways to compute the transitive closure of a graph in Theta(N3) time is to assign a
weight of 1 to each edge of E and then run the Floyd Warshall Algorithm.
advertisement
Answer: b
Explanation: Bottom up procedure is being used to compute the values of the matrix elements dij(k). The
input is an n x n matrix. The procedure returns the matrix D(n) of the shortest path weights.
Answer: a
Explanation: Floyd- Warshall Algorithm was proposed by Robert Floyd in the year 1962. The same
algorithm was proposed by Stephen Warshall during the same year for finding the transitive closure of the
graph.
8. Who proposed the modern formulation of Floyd-Warshall Algorithm as three nested loops?
a) Robert Floyd
b) Stephen Warshall
c) Bernard Roy
d) Peter Ingerman
Answer: d
Explanation: The modern formulation of Floyd-Warshall Algorithm as three nested for-loops was proposed
by Peter Ingerman in the year 1962.
n=rows[W]
D(0)=W
for k=1 to n
do for i=1 to n
do for j=1 to n
do ________________________________
return D(n)
Answer: c
Explanation: In order to compute the shortest path from vertex i to vertex j, we need to find the minimum of
2 values which are dij(k-1) and sum of dik(k-1) and dkj(k-1).
10. What happens when the value of k is 0 in the Floyd Warshall Algorithm?
a) 1 intermediate vertex
b) 0 intermediate vertex
c) N intermediate vertices
d) N-1 intermediate vertices
Answer: b
Explanation: When k=0, a path from vertex i to vertex j has no intermediate vertices at all. Such a path has
at most one edge and hence dij(0) = wij.
11. Using logical operator’s instead arithmetic operators saves time and space.
a) True
b) False
Answer: a
Explanation: In computers, logical operations on single bit values execute faster than arithmetic operations
on integer words of data.
12. The time taken to compute the transitive closure of a graph is Theta(n2).
a) True
b) False
Answer: b
Explanation: The time taken to compute the transitive closure of a graph is Theta(n3). Transitive closure can
be computed by assigning weight of 1 to each edge and by running Floyd Warshall Algorithm.
13. In the given graph, what is the minimum cost to travel from vertex 1 to vertex 3?
a) 3
b) 2
c) 10
d) -3
Answer: d
Explanation: The minimum cost required to travel from node 1 to node 5 is -3.
1-5, cost is -4
5-4, cost is 6
4-3, cost is -5
Hence total cost is -4 + 6 + -5 = -3.
14. In the given graph, how many intermediate vertices are required to travel from node a to node e at a
minimum cost?
a) 2
b) 0
c) 1
d) 3
Answer: c
Explanation: The minimum cost to travel from node a to node e is 1 by passing via nodes b and c.
a-b, cost 5
b-c, cost 3
c-e, cost -7
Hence the total cost is 1.
Answer: b
Explanation: Transitive closure of a graph can be computed by using Floyd Warshall algorithm. This
method involves substit
Answer: a
Explanation: The maximum flow problem involves finding a feasible flow between a source and a sink in a
network that is maximum and not minimum.
Answer: b
Explanation: A network can have only one source and one sink inorder to find the feasible flow in a
weighted connected graph.
Answer: a
Explanation: Vertex with no incoming edges is called as a source. Vertex with no leaving edges is called as
a sink.
Answer: d
Explanation: Ford-fulkerson algorithm is used to compute the maximum feasible flow between a source and
a sink in a network.
Answer: b
Explanation: Ford-Fulkerson algorithm uses the idea of residual graphs which is an extension of naïve
greedy approach allowing undo operations.
advertisement
Answer: a
Explanation: The first step in the naïve greedy algorithm is to start with the zero flow followed by adding
edges with higher values.
7. Under what condition can a vertex combine and distribute flow in any manner?
a) It may violate edge capacities
b) It should maintain flow conservation
c) The vertex should be a source vertex
d) The vertex should be a sink vertex
Answer: b
Explanation: A vertex can combine and distribute flow in any manner but it should not violate edge
capacities and it should maintain flow conservation.
a) 22
b) 17
c) 15
d) 20
Answer: c
Explanation: Initially, zero flow is computed. Then, computing flow= 7+1+5+2=15. Hence, maximum
flow=15.
9. A simple acyclic path between source and sink which pass through only positive weighted edges is
called?
a) augmenting path
b) critical path
c) residual path
d) maximum path
Answer: a
Explanation: Augmenting path between source and sink is a simple path without cycles. Path consisting of
zero slack edges is called critical path.
Answer: b
Explanation: An augmenting path can be found in O(|E|) mathematically by an unweighted shortest path
algorithm.
Answer: a
Explanation: Dinic’s algorithm includes construction of level graphs and resLidual graphs and finding of
augmenting paths along with blocking flow and is faster than the Ford-Fulkerson algorithm.
12. What is the running time of an unweighted shortest path algorithm whose augmenting path is the path
with the least number of edges?
a) O(|E|)
b) O(|E||V|)
c) O(|E|2|V|)
d) O(|E| log |V|)
Answer: c
Explanation: Each augmenting step takes O(|E|) using an unweighted shortest path algorithm yielding a O(|
E|2|V|) bound on the running time.
Answer: b
Explanation: The first ever people to formulate Maximum flow problem were T.E. Harris and F.S. Ross.
Lester R. Ford and Delbert R. Fulkerson formulated Ford- Fulkerson algorithm.
Answer: a
Explanation: The running time of Dinic’s blocking flow algorithm is O(V2E). The running of Ford-
Fulkerson algorithm is O(E max |f|).
Answer: c
Explanation: A flow is a mapping which follows two constraints- conservation of flows and capacity
constraints.
Answer: b
Explanation: Stable marriage problem is an example for recursive algorithm because it recursively uses
backtracking algorithm to find an optimal solution.
Answer: a
Explanation: Stable marriage problem uses Gale-Shapley algorithm. Maximum flow problem uses Ford-
Fulkerson algorithm. Prim’s algorithm involves minimum spanning tree.
Answer: a
Explanation: An optimal solution satisfying men’s preferences are said to be man optimal. An optimal
solution satisfying woman’s preferences are said to be woman optimal.
4. When a free man proposes to an available woman, which of the following happens?
a) She will think and decide
b) She will reject
c) She will replace her current mate
d) She will accept
Answer: d
Explanation: When a man proposes to an available woman, she will accept his proposal irrespective of his
position on his preference list.
5. If there are n couples who would prefer each other to their actual marriage partners, then the assignment is
said to be unstable.
a) True
b) False
Answer: a
Explanation: If there are n couples such that a man and a woman are not married, and if they prefer each
other to their actual partners, the assignment is unstable.
advertisement
Answer: b
Explanation: Two 2*2 matrices are used. One for men representing corresponding woman and ranking and
the other for women.
Answer: c
Explanation: If the preference of the man is greater, she replaces her current mate with him, leaving her
current mate free.
Answer: b
Explanation: Possibilities- There might be a woman pw, preferred to w by m, who herself prefers m to be
her husband and the same applies to man as well.
9. Consider the following ranking matrix. Assume that M1 and W2 are married. Now, M2 approaches W2.
Which of the following happens?
a) W2 replaces M1 with M2
b) W2 rejects M2
c) W2 accepts both M1 and M2
d) W2 rejects both M1 and M2
Answer: a
Explanation: W2 is married to M1. But the preference of W2 has M2 before M1. Hence, W2 replaces M1
with M2.
10. Consider the following ranking matrix. Assume that M1 and W1 are married and M2 and W3 are
married. Now, whom will M3 approach first?
a) W1
b) W2
c) W3
d) All three
Answer: c
Explanation: M3 will approach W3 first. Since W3 is married and since her preference list has her current
mate before M3, she rejects his proposal.
11. Who formulated a straight forward backtracking scheme for stable marriage problem?
a) McVitie and Wilson
b) Gale
c) Ford and Fulkerson
d) Dinitz
Answer: a
Explanation: McVitie and Wilson formulated a much faster straight forward backtracking scheme for stable
marriage problem. Ford and Fulkerson formulated Maximum flow problem.
12. Can stable marriage cannot be solved using branch and bound algorithm.
a) True
b) False
Answer: b
Explanation: Stable marriage problem can be solved using branch and bound approach because branch and
bound follows backtracking scheme with a limitation factor.
Answer: c
Explanation: The prime task of stable marriage problem is to determine stability of marriage (i.e) finding a
man and a woman who prefer each other to others.
Answer: a
Explanation: Choice of school by students is the most related example in the given set of options since both
school and students will have a preference list.
15. What is the efficiency of Gale-Shapley algorithm used in stable marriage problem?
a) O(N)
b) O(N log N)
c) O(N2)
d) O(log N)
Answer: c
Explanation: The time efficiency of Gale-Shapley algorithm is mathematically found to be O(N2) where N
denotes
Answer: a
Explanation: Maximum bipartite matching matches two elements with a property that no two edges share a
vertex.
Answer: a
Explanation: Maximum matching is also called as maximum cardinality matching (i.e.) matching with the
largest number of edges.
Answer: b
Explanation: A bipartite graph is said to be two-colourable so that every edge has its vertices coloured in
different colours.
Answer: c
Explanation: It is not difficult to prove that a graph is bipartite if and only if it does not have a cycle of an
odd length.
Answer: a
Explanation: A matching that matches all the vertices of a graph is called perfect matching.
advertisement
Answer: b
Explanation: The length of an augmenting path in a bipartite graph is always said to be always odd.
7. In a bipartite graph G=(V,U,E), the matching of a free vertex in V to a free vertex in U is called?
a) Bipartite matching
b) Cardinality matching
c) Augmenting
d) Weight matching
Answer: c
Explanation: A simple path from a free vertex in V to a free vertex in U whose edges alternate between
edges not in M and edges in M is called a augmenting path.
8. A matching M is maximal if and only if there exists no augmenting path with respect to M.
a) True
b) False
Answer: a
Explanation: According to the theorem discovered by the French mathematician Claude Berge, it means that
the current matching is maximal if there is no augmenting path.
Answer: b
Explanation: Pairing boys and girls for a dance is a traditional example for matching. Proposal of marriage is
an application of stable marriage problem.
10. Which is the correct technique for finding a maximum matching in a graph?
a) DFS traversal
b) BFS traversal
c) Shortest path traversal
d) Heap order traversal
Answer: b
Explanation: The correct technique for finding a maximum matching in a bipartite graph is by using a
Breadth First Search(BFS).
11. The problem of maximizing the sum of weights on edges connecting matched pairs of vertices is?
a) Maximum- mass matching
b) Maximum bipartite matching
c) Maximum weight matching
d) Maximum node matching
Answer: c
Explanation: The problem is called as maximum weight matching which is similar to a bipartite matching. It
is also called as assignment problem.
12. What is the total number of iterations used in a maximum- matching algorithm?
a) [n/2]
b) [n/3]
c) [n/2]+n
d) [n/2]+1
Answer: d
Explanation: The total number of iterations cannot exceed [n/2]+1 where n=|V|+|U| denoting the number of
vertices in the graph.
Answer: c
Explanation: The efficiency of algorithm designed by Hopcroft and Karp is mathematically found to be
O(√n(n+m)).
14. Who was the first person to solve the maximum matching problem?
a) Jack Edmonds
b) Hopcroft
c) Karp
d) Claude Berge
Answer: a
Explanation: Jack Edmonds was the first person to solve the maximum matching problem in 1965.
15. From the given graph, how many vertices can be matched using maximum matching in bipartite graph
algorithm?
a) 5
b) 4
c) 3
d) 2
Answer: a
Explanation: One
Answer: c
Explanation: Minimum cut algorithm is solved using Stoer-Wagner algorithm. Maximum flow problem is
solved using Ford-Fulkerson algorithm. Stable marriage problem is solved using Gale-Shapley algorithm.
2. ___________ is a partition of the vertices of a graph in two disjoint subsets that are joined by atleast one
edge.
a) Minimum cut
b) Maximum flow
c) Maximum cut
d) Graph cut
Answer: a
Explanation: Minimum cut is a partition of the vertices in a graph 4. in two disjoint subsets joined by one
edge. It is a cut that is minimal in some sense.
3. Minimum cut algorithm comes along with the maximum flow problem.
a) true
b) false
Answer: a
Explanation: Minimum cut algorithm is considered to be an extension of the maximum flow problem.
Minimum cut is finding a cut that is minimal.
Answer: a
Explanation: The given figure is a depiction of min cut problem since the graph is partitioned to find the
minimum cut.
Answer: c
Explanation: A cut separates a particular pair of vertices in a weighted undirected graph and has minimum
possible weight.
advertisement
6. What is the minimum number of cuts that a graph with ‘n’ vertices can have?
a) n+1
b) n(n-1)
c) n(n+1)/2
d) n(n-1)/2
Answer: c
Explanation: The mathematical formula for a graph with ‘n’ vertices can at the most have n(n-1)/2 distinct
vertices.
7. What is the running time of Karger’s algorithm to find the minimum cut in a graph?
a) O(E)
b) O(|V|2)
c) O(V)
d) O(|E|)
Answer: b
Explanation: The running time of Karger’s algorithm to find the minimum cut is mathematically found to be
O(|V|2).
Answer: b
Explanation: Graph partition is a problem in which the graph is partitioned into two or more parts with
additional conditions.
9. The weight of the cut is not equal to the maximum flow in a network.
a) true
b) false
Answer: b
Explanation: According to max-flow min-cut theorem, the weight of the cut is equal to the maximum flow
that is sent from source to sink.
10. __________ is a data structure used to collect a system of cuts for solving min-cut problem.
a) Gomory-Hu tree
b) Gomory-Hu graph
c) Dancing tree
d) AA tree
Answer: a
Explanation: Gomory-Hu tree is a weighted tree that contains the minimum cuts for all pairs in a graph. It is
constructed in |V|-1 max-flow computations.
11. In how many ways can a Gomory-Hu tree be implemented?
a) 1
b) 2
c) 3
d) 4
Answer: b
Explanation: Gomory-Hu tree can be implemented in two ways- sequential and parallel.
12. The running time of implementing naïve solution to min-cut problem is?
a) O(N)
b) O(N log N)
c) O(log N)
d) O(N2)
Answer: d
Explanation: The running time of min-cut algorithm using naïve implementation is mathematically found to
be O(N2).
13. What is the running time of implementing a min-cut algorithm using bidirected edges in a graph?
a) O(N)
b) O(N log N)
c) O(N4)
d) O(N2)
Answer: c
Explanation: The running time of a min-cut algorithm using Ford-Fulkerson method of making edges
birected in a graph is mathematically found to be O(N4).
14. Which one of the following is not an application of max-flow min-cut algorithm?
a) network reliability
b) closest pair
c) network connectivity
d) bipartite matching
Answer: b
Explanation: Network reliability, connectivity and bipartite matching are all applications of min-cut
algorithm whereas closest pair is a different kind of problem.
Answer: a
Explanation: The minimum cut of the given graph network is found to be ({1,3},{4,3},{4,5}) and its
capacity is 23.
Answer: b
Explanation: According to the graph theory a graph is the collection of dots and lines. A bar graph is not a
type of graph in computer science.
Answer: a
Explanation: The condition for vertex coloring of a graph is that two vertices which share a common edge
should not have the same color. If it uses k colors in the process then it is called k coloring of graph.
Answer: c
Explanation: In order to have a fully connected tree it must have N-1 edges. So the correct answer will be N-
1.
4. Minimum number of unique colors required for vertex coloring of a graph is called?
a) vertex matching
b) chromatic index
c) chromatic number
d) color number
Answer: c
Explanation: The minimum number of colors required for proper vertex coloring of graph is called
chromatic number whereas the minimum number of colors required for proper edge coloring of graph is
called chromatic index of a graph.
5. How many unique colors will be required for proper vertex coloring of an empty graph having n vertices?
a) 0
b) 1
c) 2
d) n
Answer: b
Explanation: An empty graph is a graph without any edges. So the number of unique colors required for
proper coloring of the graph will be 1.
advertisement
6. How many unique colors will be required for proper vertex coloring of a bipartite graph having n
vertices?
a) 0
b) 1
c) 2
d) n
Answer: c
Explanation: A bipartite graph is a graph such that no two vertices of the same set are adjacent to each other.
So the number of unique colors required for proper coloring of the graph will be 2.
Answer: c
Explanation: Calculating the chromatic number of a graph is an NP complete problem as a chromatic
number of an arbitrary graph cannot be determined by using any convenient method.
8. How many unique colors will be required for proper vertex coloring of a line graph having n vertices?
a) 0
b) 1
c) 2
d) n
Answer: d
Explanation: A line graph of a simple graph is obtained by connecting two vertices with an edge. So the
number of unique colors required for proper coloring of the graph will be n.
9. How many unique colors will be required for proper vertex coloring of a complete graph having n
vertices?
a) 0
b) 1
c) n
d) n!
Answer: c
Explanation: A complete graph is the one in which each vertex is directly connected with all other vertices
with an edge. So the number of unique colors required for proper coloring of the graph will be n.
10. Minimum number of colors required for proper edge coloring of a graph is called?
a) Chromatic color
b) Chromatic index
c) Edge matching
d) Color number
Answer: b
Explanation: The minimum number of colors required for proper edge coloring of graph is called chromatic
index. It is also known as edge chromatic number.
a) 1
b) 2
c) 3
d) 4
Answer: b
Explanation: The given graph will only require 2 unique colors so that no two vertices connected by a
common edge will have the same color. All nodes will have the same color except the central node.
12. How many unique colors will be required for vertex coloring of the following graph?
a) 2
b) 3
c) 4
d) 5
Answer: c
Explanation: The given graph will require 4 unique colors so that no two vertices connected by a common
edge will have the same color. So its chromatic number will be 4.
13. How many unique colors will be required for vertex coloring of the following graph?
a) 2
b) 3
c) 4
d) 5
Answer: b
Explanation: The given graph will require 3 unique colors because two diagonal vertex are connected to
each other directly. So its chromatic number will be 3.
14. Vertex coloring and chromatic number are one and the same.
a) True
b) False
Answer: b
Explanation: Vertex colo
Answer: b
Explanation: According to the graph theory a graph is the collection of dots and lines. Vertices are also
called dots and lines are also called edges.
Answer: a
Explanation: The condition for proper coloring of graph is that two vertices which share a common edge
should not have the same color. If it uses k colors in the process then it is called k coloring of graph.
Answer: a
Explanation: A proper graph ensures that two vertices which share a common edge should not have the same
color. If it uses k colors in the process then it is called k coloring of graph.
Answer: c
Explanation: The minimum number of colors required for proper vertex coloring of graph is called
chromatic number whereas the minimum number of colors required for proper edge coloring of graph is
called chromatic index of a graph.
5. What will be the chromatic number for an empty graph having n vertices?
a) 0
b) 1
c) 2
d) n
Answer: b
Explanation: An empty graph is a graph without any edges. So the chromatic number for such a graph will
be 1.
advertisement
6. What will be the chromatic number for an bipartite graph having n vertices?
a) 0
b) 1
c) 2
d) n
Answer: c
Explanation: A bipartite graph is graph such that no two vertices of the same set are adjacent to each other.
So the chromatic number for such a graph will be 2.
Answer: c
Explanation: Chromatic number of an arbitrary graph cannot be determined by using any convenient
method. So calculating the chromatic number of a graph is an NP complete problem.
8. What will be the chromatic number for a line graph having n vertices?
a) 0
b) 1
c) 2
d) n
Answer: d
Explanation: A line graph of a simple graph is obtained by connecting two vertices with an edge. A line
graph has a chromatic number of n.
9. What will be the chromatic number for a complete graph having n vertices?
a) 0
b) 1
c) n
d) n!
Answer: c
Explanation: A complete graph is the one in which each vertex is directly connected with all other vertices
with an edge. So in such a case each vertex should have a unique color. Thus the chromatic number will be
n.
10. What will be the chromatic number for a tree having more than 1 vertex?
a) 0
b) 1
c) 2
d) Varies with the structure and number of vertices of the tree
Answer: c
Explanation: The minimum number of colors required for proper vertex coloring of graph is called
chromatic number. So every tree having more than 1 vertex is 2 chromatic.
Answer: b
Explanation: Any graph that has a chromatic number less than or equal to k is called k colorable. Whereas a
graph with chromatic number k is called k chromatic.
a) 1
b) 2
c) 3
d) 4
Answer: b
Explanation: The given graph will only require 2 unique colors so that no two vertices connected by a
common edge will have the same color. So its chromatic number will be 2.
a) 2
b) 3
c) 4
d) 5
Answer: b
Explanation: The given graph will require 3 unique colors so that no two vertices connected by a common
edge will have the same color. So its chromatic number will be 3.
a) 2
b) 3
c) 4
d) 5
Answer: b
Explanation: The given graph will require 3 unique colors so that no two vertices connected by a common
edge will have the same color. So its chromatic number will be 3.
15. The chromatic number of star graph with 3 vertices is greater than that of a complete graph with 3
vertices.
a) True
b) False
Answer: b
Explanation: The chromatic number of a star graph is always 2 (for more than 1 vertex) whereas the
chromatic number of complete graph with 3 vertices will be 3. So chromatic number of complete graph will
be greater.
16. The chromatic number of star graph with 3 vertices is greater than that of a tree with same number of
vertices.
a) True
b) False
Answer: b
Explanation: Th
Answer: c
Explanation: According to the graph theory a graph is the collection of dots and lines. Vertices are also
called dots and lines are also called edges.
2. What is the condition for proper edge coloring of a graph?
a) Two vertices having a common edge should not have same color
b) Two vertices having a common edge should always have same color
c) No two incident edges should have the same color
d) No two incident edges should have different color
Answer: c
Explanation: The condition for proper edge coloring of graph is that no two incident edges should have the
same color. If it uses k colors in the process then it is called k edge coloring of graph.
Answer: a
Explanation: A proper edge coloring graph ensures that no two incident edges has the same color. If it uses k
colors in the process then it is called k coloring of graph.
Answer: d
Explanation: The minimum number of colors required for proper edge coloring of graph is called chromatic
index whereas the minimum number of colors required for proper vertex coloring of graph is called
chromatic number of a graph.
5. What will be the chromatic index for an empty graph having n vertices?
a) 0
b) 1
c) 2
d) n
Answer: a
Explanation: An empty graph is a graph without any edges. So the chromatic index for such a graph will be
0.
advertisement
6. If chromatic number of a line graph is 4 then the chromatic index of the graph will be?
a) 0
b) 1
c) 4
d) information insufficient
Answer: c
Explanation: The chromatic index of a graph is always equal to the chromatic number of its line graph. So
the chromatic index of the graph will be 4.
7. Calculating the chromatic index of a graph is a ______________
a) P problem
b) NP hard problem
c) NP complete problem
d) Cannot be identified as any of the given problem types
Answer: c
Explanation: Chromatic index of an arbitrary graph cannot be determined by using any convenient method.
So calculating the chromatic index of a graph is an NP complete problem.
8. Chromatic number of line graph is always equal to the chromatic index of the graph.
a) True
b) False
Answer: a
Explanation: The chromatic index of a graph is always equal to the chromatic number of its line graph. So
we can calculate the chromatic index of a graph by calculating the chromatic number of its line graph.
Answer: a
Explanation: A bipartite graph has an edge chromatic number equal to Δ. So bipartite graphs belongs to
class 1 graphs.
a) 1
b) 2
c) 3
d) 4
Answer: b
Explanation: The given graph will require 2 unique colors so that no two incident edges have the same color.
So its chromatic index will be 2.
a) 2
b) 3
c) 4
d) 5
Answer: b
Explanation: The given graph will require 3 unique colors so that no two incident edges have the same color.
So its chromatic index will be 3.
a) 0
b) 1
c) 2
d) 3
Answer: c
Explanation: The given graph will require 2 unique colors so that no two incident edges have the same color.
So its chromatic index will be 2.
13. What will be the chromatic index for a complete graph having n vertices (consider n to be an odd
number)?
a) n
b) n + 1
c) n – 1
d) 2n + 1
Answer: a
Explanation: A complete graph is the one in which each vertex is directly connected with all other vertices
with an edge. The chromatic index for an odd number of vertices will be n.
14. What will be the chromatic index for a complete graph having n vertices (consider n to be an even
number)?
a) n
b) n + 1
c) n – 1
d) 2n + 1
Answer: c
Explanation: A complete graph is the one in which each vertex is directly connected with all other vertices
with an ed
1. Given G is a bipartite graph and the bipartitions of this graphs are U and V respectively. What is the
relation between them?
a) Number of vertices in U = Number of vertices in V
b) Sum of degrees of vertices in U = Sum of degrees of vertices in V
c) Number of vertices in U > Number of vertices in V
d) Nothing can be said
Answer: b
Explanation: We can prove this by induction. By adding one edge, the degree of vertices in U is equal to 1
as well as in V. Let us assume that this is true for n-1 edges and add one more edge. Since the given edge
adds exactly once to both U and V we can tell that this statement is true for all n vertices.
2. A k-regular bipartite graph is the one in which degree of each vertices is k for all the vertices in the graph.
Given that the bipartitions of this graph are U and V respectively. What is the relation between them?
a) Number of vertices in U=Number of vertices in V
b) Number of vertices in U not equal to number of vertices in V
c) Number of vertices in U always greater than the number of vertices in V
d) Nothing can be said
Answer: a
Explanation: We know that in a bipartite graph sum of degrees of vertices in U=sum of degrees of vertices
in V. Given that the graph is a k-regular bipartite graph, we have k*(number of vertices in U)=k*(number of
vertices in V).
3. There are four students in a class namely A, B, C and D. A tells that a triangle is a bipartite graph. B tells
pentagon is a bipartite graph. C tells square is a bipartite graph. D tells heptagon is a bipartite graph. Who
among the following is correct?
a) A
b) B
c) C
d) D
Answer: c
Explanation: We can prove it in this following way. Let ‘1’ be a vertex in bipartite set X and let ‘2’ be a
vertex in the bipartite set Y. Therefore the bipartite set X contains all odd numbers and the bipartite set Y
contains all even numbers. Now let us consider a graph of odd cycle (a triangle). There exists an edge from
‘1’ to ‘2’, ‘2’ to ‘3’ and ‘3’ to ‘1’. The latter case (‘3’ to ‘1’) makes an edge to exist in a bipartite set X itself.
Therefore telling us that graphs with odd cycles are not bipartite.
4. A complete bipartite graph is a one in which each vertex in set X has an edge with set Y. Let n be the total
number of vertices. For maximum number of edges, the total number of vertices hat should be present on set
X is?
a) n
b) n/2
c) n/4
d) data insufficient
Answer: b
Explanation: We can prove this by calculus. Let x be the total number of vertices on set X. Therefore set Y
will have n-x. We have to maximize x*(n-x). This is true when x=n/2.
Answer: a
Explanation: Condition needed is that there should not be an odd cycle. But in a tree there are no cycles at
all. Hence it is bipartite.
7. A graph has 20 vertices. The maximum number of edges it can have is? (Given it is bipartite)
a) 100
b) 140
c) 80
d) 20
Answer: a
Explanation: Let the given bipartition X have x vertices, then Y will have 20-x vertices. We need to
maximize x*(20-x). This will be maxed when x=10.
8. Given that a graph contains no odd cycle. Is it enough to tell that it is bipartite?
a) Yes
b) No
Answer: a
Explanation: It is required that the graph is connected also. If it is not then it cannot be called a bipartite
graph.
Answer: a
Explanation: If a graph is such that there exists a path which visits every edge atleast once, then it is said to
be Eulerian. Taking an example of a square, the given question evaluates to yes.
10. A graph is found to be 2 colorable. What can be said about that graph?
a) The given graph is eulerian
b) The given graph is bipartite
c) The given graph is hamiltonian
d) The given graph is planar
Answer: b
Explanation: A gra
1. Which type of graph has no odd cycle in it?
a) Bipartite
b) Histogram
c) Cartesian
d) Pie
Answer: a
Explanation: The graph is known as Bipartite if the graph does not contain any odd length cycle in it. Odd
length cycle means a cycle with the odd number of vertices in it.
Answer: b
Explanation: A graph is known as bipartite graph if and only if it has the total chromatic number less than or
equal to 2. The smallest number of graphs needed to color the graph is chromatic number.
3. Which of the following is the correct type of spectrum of the bipartite graph?
a) Symmetric
b) Anti – Symmetric
c) Circular
d) Exponential
Answer: a
Explanation: The spectrum of the bipartite graph is symmetric in nature. The spectrum is the property of
graph that are related to polynomial, Eigen values, Eigen vectors of the matrix related to graph.
Answer: d
Explanation: A graph is known to be bipartite if it has odd length cycle number. It also has symmetric
spectrum and the bipartite graph contains the total chromatic number less than or equal to 2.
Answer: a
Explanation: A graph is known as bipartite graph if and only if it has the total chromatic number less than or
equal to 2. The smallest number of graphs needed to color the graph is the chromatic number.
advertisement
6. Which graph has a size of minimum vertex cover equal to maximum matching?
a) Cartesian
b) Tree
c) Heap
d) Bipartite
Answer: d
Explanation: The Konig’s theorem given the equivalence relation between the minimum vertex cover and
the maximum matching in graph theory. Bipartite graph has a size of minimum vertex cover equal to
maximum matching.
7. Which theorem gives the relation between the minimum vertex cover and maximum matching?
a) Konig’s Theorem
b) Kirchhoff’s Theorem
c) Kuratowski’s Theorem
d) Kelmans Theorem
Answer: a
Explanation: The Konig’s theorem given the equivalence relation between the minimum vertex cover and
the maximum matching in graph theory. Bipartite graph has a size of minimum vertex cover equal to
maximum matching.
Answer: d
Explanation: TThe Compliment of Line Graph of Bipartite Graph, Compliment of Bipartite Graph, Line
Graph of Bipartite Graph and every Bipartite Graph is known as a perfect graph in graph theory. Normal
line graph is not a perfect graph whereas line perfect graph is a graph whose line graph is a perfect graph.
9. Which of the following graphs don’t have chromatin number less than or equal to 2?
a) Compliment of Line Graph of Bipartite Graph
b) Compliment of Bipartite Graph
c) Line Graph of Bipartite Graph
d) Wheel graph
Answer: d
Explanation: The perfect bipartite graph has chromatic number 2. Also, the Compliment of Line Graph of
Bipartite Graph, Compliment of Bipartite Graph, Line Graph of Bipartite Graph and every Bipartite Graph is
known as perfect graph in graph theory. Wheel graph Wn has chromatin number 3 if n is odd and 4 if n is
even.
11. What is the chromatic number of compliment of line graph of bipartite graph?
a) 0
b) 1
c) 2
d) 3
Answer: c
Explanation: The perfect bipartite graph has chromatic number 2. So the Compliment of Line Graph of
Bipartite Graph, Compliment of Bipartite Graph, Line Graph of Bipartite Graph and every Bipartite Graph
has chromatic number 2.
12. What is the clique size of the line graph of bipartite graph?
a) 0
b) 1
c) 2
d) 3
Answer: c
Explanation: The perfect bipartite graph has clique size 2. So the clique size of Compliment of Line Graph
of Bipartite Graph, Compliment of Bipartite Graph, Line Graph of Bipartite Graph and every Bipartite
Graph is 2.
Answer: b
Explanation: A graph is known as bipartite graph if and only if it has the total chromatic number less than or
equal to 2. The smallest number of graphs needed to color the graph is the chromatic number. But the
chromatic number cannot be negative.
Answer: a
Explanation: Berge theorem proves the forbidden graph characterization of every perfect graphs. Because of
that reason every bipartite graph is perfect graph.
1. Which type of graph has all the vertex of the first set connected to all the vertex of the second set?
a) Bipartite
b) Complete Bipartite
c) Cartesian
d) Pie
Answer: b
Explanation: The graph is known as Bipartite if the graph does not contain any odd length cycle in it. The
complete bipartite graph has all the vertex of first set connected to all the vertex of second set.
Answer: b
Explanation: A graph is known as complete bipartite graph if and only if it has all the vertex of first set
connected to all the vertex of second set. Complete Bipartite graph is also known as Biclique.
3. Which term defines all the complete bipartite graph that are trees?
a) Symmetric
b) Anti – Symmetric
c) Circular
d) Stars
Answer: d
Explanation: Star is a complete bipartite graph with one internal node and k leaves. Therefore, all complete
bipartite graph which is trees are known as stars in graph theory.
Answer: c
Explanation: A n vertex triangle free graph contains a total of n2 / 4 number of edges. This is stated by
Mantel’s Theorem which is a special case in Turan’s theorem for r=2.
Answer: d
Explanation: NP stands for nondeterministic polynomial time. In a bipartite graph, the testing of a complete
bipartite subgraph in a bipartite graph is an NP-Complete Problem.
Answer: a
Explanation: Minor graph is formed by deleting certain number of edges from a graph or by deleting certain
number off vertices from a graph. Hence Planar graph cannot contain K3, 3 as a minor graph.
8. Which of the following is not an Eigen value of the adjacency matrix of the complete bipartite graph?
a) (nm)1/2
b) (-nm)1/2
c) 0
d) nm
Answer: d
Explanation: The adjacency matrix is a square matrix that is used to represent a finite graph. Therefore, the
Eigen values for the complete bipartite graph is found to be (nm)1/2, (-nm)1/2, 0.
Answer: c
Explanation: Minor graph is formed by deleting certain number of edges from a graph or by deleting certain
number off vertices from a graph. Hence Outer Planar graph cannot contain K3, 2 as a minor graph.
11. What is the multiplicity for the adjacency matrix of complete bipartite graph for 0 Eigen value?
a) 1
b) n + m – 2
c) 0
d) 2
Answer: b
Explanation: The adjacency matrix is a square matrix that is used to represent a finite graph. The multiplicity
of the adjacency matrix off complete bipartite graph with Eigen Value 0 is n + m – 2.
12. Which of the following is not an Eigen value of the Laplacian matrix of the complete bipartite graph?
a) n + m
b) n
c) 0
d) n*m
Answer: d
Explanation: The laplacian matrix is used to represent a finite graph in the mathematical field of Graph
Theory. Therefore, the Eigen values for the complete bipartite graph is found to be n + m, n, m, 0.
13. What is the multiplicity for the laplacian matrix of the complete bipartite graph for n Eigen value?
a) 1
b) m-1
c) n-1
d) 0
Answer: b
Explanation: The laplacian matrix is used to represent a finite graph in the mathematical field of Graph
Theory. The multiplicity of the laplacian matrix of complete bipartite graph with Eigen Value n is m-1.
Answer: a
Explanation: Yes, the modular graph in graph theory is defined as an undirected graph in which all three
vertices have at least one median vertex. So all complete bipartite graph is called modular graph.
15. How many spanning trees does a complete bipartite graph contain?
a) nm
b) mn-1 * nn-1
c) 1
d) 0
Answer: b
Explanation: Spanning tree
1. Recursion is a method in which the solution of a problem depends on ____________
a) Larger instances of different problems
b) Larger instances of the same problem
c) Smaller instances of the same problem
d) Smaller instances of different problems
Answer: c
Explanation: In recursion, the solution of a problem depends on the solution of smaller instances of the same
problem.
Answer: d
Explanation: Problems without base case leads to infinite recursion call. In general, we will assume a base
case to avoid infinite recursion call. Problems like finding Factorial of a number, Nth Fibonacci number and
Length of a string can be solved using recursion.
Answer: b
Explanation: Recursion is similar to a loop.
4. In recursion, the condition for which the function will stop calling itself is ____________
a) Best case
b) Worst case
c) Base case
d) There is no such condition
Answer: c
Explanation: For recursion to end at some point, there always has to be a condition for which the function
will not call itself. This condition is known as base case.
void my_recursive_function()
{
my_recursive_function();
}
int main()
{
my_recursive_function();
return 0;
}
a) The code will be executed successfully and no output will be generated
b) The code will be executed successfully and random output will be generated
c) The code will show a compile time error
d) The code will run for some time and stop when the stack overflows
Answer: d
Explanation: Every function call is stored in the stack memory. In this case, there is no terminating
condition(base case). So, my_recursive_function() will be called continuously till the stack overflows and
there is no more space to store the function calls. At this point of time, the program will stop abruptly.
advertisement
void my_recursive_function(int n)
{
if(n == 0)
return;
printf("%d ",n);
my_recursive_function(n-1);
}
int main()
{
my_recursive_function(10);
return 0;
}
a) 10
b) 1
c) 10 9 8 … 1 0
d) 10 9 8 … 1
Answer: d
Explanation: The program prints the numbers from 10 to 1.
void my_recursive_function(int n)
{
if(n == 0)
return;
printf("%d ",n);
my_recursive_function(n-1);
}
int main()
{
my_recursive_function(10);
return 0;
}
a) return
b) printf(“%d “, n)
c) if(n == 0)
d) my_recursive_function(n-1)
Answer: c
Explanation: For the base case, the recursive function is not called. So, “if(n == 0)” is the base case.
8. How many times is the recursive function called, when the following code is executed?
void my_recursive_function(int n)
{
if(n == 0)
return;
printf("%d ",n);
my_recursive_function(n-1);
}
int main()
{
my_recursive_function(10);
return 0;
}
a) 9
b) 10
c) 11
d) 12
Answer: c
Explanation: The recursive function is called 11 times.
void my_recursive_function(int n)
{
if(n == 0)
return;
my_recursive_function(n-1);
printf("%d ",n);
}
int main()
{
my_recursive_function(10);
return 0;
}
Answer: c
Explanation: The above code prints the numbers from 1 to 10.
Answer: b
Explanation: Recursion uses more memory compared to iteration because every time the recursive function
is called, the function call is stored in stack.
a) 123456789
b) 10
c) 0
d) 9
Answer: d
Explanation: The program prints the number of digits in the number 123456789, which is 9.
void my_recursive_function(int n)
{
if(n == 0)
{
printf("False");
return;
}
if(n == 1)
{
printf("True");
return;
}
if(n%2==0)
my_recursive_function(n/2);
else
{
printf("False");
return;
}
}
int main()
{
my_recursive_function(100);
return 0;
}
a) True
b) False
Answer: b
Explanation: The function checks if a number is a power of 2. Since 100 is not a power of 2, it prints false.
int cnt = 0;
void my_recursive_function(char *s, int i)
{
if(s[i] == '\0')
return;
if(s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u')
cnt++;
my_recursive_function(s,i+1);
}
int main()
{
my_recursive_function("thisisrecursion",0);
printf("%d",cnt);
return 0;
}
a) 6
b) 9
c) 5
d) 10
Answer: a
Explanation: The function counts the number of vowels in a string. In this case the number is vowels is 6.
a) 3
b) 4
c) 5
d) 6
Answer: b
Explanation: The progra
1. In general, which of the following methods isn’t used to find the factorial of a number?
a) Recursion
b) Iteration
c) Dynamic programming
d) Non iterative / recursive
Answer: d
Explanation: In general we use recursion, iteration and dynamic programming to find the factorial of a
number. We can also implement without using iterative / recursive method by using tgammal() method.
Most of us never use it generally.
2. Which of the following recursive formula can be used to find the factorial of a number?
a) fact(n) = n * fact(n)
b) fact(n) = n * fact(n+1)
c) fact(n) = n * fact(n-1)
d) fact(n) = n * fact(1)
Answer: c
Explanation: fact(n) = n * fact(n – 1) can be used to find the factorial of a number.
3. Consider the following iterative implementation to find the factorial of a number. Which of the lines
should be inserted to complete the below code?
int main()
{
int n = 6, i;
int fact = 1;
for(i=1;i<=n;i++)
_________;
printf("%d",fact);
return 0;
}
a) fact = fact + i
b) fact = fact * i
c) i = i * fact
d) i = i + fact
Answer: b
Explanation: The line “fact = fact * i” should be inserted to complete the above code.
4. Consider the following recursive implementation to find the factorial of a number. Which of the lines
should be inserted to complete the below code?
int fact(int n)
{
if(_________)
return 1;
return n * fact(n - 1);
}
int main()
{
int n = 5;
int ans = fact(n);
printf("%d",ans);
return 0;
}
a) n = 0
b) n != 0
c) n == 0
d) n == 1
Answer: c
Explanation: The line “n == 0” should be inserted to complete the above code.
Note: “n == 1” cannot be used because it does not take care of the case when n = 0, i.e when we want to find
the factorial of 0.
advertisement
5. The time complexity of the following recursive implementation to find the factorial of a number is
________
int fact(int n)
{
if(_________)
return 1;
return n * fact(n - 1);
}
int main()
{
int n = 5;
int ans = fact(n);
printf("%d",ans);
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
Answer: b
Explanation: The time complexity of the above recursive implementation to find the factorial of a number is
O(n).
6. What is the space complexity of the following recursive implementation to find the factorial of a number?
int fact(int n)
{
if(_________)
return 1;
return n * fact(n - 1);
}
int main()
{
int n = 5;
int ans = fact(n);
printf("%d",ans);
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
Answer: a
Explanation: The space complexity of the above recursive implementation to find the factorial of a number
is O(1).
7. Consider the following recursive implementation to find the factorial of a number. Which of the lines is
the base case?
int fact(int n)
{
if(n == 0)
return 1;
return n * fact(n - 1);
}
int main()
{
int n = 5;
int ans = fact(n);
printf("%d",ans);
return 0;
}
a) return 1
b) return n * fact(n-1)
c) if(n == 0)
d) if(n == 1)
Answer: c
Explanation: The line “if(n == 0)” is the base case.
int fact(int n)
{
if(n == 0)
return 1;
return n * fact(n - 1);
}
int main()
{
int n = 0;
int ans = fact(n);
printf("%d",ans);
return 0;
}
a) 0
b) 1
c) 2
d) 3
Answer: b
Explanation: The program prints 0!, which is 1.
int fact(int n)
{
if(n == 0)
return 1;
return n * fact(n - 1);
}
int main()
{
int n = 1;
int ans = fact(n);
printf("%d",ans);
return 0;
}
a) 0
b) 1
c) 2
d) 3
Answer: b
Explanation: The program prints 1!, which is 1.
10. How many times will the function fact() be called when the following code is executed?
int fact(int n)
{
if(n == 0)
return 1;
return n * fact(n - 1);
}
int main()
{
int n = 5;
int ans = fact(n);
printf("%d",ans);
return 0;
}
a) 4
b) 5
c) 6
d) 7
Answer: c
Explanation: The fact() function will be called 6 times with the following arguments:
fact(5), fact(4), fact(3), fact(2), fact(1), fact(0).
int fact(int n)
{
if(n == 0)
return 1;
return n * fact(n - 1);
}
int main()
{
int n = 5;
int ans = fact(n);
printf("%d",ans);
return 0;
}
a) 24
b) 120
c) 720
d) 1
Answer: b
Explanation: The func
1. Suppose the first fibonnaci number is 0 and the second is 1. What is the sixth fibonnaci number?
a) 5
b) 6
c) 7
d) 8
Answer: a
Explanation: The sixth fibonnaci number is 5.
Answer: d
Explanation: 14 is not a fibonnaci number.
Answer: d
Explanation: Fibonacci number can be calculated by using Dynamic Programming, Recursion method,
Iteration Method.
4. Consider the following iterative implementation to find the nth fibonacci number?
int main()
{
int n = 10,i;
if(n == 1)
printf("0");
else if(n == 2)
printf("1");
else
{
int a = 0, b = 1, c;
for(i = 3; i <= n; i++)
{
c = a + b;
________;
________;
}
printf("%d",c);
}
return 0;
}
Which of the following lines should be added to complete the above code?
a)
c = b
b = a
b)
a = b
b = c
advertisement
c)
b = c
a = b
d)
a = b
b = a
Answer: b
Explanation: The lines “a = b” and “b = c” should be added to complete the above code.
5. Which of the following recurrence relations can be used to find the nth fibonacci number?
a) F(n) = F(n) + F(n – 1)
b) F(n) = F(n) + F(n + 1)
c) F(n) = F(n – 1)
d) F(n) = F(n – 1) + F(n – 2)
Answer: d
Explanation: The relation F(n) = F(n – 1) + F(n – 2) can be used to find the nth fibonacci number.
6. Consider the following recursive implementation to find the nth fibonacci number:
int fibo(int n)
{
if(n == 1)
return 0;
else if(n == 2)
return 1;
return ________;
}
int main()
{
int n = 5;
int ans = fibo(n);
printf("%d",ans);
return 0;
}
Which of the following lines should be inserted to complete the above code?
a) fibo(n – 1)
b) fibo(n – 1) + fibo(n – 2)
c) fibo(n) + fibo(n – 1)
d) fibo(n – 2) + fibo(n – 1)
Answer: b
Explanation: The line fibo(n – 1) + fibo(n – 2) should be inserted to complete the above code.
7. Consider the following recursive implementation to find the nth fibonnaci number:
int fibo(int n)
{
if(n == 1)
return 0;
else if(n == 2)
return 1;
return fibo(n - 1) + fibo(n - 2);
}
int main()
{
int n = 5;
int ans = fibo(n);
printf("%d",ans);
return 0;
}
Answer: d
Explanation: Both if(n == 1) and else if(n == 2) are the base cases.
8. What is the time complexity of the following recursive implementation to find the nth fibonacci number?
int fibo(int n)
{
if(n == 1)
return 0;
else if(n == 2)
return 1;
return fibo(n - 1) + fibo(n - 2);
}
int main()
{
int n = 5;
int ans = fibo(n);
printf("%d",ans);
return 0;
}
a) O(1)
b) O(2*n)
c) O(n2)
d) O(2n)
Answer: d
Explanation: The time complexity of the above recursive implementation to find the nth fibonacci number is
O(2n).
9. What is the space complexity of the following recursive implementation to find the nth fibonacci number?
int fibo(int n)
{
if(n == 1)
return 0;
else if(n == 2)
return 1;
return fibo(n - 1) + fibo(n - 2);
}
int main()
{
int n = 5;
int ans = fibo(n);
printf("%d",ans);
return 0;
}
a) O(1)
b) O(2*n)
c) O(n2)
d) O(2n)
Answer: a
Explanation: The space complexity of the above recursive implementation to find the nth fibonacci number
is O(1).
int fibo(int n)
{
if(n == 1)
return 0;
else if(n == 2)
return 1;
return fibo(n - 1) + fibo(n - 2);
}
int main()
{
int n = -1;
int ans = fibo(n);
printf("%d",ans);
return 0;
}
a) 0
b) 1
c) Compile time error
d) Runtime error
Answer: d
Explanation: Since negative numbers are not handled by the program, the function fibo() will be called
infinite times and the program will produce a runtime error when the stack overflows.
a) 1
b) 2
c) 3
d) 5
Answer: c
Explanation: The program prints the 5th fibonacci number, which is 3.
12. How many times will the function fibo() be called when the following code is executed?
int fibo(int n)
{
if(n == 1)
return 0;
else if(n == 2)
return 1;
return fibo(n - 1) + fibo(n - 2);
}
int main()
{
int n = 5;
int ans = fibo(n);
printf("%d",ans);
return 0;
}
a) 5
b) 6
c) 8
d) 9
Answer: d
Explanation: The function fibo() will be called 9 times, when the above code is executed.
int fibo(int n)
{
if(n == 1)
return 0;
else if(n == 2)
return 1;
return fibo(n - 1) + fibo(n - 2);
}
int main()
{
int n = 10;
int ans = fibo(n);
printf("%d",ans);
return 0;
}
a) 21
b) 34
c) 55
d) 13
Answer: b
Explanation: The p
Answer: d
Explanation: All of the above mentioned methods can be used to find the sum of first n natural numbers.
2. Which of the following gives the sum of the first n natural numbers?
a) nC2
b) (n-1)C2
c) (n+1)C2
d) (n+2)C2
Answer: c
Explanation: The sum of first n natural numbers is given by n*(n+1)/2, which is equal to (n+1)C2.
3. Consider the following iterative solution to find the sum of first n natural numbers:
#include<stdio.h>
int get_sum(int n)
{
int sm = 0, i;
for(i = 1; i <= n; i++)
________;
return sm;
}
int main()
{
int n = 10;
int ans = get_sum(n);
printf("%d",ans);
return 0;
}
Answer: b
Explanation: The line “sm += i” completes the above code.
#include<stdio.h>
int get_sum(int n)
{
int sm, i;
for(i = 1; i <= n; i++)
sm += i;
return sm;
}
int main()
{
int n = 10;
int ans = get_sum(n);
printf("%d",ans);
return 0;
}
a) 55
b) 45
c) 35
d) Depends on compiler
Answer: d
Explanation: Since the variable “sm” is not initialized to 0, it will produce a garbage value. Some compiler
will automatically initialises variables to 0 if not initialised. In that case the value is 55. Hence the value
depends on the compiler.
advertisement
5. What is the time complexity of the following iterative method used to find the sum of the first n natural
numbers?
#include<stdio.h>
int get_sum(int n)
{
int sm, i;
for(i = 1; i <= n; i++)
sm += i;
return sm;
}
int main()
{
int n = 10;
int ans = get_sum(n);
printf("%d",ans);
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
Answer: b
Explanation: The time complexity of the above iterative method used to find the sum of first n natural
numbers is O(n).
#include<stdio.h>
int recursive_sum(int n)
{
if(n == 0)
return 0;
return ________;
}
int main()
{
int n = 5;
int ans = recursive_sum(n);
printf("%d",ans);
return 0;
}
Which of the following lines is the recurrence relation for the above code?
a) (n – 1) +recursive_sum(n)
b) n + recursive_sum(n)
c) n + recursive_sum(n – 1)
d) (n – 1) + recursive_sum(n – 1)
Answer: c
Explanation: The recurrence relation for the above code is: n + recursive_sum(n – 1).
#include<stdio.h>
int recursive_sum(int n)
{
if(n == 0)
return 0;
return n + recursive_sum(n - 1);
}
int main()
{
int n = 5;
int ans = recursive_sum(n);
printf("%d",ans);
return 0;
}
Which of the following is the base case for the above recursive code?
a) if(n == 0)
b) return 0
c) return n + recursive_sum(n – 1)
d) if(n == 1)
Answer: a
Explanation: “if(n == 0)” is the base case for the above recursive code.
8. What is the time complexity of the following recursive implementation used to find the sum of the first n
natural numbers?
#include<stdio.h>
int recursive_sum(int n)
{
if(n == 0)
return 0;
return n + recursive_sum(n - 1);
}
int main()
{
int n = 5;
int ans = recursive_sum(n);
printf("%d",ans);
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
Answer: b
Explanation: The time complexity of the above recursive implementation used to find the sum of first n
natural numbers is O(n).
9. Which of the following methods used to find the sum of first n natural numbers has the least time
complexity?
a) Recursion
b) Iteration
c) Binomial coefficient
d) All have equal time complexity
Answer: c
Explanation: Recursion and iteration take O(n) time to find the sum of first n natural numbers while
binomial coefficient takes O(1) time.
#include<stdio.h>
int recursive_sum(int n)
{
if(n == 0)
return 0;
return n + recursive_sum(n - 1);
}
int main()
{
int n = 5;
int ans = recursive_sum(n);
printf("%d",ans);
return 0;
}
a) 10
b) 15
c) 21
d) 14
Answer: b
Explanation: The above code prints the sum of first 5 natural numbers, which is 15.
11. How many times is the function recursive_sum() called when the following code is executed?
#include<stdio.h>
int recursive_sum(int n)
{
if(n == 0)
return 0;
return n + recursive_sum(n - 1);
}
int main()
{
int n = 5;
int ans = recursive_sum(n);
printf("%d",ans);
return 0;
}
a) 4
b) 5
c) 6
d) 7
Answer: c
Explanation: The function recursive_sum is called 6 times when the following code is executed.
#include<stdio.h>
int recursive_sum(int n)
{
if(n == 0)
return 0;
return n + recursive_sum(n - 1);
}
int main()
{
int n = 0;
int ans = recursive_sum(n);
printf("%d",ans);
return 0;
}
a) -1
b) 0
c) 1
d) runtime error
Answer: b
Explanation: The program prints the sum of first 0 natural numbers, which is 0.
#include<stdio.h>
int recursive_sum(int n)
{
if(n == 0)
return 0;
return n + recursive_sum(n - 1);
}
int main()
{
int n = -4;
int ans = recursive_sum(n);
printf("%d",ans);
return 0;
}
a) 0
b) -10
c) 1
d) runtime error
Answer: d
Explanation: The a
1. Which of the following is not another name for GCD(Greatest Common Divisor)?
a) LCM
b) GCM
c) GCF
d) HCF
Answer: a
Explanation: : LCM (Least Common Multiple) and GCD are not same. GCM (Greatest Common Measure),
GCF (Greatest Common Factor), HCF (Highest Common Factor) are other names for GCD.
Answer: d
Explanation: GCD is largest positive integer that divides each of the integer. So the GCD of 8 and 12 is 4.
3. If GCD of two number is 8 and LCM is 144, then what is the second number if first number is 72?
a) 24
b) 2
c) 3
d) 16
Answer: d
Explanation: As A * B = GCD (A, B) * LCM (A, B). So B = (144 * 8)/72 = 16.
Answer: d
Explanation: Coprime numbers have GCD 1. So 9 and 28 are coprime numbers. While 54 and 24 have GCD
6, 4 and 8 have GCD 4, 6 and 12 have GCD 6.
advertisement
6. In terms of Venn Diagram, which of the following expression gives GCD (Given A ꓵ B ≠ Ø)?
a) Multiplication of A U B terms
b) Multiplication of A ꓵ B terms
c) Multiplication of A*B terms
d) Multiplication of A-B terms
Answer: b
Explanation: In terms of Venn Diagram, the GCD is given by the intersection of two sets. So A ꓵ B gives
the GCD. While A U B gives the LCM.
a) 2
b) 3
c) 5
d) 6
Answer: c
Explanation: In terms of Venn Diagram, the GCD is given by the intersection of two sets. So A ꓵ B gives
the GCD. While A U B gives the LCM. So here A ꓵ B is 5.
Answer: d
Explanation: GCD is largest positive integer that divides each of the integer. So the GCD of 48, 18, 0 is 6.
Answer: a
Explanation: Coprime numbers have GCD 1. So 9 and 28 are coprime numbers.
11. If gcd (a, b) is defined by the expression, d=a*p + b*q where d, p, q are positive integers and a, b is both
not zero, then what is the expression called?
a) Bezout’s Identity
b) Multiplicative Identity
c) Sum of Product
d) Product of Sum
Answer: a
Explanation: If gcd (a, b) is defined by the expression, d=a*p + b*q where d, p, q are positive integers and a,
b is both not zero, then the expression is called Bezout’s Identity and p, q can be calculated by extended
form of Euclidean algorithm.
Answer: a
Explanation: The gcd function is an associative function as gcd (a, gcd (b, c)) = gcd (gcd (a, b), c).
13. Which is the correct term of the given relation, gcd (a, b) * lcm (a, b) =?
a) |a*b|
b) a + b
c) a – b
d) a / b
Answer: a
Explanation: The gcd is closely related to lcm as gcd (a, b) * lcm (a, b) = |a*b|.
14. Who gave the expression for the probability and expected value of gcd?
a) James E. Nymann
b) Riemann
c) Thomae
d) Euler
Answer: a
Explanation: In the year 1972, James E. Nymann showed some result to show the probability and expected
value of gcd.
15. What is the computational complexity of Binary GCD algorithm where a and b are integers?
a) O (log a + log b)2)
b) O (log (a + b))
c) O (log ab)
d) O (log a-b)
Answer: a
Explanation: Fro
Answer: b
Explanation: GCD (Greatest Common Divisor), GCF (Greatest Common Factor), HCF (Highest Common
Factor) is not an alias for LCM. LCM is also called as Smallest Common Multiple(SCM).
Answer: d
Explanation: 104 is the smallest positive integer that is divisible by both 8 and 12.
Answer: d
Explanation: LCM of 2, 4, 8 is 8. So check for the number that is divisible by 8. So 104 is the smallest
number that is divisible by 2, 4, 8.
Answer: a
Explanation: Least Common Multiple is also known as LCM or Lowest Common Multiple.
Answer: d
Explanation: Coprime numbers have GCD 1. While LCM of coprime numbers is the product of those two
coprime numbers.
advertisement
6. In terms of Venn Diagram, which of the following expression gives LCM (Given A ꓵ B ≠ Ø)?
a) Multiplication of A U B terms
b) Multiplication of A ꓵ B terms
c) Multiplication of A*B terms
d) Multiplication of A-B terms
Answer: a
Explanation: In terms of Venn Diagram, the LCM is given by the Union of two sets. So A U B gives the
LCM. While A ꓵ B gives the GCD.
a) 2
b) 3
c) 180
d) 6
Answer: c
Explanation: In terms of Venn Diagram, the LCM is given by the Union of two sets. So A U B gives the
LCM. So product of all the terms is 180.
Answer: a
Explanation: The LCM of 48, 18, 6 is 144 and 122 is 144.
Answer: a
Explanation: Coprime numbers have GCD 1 and LCM is the product of the two given terms. So 9 and 28 are
coprime numbers.
11. What is the following expression, lcm (a, lcm (b, c) equal to?
a) lcm (a, b, c)
b) a*b*c
c) a + b + c
d) lcm (lcm (a, b), c)
Answer: d
Explanation: Since LCM function follows associativity, hence lcm (a, lcm (b, c) is equal to lcm (lcm (a, b),
c).
Answer: a
Explanation: The lcm function is an associative function as lcm (a, lcm (b, c) is equal to lcm (lcm (a, b), c).
13. Which is the correct term of the given relation, lcm (a, b) * gcd (a, b) =?
a) |a*b|
b) a + b
c) a – b
d) a / b
Answer: a
Explanation: The lcm is closely related to gcd as lcm (a, b) * gcd (a, b) = |a*b|.
14. What is the following expression, lcm (a, gcd (a, b)) equal to?
a) a
b) b
c) a*b
d) a + b
Answer: a
Explanation: Since the lcm function follows absorption laws so lcm (a, gcd (a, b)) equal to a.
15. Which algorithm is the most efficient numerical algorithm to obtain lcm?
a) Euler’s Algorithm
b) Euclid’s Algorithm
c) Chebyshev Function
d) Partial Division Algorithm
Answer: b
Explanation: The most efficient way of calculating the lcm of a given number is using Euclid’s algorithm
which
1. Which of the following methods can be used to find the sum of digits of a number?
a) Recursion
b) Iteration
c) Greedy algorithm
d) Both recursion and iteration
Answer: d
Explanation: Both recursion and iteration can be used to find the sum of digits of a number.
Answer: c
Explanation: The sum of digits will be maximum when all the digits are 9. Thus, the sum will be maximum
for the number 9999, which is 36.
Answer: b
Explanation: The sum of digits will be minimum for the number 1000 and the sum is 1.
4. Consider the following iterative implementation to find the sum of digits of a number:
#include<stdio.h>
int sum_of_digits(int n)
{
int sm = 0;
while(n != 0)
{
_________;
n /= 10;
}
return sm;
}
int main()
{
int n = 1234;
int ans = sum_of_digits(n);
printf("%d",ans);
return 0;
}
Which of the following lines should be inserted to complete the above code?
a) sm += n
b) sm += n%10
c) sm += n-10
d) sm += n/10
Answer: b
Explanation: The line “sm += n % 10” adds the last digit(LSB) of the number to the current sum. Thus, the
line “sm += n%10” should be added to complete the above code.
advertisement
#include<stdio.h>
int sum_of_digits(int n)
{
int sm = 0;
while(n != 0)
{
sm += n%10;
n /= 10;
}
return sm;
}
int main()
{
int n = 1234;
int ans = sum_of_digits(n);
printf("%d",ans);
return 0;
}
a) 1
b) 3
c) 7
d) 10
Answer: d
Explanation: The above code prints the sum of digits of the number 1234, which is 10.
6. Consider the following recursive implementation to find the sum of digits of number:
#include<stdio.h>
int recursive_sum_of_digits(int n)
{
if(n == 0)
return 0;
return _________;
}
int main()
{
int n = 1201;
int ans = recursive_sum_of_digits(n);
printf("%d",ans);
return 0;
}
Which of the following lines should be inserted to complete the above code?
a) (n / 10) + recursive_sum_of_digits(n % 10)
b) (n) + recursive_sum_of_digits(n % 10)
c) (n % 10) + recursive_sum_of_digits(n / 10)
d) (n % 10) + recursive_sum_of_digits(n % 10)
Answer: c
Explanation: The line “(n % 10) + recursive_sum_of_digits(n / 10)” should be inserted to complete the
above code.
7. What is the time complexity of the following recursive implementation to find the sum of digits of a
number n?
#include<stdio.h>
int recursive_sum_of_digits(int n)
{
if(n == 0)
return 0;
return _________;
}
int main()
{
int n = 1201;
int ans = recursive_sum_of_digits(n);
printf("%d",ans);
return 0;
}
a) O(n)
b) O(1)
c) O(len(n)), where len(n) is the number of digits in n
d) O(1/2)
Answer: c
Explanation: The time complexity of the above recursive implementation to find the sum of digits of a
number is O(len(n)).
#include<stdio.h>
int recursive_sum_of_digits(int n)
{
if(n == 0)
return 0;
return n % 10 + recursive_sum_of_digits(n/10);
}
int main()
{
int n = 1234321;
int ans = recursive_sum_of_digits(n);
printf("%d",ans);
return 0;
}
a) 10
b) 16
c) 15
d) 14
Answer: b
Explanation: The above code prints the sum of digits of the number 1234321, which is 16.
9. How many times is the function recursive_sum_of_digits() called when the following code is executed?
#include<stdio.h>
int recursive_sum_of_digits(int n)
{
if(n == 0)
return 0;
return n % 10 + recursive_sum_of_digits(n/10);
}
int main()
{
int n = 1201;
int ans = recursive_sum_of_digits(n);
printf("%d",ans);
return 0;
}
a) 6
b) 7
c) 5
d) 9
Answer: c
Explanation: The function recursive_sum_of_digits() is called 8 times, when the following code is executed.
10. You have to find the sum of digits of a number given that the number is always greater than 0. Which of
the following base cases can replace the base case for the below code?
#include<stdio.h>
int recursive_sum_of_digits(int n)
{
if(n == 0)
return 0;
return n % 10 + recursive_sum_of_digits(n/10);
}
int main()
{
int n = 1201;
int ans = recursive_sum_of_digits(n);
printf("%d",ans);
return 0;
}
a) if(n == 0) return 1
b) if(n == 1) return 0
c) if(n == 1) return 1
d) no need to modify the base case
Answer: d
Explanation: None of the above mentioned base cases can replace the base case if(n == 0) return 0.
#include<stdio.h>
int recursive_sum_of_digits(int n)
{
if(n == 0)
return 0;
return n % 10 + recursive_sum_of_digits(n/10);
}
int main()
{
int n = 10000;
int ans = recursive_sum_of_digits(n);
printf("%d",ans);
return 0;
}
a) 0
b) 1
c) runtime error
d) -1
Answer: b
Explanation: The program prints the sum of digits of the number 10000, which is 1.
#include<stdio.h>
int cnt =0;
int my_function(int n, int sm)
{
int i, tmp_sm;
for(i=1;i<=n;i++)
{
tmp_sm = recursive_sum_of_digits(i);
if(tmp_sm == sm)
cnt++;
}
return cnt;
}
int recursive_sum_of_digits(int n)
{
if(n == 0)
return 0;
return n % 10 + recursive_sum_of_digits(n/10);
}
int main()
{
int n = 20, sum = 3;
int ans = my_function(n,sum);
printf("%d",ans);
return 0;
}
a) 0
b) 1
c) 2
d) 3
Answer: c
Explanation: The code prints the count of numbers between 1 and 20 such that the sum of their digits is 3.
#include<stdio.h>
#include<string.h>
void reverse_string(char *s)
{
int len = strlen(s);
int i,j;
i=0;
j=len-1;
while(______)
{
char tmp = s[i];
s[i] = s[j];
s[j] = tmp;
i++;
j--;
}
}
Which of the following lines should be inserted to complete the above code?
a) i > j
b) i < len
c) j > 0
d) i < j
Answer: d
Explanation: The line “i < j” should be inserted to complete the above code.
#include<stdio.h>
#include<string.h>
void reverse_string(char *s)
{
int len = strlen(s);
int i,j;
i=0;
j=len-1;
while(i < j)
{
char tmp = s[i];
s[i] = s[j];
s[j] = tmp;
i++;
j--;
}
}
int main()
{
char s[100] = "reverse";
reverse_string(s);
printf("%s",s);
return 0;
}
a) ersevre
b) esrever
c) eserver
d) eresevr
Answer: b
Explanation: The program reverses the string “reverse” and prints “esrever”.
3. What is the time complexity of the above code used to reverse a string?
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
Answer: b
Explanation: The time complexity of the above code used to reverse a string is O(n).
advertisement
#include<stdio.h>
#include<string.h>
void reverse_string(char *s)
{
int len = strlen(s);
int i,j;
i=0;
j=len-1;
while(i < j)
{
char tmp = s[i];
s[i] = s[j];
s[j] = tmp;
i++;
j--;
}
}
int main()
{
char s[100] = "abcdefg";
char t[100];
strcpy(t,s);
reverse_string(s);
if(strcmp(t,s) == 0)
printf("Yes");
else
printf("No");
return 0;
}
#include<stdio.h>
#include<string.h>
void reverse_string(char *s)
{
int len = strlen(s);
int i,j;
i=0;
j=len-1;
while(i < j)
{
char tmp = s[i];
s[i] = s[j];
s[j] = tmp;
i++;
j--;
}
}
int main()
{
char s[100] = "rotator";
char t[100];
strcpy(t,s);
reverse_string(s);
if(strcmp(t,s) == 0)
printf("Yes");
else
printf("No");
return 0;
}
a) Yes
b) No
c) Runtime error
d) Compile time error
Answer: a
Explanation: The program checks if a string is a palindrome. Since the string rotator is a palindrome, it
prints “yes”.
Which of the following lines should be inserted to complete the above code?
a) recursive_reverse_string(s, left+1, right+1)
b) recursive_reverse_string(s, left-1, right-1)
c) recursive_reverse_string(s, left+1, right-1)
d) recursive_reverse_string(s, left-1, right+1)
Answer: c
Explanation: The line “recursive_reverse_string(s, left+1, right-1)” should be inserted to complete the above
code.
#include<stdio.h>
#include<string.h>
void recursive_reverse_string(char *s, int left, int right)
{
if(left < right)
{
char tmp = s[left];
s[left] = s[right];
s[right] = tmp;
recursive_reverse_string(s, left+1, right-1);
}
}
int main()
{
char s[100] = "recursion";
int len = strlen(s);
recursive_reverse_string(s,0,len-1);
printf("%s",s);
return 0;
}
a) recursion
b) nsoirucer
c) noisrcuer
d) noisrucer
Answer: d
Explanation: The program prints the reversed string of “recursion”, which is “noisrucer”.
8. How many times is the function recursive_reverse_string() called when the following code is executed?
#include<stdio.h>
#include<string.h>
void recursive_reverse_string(char *s, int left, int right)
{
if(left < right)
{
char tmp = s[left];
s[left] = s[right];
s[right] = tmp;
recursive_reverse_string(s, left+1, right-1);
}
}
int main()
{
char s[100] = "madam";
int len = strlen(s);
recursive_reverse_string(s,0,len-1);
printf("%s",s);
return 0;
}
a) 3
b) 4
c) 5
d) 6
Answer: a
Explanation: The function recursive_reverse_string() is called 3 times when the above code is executed.
9. What is the time complexity of the above recursive implementation used to reverse a string?
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
Answer: b
Explanation: The time complexity of the above recursive implementation used to reverse a string is O(n).
10. In which of the following cases is the reversal of a string not equal to the original string?
a) Palindromic strings
b) Strings of length 1
c) Empty String
d) Strings of length 2
Answer: d
Explanation: String “ab” is a string of length 2 whose reversal is not the same as the given one. Palindromic
Strin
Answer: c
Explanation: 100 = 64 + 32 + 4 = 26 + 25 + 22 = 1100100.
2. Consider the following iterative code used to convert a decimal number to its equivalent binary:
#include<stdio.h>
void dec_to_bin(int n)
{
int arr[31],len = 0,i;
if(n == 0)
{
arr[0] = 0;
len = 1;
}
while(n != 0)
{
arr[len++] = n % 2;
_______;
}
for(i=len-1; i>=0; i--)
printf("%d",arr[i]);
}
int main()
{
int n = 10;
dec_to_bin(n);
return 0;
}
Which of the following lines should be inserted to complete the above code?
a) n–
b) n /= 2
c) n /= 10
d) n++
Answer: b
Explanation: The line “n /= 2” should be inserted to complete the above code.
#include<stdio.h>
void dec_to_bin(int n)
{
int arr[31],len = 0,i;
if(n == 0)
{
arr[0] = 0;
len = 1;
}
while(n != 0)
{
arr[len++] = n % 2;
n /= 2;
}
for(i=len-1; i>=0; i--)
printf("%d",arr[i]);
}
int main()
{
int n = 63;
dec_to_bin(n);
return 0;
}
a) 111111
b) 111011
c) 101101
d) 101010
Answer: a
Explanation: The program prints the binary equivalent of 63, which is 111111.
advertisement
#include<stdio.h>
void dec_to_bin(int n)
{
int arr[31],len = 0,i;
if(n == 0)
{
arr[0] = 0;
len = 1;
}
while(n != 0)
{
arr[len++] = n % 2;
n /= 2;
}
for(i=len-1; i>=0; i--)
printf("%d",arr[i]);
}
int main()
{
int n = 0;
dec_to_bin(n);
return 0;
}
a) 0
b) 1
c) Runtime error
d) Garbage value
Answer: a
Explanation: The program prints the binary equivalent of 0, which is 0.
5. What is the time complexity of the following code used to convert a decimal number to its binary
equivalent?
#include<stdio.h>
void dec_to_bin(int n)
{
int arr[31],len = 0,i;
if(n == 0)
{
arr[0] = 0;
len = 1;
}
while(n != 0)
{
arr[len++] = n % 2;
n /= 2;
}
for(i=len-1; i>=0; i--)
printf("%d",arr[i]);
}
int main()
{
int n = 0;
dec_to_bin(n);
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(logn)
Answer: d
Explanation: The time complexity of the above code used to convert a decimal number to its binary
equivalent is O(logn).
6. Consider the following recursive implementation used to convert a decimal number to its binary
equivalent:
#include<stdio.h>
int arr[31], len = 0;
void recursive_dec_to_bin(int n)
{
if(n == 0 && len == 0)
{
arr[len++] = 0;
return;
}
if(n == 0)
return;
__________;
recursive_dec_to_bin(n/2);
}
int main()
{
int n = 100,i;
recursive_dec_to_bin(n);
for(i=len-1; i>=0; i--)
printf("%d",arr[i]);
return 0;
}
Which of the following lines should be inserted to complete the above code?
a) arr[len] = n
b) arr[len] = n % 2
c) arr[len++] = n % 2
d) arr[len++] = n
Answer: c
Explanation: The line “arr[len++] = n % 2” should be inserted to complete the above code.
#include<stdio.h>
int arr[31], len = 0;
void recursive_dec_to_bin(int n)
{
if(n == 0 && len == 0)
{
arr[len++] = 0;
return;
}
if(n == 0)
return;
arr[len++] = n % 2;
recursive_dec_to_bin(n/2);
}
Which of the following lines is the base case for the above code?
a) if(n ==0 && len == 0)
b) if(n == 0)
c) if(n ==0 && len == 0) and if(n == 0)
d) if(n == 1)
Answer: c
Explanation: Both of the above mentioned lines are the base cases for the above code.
#include<stdio.h>
int arr[31], len = 0;
void recursive_dec_to_bin(int n)
{
if(n == 0 && len == 0)
{
arr[len++] = 0;
return;
}
if(n == 0)
return;
arr[len++] = n % 2;
recursive_dec_to_bin(n/2);
}
int main()
{
int n = -100,i;
recursive_dec_to_bin(n);
for(i=len-1; i>=0; i--)
printf("%d",arr[i]);
return 0;
}
a) -1100100
b) 1100100
c) 2’s complement of 1100100
d) Garbage value
Answer: d
Explanation: The program doesn’t handle negative inputs and so produces a garbage value.
9. What is the time complexity of the recursive implementation used to convert a decimal number to its
binary equivalent?
#include<stdio.h>
int arr[31], len = 0;
void recursive_dec_to_bin(int n)
{
if(n == 0 && len == 0)
{
arr[len++] = 0;
return;
}
if(n == 0)
return;
arr[len++] = n % 2;
recursive_dec_to_bin(n/2);
}
a) O(1)
b) O(n)
c) O(n2)
d) O(logn)
Answer: d
Explanation: The time complexity of the recursive implementation used to convert a decimal number to its
binary equivalent is O(logn).
10. What is the space complexity of the recursive implementation used to convert a decimal number to its
binary equivalent?
#include<stdio.h>
int arr[31], len = 0;
void recursive_dec_to_bin(int n)
{
if(n == 0 && len == 0)
{
arr[len++] = 0;
return;
}
if(n == 0)
return;
arr[len++] = n % 2;
recursive_dec_to_bin(n/2);
}
a) O(1)
b) O(n)
c) O(n2)
d) O(logn)
Answer: d
Explanation: The space complexity of the recursive implementation used to convert a decimal number to its
binary equivalent is O(logn).
#include<stdio.h>
int arr[31], len = 0;
void recursive_dec_to_bin(int n)
{
if(n == 0 && len == 0)
{
arr[len++] = 0;
return;
}
if(n == 0)
return;
arr[len++] = n % 2;
recursive_dec_to_bin(n/2);
}
int main()
{
int n = 111,i;
recursive_dec_to_bin(n);
for(i=len-1; i>=0; i--)
printf("%d",arr[i]);
return 0;
}
a) 1110111
b) 1001111
c) 1101111
d) 1010111
Answer: c
Explanation: The program prints the binary equivalent of 111, which is 1101111.
12. How many times is the function recursive_dec_to_bin() called when the following code is executed?
#include<stdio.h>
int arr[31], len = 0;
void recursive_dec_to_bin(int n)
{
if(n == 0 && len == 0)
{
arr[len++] = 0;
return;
}
if(n == 0)
return;
arr[len++] = n % 2;
recursive_dec_to_bin(n/2);
}
int main()
{
int n = 111,i;
recursive_dec_to_bin(n);
for(i=len-1; i>=0; i--)
printf("%d",arr[i]);
return 0;
}
a) 7
b) 8
c) 9
d) 10
Answer: b
Explanation: The function recursive_dec
1. Consider the following iterative implementation used to find the length of a linked list:
struct Node
{
int val;
struct Node *next;
}*head;
int get_len()
{
struct Node *temp = head->next;
int len = 0;
while(_____)
{
len++;
temp = temp->next;
}
return len;
}
Which of the following conditions should be checked to complete the above code?
a) temp->next != 0
b) temp == 0
c) temp != 0
d) temp->next == 0
Answer: c
Explanation: The condition “temp != 0” should be checked to complete the above code.
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int val;
struct Node *next;
}*head;
int get_len()
{
struct Node *temp = head->next;
int len = 0;
while(temp != 0)
{
len++;
temp = temp->next;
}
return len;
}
int main()
{
int arr[10] = {1,2,3,4,5}, n = 5, i;
struct Node *temp, *newNode;
head = (struct Node*)malloc(sizeof(struct Node));
head->next = 0;
temp = head;
for(i=0; i<n; i++)
{
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->val = arr[i];
newNode->next = 0;
temp->next = newNode;
temp = temp->next;
}
int len = get_len();
printf("%d",len);
return 0;
}
a) 4
b) 5
c) 6
d) 7
Answer: b
Explanation: The program prints the length of the linked list, which is 5.
3. What is the time complexity of the following iterative implementation used to find the length of a linked
list?
advertisement
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int val;
struct Node *next;
}*head;
int get_len()
{
struct Node *temp = head->next;
int len = 0;
while(temp != 0)
{
len++;
temp = temp->next;
}
return len;
}
int main()
{
int arr[10] = {1,2,3,4,5}, n = 5, i;
struct Node *temp, *newNode;
head = (struct Node*)malloc(sizeof(struct Node));
head->next = 0;
temp = head;
for(i=0; i<n; i++)
{
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->val = arr[i];
newNode->next = 0;
temp->next = newNode;
temp = temp->next;
}
int len = get_len();
printf("%d",len);
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(logn)
Answer: b
Explanation: The time complexity of the above iterative implementation used to find the length of a linked
list is O(n).
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int val;
struct Node *next;
}*head;
int get_len()
{
struct Node *temp = head->next;
int len = 0;
while(temp != 0)
{
len++;
temp = temp->next;
}
return len;
}
int main()
{
int arr[10] = {1,2,3,4,5}, n = 5, i;
struct Node *temp, *newNode;
head = (struct Node*)malloc(sizeof(struct Node));
head->next = 0;
int len = get_len();
printf("%d",len);
return 0;
}
a) 0
b) Garbage value
c) Compile time error
d) Runtime error
Answer: a
Explanation: The program prints the length of the linked list, which is 0.
5. Which of the following can be the base case for the recursive implementation used to find the length of
linked list?
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int val;
struct Node *next;
}*head;
int get_len()
{
struct Node *temp = head->next;
int len = 0;
while(temp != 0)
{
len++;
temp = temp->next;
}
return len;
}
int main()
{
int arr[10] = {1,2,3,4,5}, n = 5, i;
struct Node *temp, *newNode;
head = (struct Node*)malloc(sizeof(struct Node));
head->next = 0;
int len = get_len();
printf("%d",len);
return 0;
}
a) if(current_node == 0) return 1
b) if(current_node->next == 0) return 1
c) if(current_node->next == 0) return 0
d) if(current_node == 0) return 0
Answer: d
Explanation: The line “if(current_node == 0) return 0” can be used as a base case in the recursive
implementation used to find the length of a linked list. Note: The line “if(current_node->next == 0) return 1”
cannot be used because it won’t work when the length of the linked list is zero.
6. Which of the following lines should be inserted to complete the following recursive implementation used
to find the length of a linked list?
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int val;
struct Node *next;
}*head;
int recursive_get_len(struct Node *current_node)
{
if(current_node == 0)
return 0;
return _____;
}
int main()
{
int arr[10] = {1,2,3,4,5}, n = 5, i;
struct Node *temp, *newNode;
head = (struct Node*)malloc(sizeof(struct Node));
head->next = 0;
temp = head;
for(i=0; i<n; i++)
{
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->val = arr[i];
newNode->next = 0;
temp->next = newNode;
temp = temp->next;
}
int len = recursive_get_len(head->next);
printf("%d",len);
return 0;
}
a) recursive_get_len(current_node)
b) 1 + recursive_get_len(current_node)
c) recursive_get_len(current_node->next)
d) 1 + recursive_get_len(current_node->next)
Answer: d
Explanation: The line “1 + recursive_get_len(current_node->next)” should be inserted to complete the
above code.
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int val;
struct Node *next;
}*head;
int recursive_get_len(struct Node *current_node)
{
if(current_node == 0)
return 0;
return 1 + recursive_get_len(current_node->next);
}
int main()
{
int arr[10] = {-1,2,3,-3,4,5,0}, n = 7, i;
struct Node *temp, *newNode;
head = (struct Node*)malloc(sizeof(struct Node));
head->next = 0;
temp = head;
for(i=0; i<n; i++)
{
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->val = arr[i];
newNode->next = 0;
temp->next = newNode;
temp = temp->next;
}
int len = recursive_get_len(head->next);
printf("%d",len);
return 0;
}
a) 6
b) 7
c) 8
d) 9
Answer: b
Explanation: The program prints the length of the linked list, which is 7.
8. What is the time complexity of the following code used to find the length of a linked list?
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int val;
struct Node *next;
}*head;
int recursive_get_len(struct Node *current_node)
{
if(current_node == 0)
return 0;
return 1 + recursive_get_len(current_node->next);
}
int main()
{
int arr[10] = {-1,2,3,-3,4,5,0}, n = 7, i;
struct Node *temp, *newNode;
head = (struct Node*)malloc(sizeof(struct Node));
head->next = 0;
temp = head;
for(i=0; i<n; i++)
{
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->val = arr[i];
newNode->next = 0;
temp->next = newNode;
temp = temp->next;
}
int len = recursive_get_len(head->next);
printf("%d",len);
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
Answer: b
Explanation: To find the length of the linked list, the program iterates over the linked list once. So, the time
complexity of the above code is O(n).
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int val;
struct Node *next;
}*head;
int recursive_get_len(struct Node *current_node)
{
if(current_node == 0)
return 0;
return 1 + recursive_get_len(current_node->next);
}
int main()
{
int arr[10] = {-1,2,3,-3,4,5}, n = 6, i;
struct Node *temp, *newNode;
head = (struct Node*)malloc(sizeof(struct Node));
head->next = 0;
temp = head;
for(i=0; i<n; i++)
{
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->val = arr[i];
newNode->next = 0;
temp->next = newNode;
temp = temp->next;
}
int len = recursive_get_len(head->next);
printf("%d",len);
return 0;
}
a) 5
b) 6
c) 7
d) 8
Answer: b
Explanation: The program prints the length of the linked list, which is 6.
10. How many times is the function recursive_get_len() called when the following code is executed?
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int val;
struct Node *next;
}*head;
int recursive_get_len(struct Node *current_node)
{
if(current_node == 0)
return 0;
return 1 + recursive_get_len(current_node->next);
}
int main()
{
int arr[10] = {-1,2,3,-3,4,5}, n = 6, i;
struct Node *temp, *newNode;
head = (struct Node*)malloc(sizeof(struct Node));
head->next = 0;
temp = head;
for(i=0; i<n; i++)
{
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->val = arr[i];
newNode->next = 0;
temp->next = newNode;
temp = temp->next;
}
int len = recursive_get_len(head->next);
printf("%d",len);
return 0;
}
a) 5
b) 6
c) 7
d) 8
Answer: c
Explanation: The function is called “len + 1” times. Since the length of the linked list in the above code is 6,
the function is calle
1. Consider the following iterative implementation to find the length of the string:
#include<stdio.h>
int get_len(char *s)
{
int len = 0;
while(________)
len++;
return len;
}
int main()
{
char *s = "harsh";
int len = get_len(s);
printf("%d",len);
return 0;
}
Which of the following lines should be inserted to complete the above code?
a) s[len-1] != 0
b) s[len+1] != 0
c) s[len] != ‘\0’
d) s[len] == ‘\0’
Answer: c
Explanation: The line “s[len] != ‘\0′” should be inserted to complete the above code.
#include<stdio.h>
int get_len(char *s)
{
int len = 0;
while(s[len] != '\0')
len++;
return len;
}
int main()
{
char *s = "lengthofstring";
int len = get_len(s);
printf("%d",len);
return 0;
}
a) 14
b) 0
c) Compile time error
d) Runtime error
Answer: a
Explanation: The program prints the length of the string “lengthofstring”, which is 14.
3. What is the time complexity of the following code used to find the length of the string?
advertisement
#include<stdio.h>
int get_len(char *s)
{
int len = 0;
while(s[len] != '\0')
len++;
return len;
}
int main()
{
char *s = "lengthofstring";
int len = get_len(s);
printf("%d",len);
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(logn)
Answer: b
Explanation: The time complexity of the code used to find the length of the string is O(n).
#include<stdio.h>
int get_len(char *s)
{
int len = 0;
while(s[len] != '\0')
len++;
return len;
}
int main()
{
char *s = "";
int len = get_len(s);
printf("%d",len);
return 0;
}
a) 0
b) 1
c) Runtime error
d) Garbage value
Answer: a
Explanation: The program prints the length of an empty string, which is 0.
5. Which of the following can be the base case for the recursive implementation used to find the length of a
string?
#include<stdio.h>
int get_len(char *s)
{
int len = 0;
while(s[len] != '\0')
len++;
return len;
}
int main()
{
char *s = "";
int len = get_len(s);
printf("%d",len);
return 0;
}
a) if(string[len] == 1) return 1
b) if(string[len+1] == 1) return 1
c) if(string[len] == ‘\0’) return 0
d) if(string[len] == ‘\0’) return 1
Answer: c
Explanation: “if(string[len] == ‘\0’) return 0” can be used as base case in the recursive implementation used
to find the length of the string.
6. Consider the following recursive implementation used to find the length of a string:
#include<stdio.h>
int recursive_get_len(char *s, int len)
{
if(s[len] == 0)
return 0;
return ________;
}
int main()
{
char *s = "abcdef";
int len = recursive_get_len(s,0);
printf("%d",len);
return 0;
}
Which of the following lines should be inserted to complete the above code?
a) 1
b) len
c) recursive_get_len(s, len+1)
d) 1 + recursive_get_len(s, len+1)
Answer: d
Explanation: The line “1 + recursive_get_len(s, len+1)” should be inserted to complete the code.
#include<stdio.h>
int recursive_get_len(char *s, int len)
{
if(s[len] == 0)
return 0;
return 1 + recursive_get_len(s, len+1);
}
int main()
{
char *s = "abcdef";
int len = recursive_get_len(s,0);
printf("%d",len);
return 0;
}
a) 5
b) 6
c) 7
d) 8
Answer: b
Explanation: The above code prints the length of the string “abcdef”, which is 6.
8. What is the time complexity of the following recursive implementation used to find the length of the
string?
#include<stdio.h>
int recursive_get_len(char *s, int len)
{
if(s[len] == 0)
return 0;
return 1 + recursive_get_len(s, len+1);
}
int main()
{
char *s = "abcdef";
int len = recursive_get_len(s,0);
printf("%d",len);
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
Answer: b
Explanation: The time complexity of the above recursive implementation used to find the length of the string
is O(n).
9. How many times is the function recursive_get_len() called when the following code is executed?
#include<stdio.h>
int recursive_get_len(char *s, int len)
{
if(s[len] == 0)
return 0;
return 1 + recursive_get_len(s, len+1);
}
int main()
{
char *s = "adghjkl";
int len = recursive_get_len(s,0);
printf("%d",len);
return 0;
}
a) 6
b) 7
c) 8
d) 9
Answer: c
Explanation: The function recursive_get_len() is called 8 times when the above code is executed.
#include<stdio.h>
int recursive_get_len(char *s, int len)
{
if(s[len] == 0)
return 0;
return 1 + recursive_get_len(s, len+1);
}
int main()
{
char *s = "123-1-2-3";
int len = recursive_get_len(s,0);
printf("%d",len);
return 0;
}
a) 3
b) 6
c) 9
d) 10
Answer: c
Explanation: The above pr
1. If Matrix A is of order X*Y and Matrix B is of order M*N, then what is the order of the Matrix A*B
given that Y=M?
a) Y*N
b) X*M
c) X*N
d) Y*M
Answer: c
Explanation: The Matrix A*B is of order X*N as it is given that Y=M i.e. number of columns in Matrix A is
equal to total number of rows in matrix B. So the Matrix A*B must have X number of rows and N number
of columns.
2. How many recursive calls are there in Recursive matrix multiplication through Simple Divide and
Conquer Method?
a) 2
b) 6
c) 9
d) 8
Answer: d
Explanation: For the multiplication two square matrix recursively using Simple Divide and Conquer
Method, there are 8 recursive calls performed for high time complexity.
3. What is the time complexity of matrix multiplied recursively by Divide and Conquer Method?
a) O(n)
b) O(n2)
c) O(n3)
d) O(n!)
Answer: c
Explanation: The time complexity of recursive multiplication of two square matrices by the Divide and
Conquer method is found to be O(n3) since there are total of 8 recursive calls.
Answer: a
Explanation: The time complexity of recursive multiplication of two square matrices by Strassen’s Method
is found to be O(nlog7) since there are total 7 recursive calls.
advertisement
5. How many recursive calls are there in Recursive matrix multiplication by Strassen’s Method?
a) 5
b) 7
c) 8
d) 4
Answer: b
Explanation: For the multiplication two square matrix recursively using Strassen’s Method, there are 7
recursive calls performed for high time complexity.
6. Matrix A is of order 3*4 and Matrix B is of order 4*5. How many elements will be there in a matrix A*B
multiplied recursively.
a) 12
b) 15
c) 16
d) 20
Answer: b
Explanation: The resultant matrix will be of order 3*5 when multiplied recursively and therefore the matrix
will have 3*5=15 elements.
7. If Matrix X is of order A*B and Matrix Y is of order C*D, and B=C then the order of the Matrix X*Y is
A*D?
a) True
b) False
Answer: a
Explanation: Given that B=C, so the two matrix can be recursively multiplied. Therefore, the order of the
Matrix X*Y is A*D.
8. What is the time complexity of the fastest known matrix multiplication algorithm?
a) O(nlog7)
b) O(n2.37)
c) O(n3)
d) O(n!)
Answer: b
Explanation: The Coppersmith-Winograd algorithm multiplies the matrices in O(n2.37) time. Several
improvements have been made in the algorithm since 2010.
Answer: a
Explanation: Since The Coppersmith-Winograd algorithm multiplies the matrices in O(n2.37) time. The time
compl
Answer: c
Explanation: The recursive program to reverse stack uses memory of the order n to store function call stack.
Answer: b
Explanation: If linked list is used for implementing stack then it can be reversed without using any extra
space.
4. Which of the following is considered as the top of the stack in the linked list implementation of the stack?
a) Last node
b) First node
c) Random node
d) Middle node
Answer: b
Explanation: First node is considered as the top element when stack is implemented using linked list.
5. What is the time complexity of the program to reverse stack when linked list is used for its
implementation?
a) O(n)
b) O(n log n)
c) O(n2)
d) O(log n)
Answer: a
Explanation: As a linked list takes O(n) time for getting reversed thus linked list version of stack will also
take the same time.
6. Which of the following takes O(n) time in worst case in array implementation of stack?
a) pop
b) push
c) isEmpty
d) pop, push and isEmpty takes constant time
Answer: d
Explanation: Functions pop, push and isEmpty all are implemented in constant time in worst case.
7. What will be the time complexity of the code to reverse stack recursively?
a) O(n)
b) O(n log n)
c) O(log n)
d) O(n2)
Answer: d
Explanation: The recurrence relation for the recursive code to reverse stack will be given by-T(n)=T(n-
1)+n.This is calculated to be equal to O(n2).
advertisement
8. Which of the following functions correctly represents the recursive approach to reverse a stack?
a)
int reverse()
{
if(s.size()<0)
{
int x = s.top();
s.pop();
reverse();
BottomInsert(x);
}
}
b)
int reverse()
{
if(s.size()>=0)
{
int x = s.top();
s.pop();
reverse();
BottomInsert(x);
}
}
c)
int reverse()
{
if(s.size()>0)
{
int x = s.top();
s.pop();
reverse();
BottomInsert(x);
}
}
d)
int reverse()
{
if(s.size()>0)
{
int x = s.top();
BottomInsert(x);
s.pop();
reverse();
}
}
Answer: c
Explanation: We keep on holding the elements in call stack until we reach the bottom of the stack.Then we
insert elements at the bottom.This reverses our stack.
9. Which of the following correctly represents the function to insert elements at the bottom of stack?
a)
int BottomInsert(int x)
{
if(s.size()!=0) s.push(x);
else
{
int a = s.top();
s.pop();
BottomInsert(x);
s.push(a);
}
}
b)
int BottomInsert(int x)
{
if(s.size()==0) s.push(x);
else
{
int a = s.top();
s.pop();
s.push(a);
BottomInsert(x);
}
}
c)
int BottomInsert(int x)
{
if(s.size()==0) s.push(x);
else
{
int a = s.top();
s.pop();
BottomInsert(x);
s.push(a);
}
}
d)
int BottomInsert(int x)
{
if(s.size()==0) s.push(x);
else
{
s.pop();
int a = s.top();
BottomInsert(x);
s.push(a);
}
}
Answer: c
Explanation: We hold all the elements in the call stack until we reach the bottom of stack and then the first if
statement is executed as the stack is empty at this stage.Finally we push back all the elements held in the call
stack.
10. Which of the following code correctly represents the function to reverse stack without using recursion?
a)
#include <stack>
void reverseStack(stack<int> &input, stack<int> &extra)
{
while(input.size()!=0)
{
extra.push(input.top());
input.pop();
}
input.swap(extra);
}
b)
#include <stack>
void reverseStack(stack<int> &input, stack<int> &extra)
{
while(input.size()!=0)
{
extra.push(input.top());
input.pop();
}
extra.swap(input);
}
c)
#include <stack>
void reverseStack(stack<int> &input, stack<int> &extra)
{
while(input.size()!=0)
{
input.pop();
extra.push(input.top());
}
extra.swap(input);
}
d)
#include <stack>
void reverseStack(stack<int> &input, stack<int> &extra)
{
while(input.size()==0)
{
input.pop();
extra.push(input.top());
}
extra.swap(input);
}
Answer: b
Explanation: We are using one extra stack to reverse the given stack. First the elements of the original stack
are pushed into the other stack which creates a reversed version of the original stack. Then we swap this
stack with the original stack.
1. Which of the following sorting algorithm has best case time complexity of O(n2)?
a) bubble sort
b) selection sort
c) insertion sort
d) stupid sort
Answer: b
Explanation: Selection sort is not an adaptive sorting algorithm. It finds the index of minimum element in
each iteration even if the given array is already sorted. Thus its best case time complexity becomes O(n2).
Answer: d
Explanation: Selection sort works by obtaining least value element in each iteration and then swapping it
with the current index. So it will take n swaps under any condition which will be useful when memory write
operation is expensive.
3. What will be the recurrence relation of the code of recursive selection sort?
a) T(n) = 2T(n/2) + n
b) T(n) = 2T(n/2) + c
c) T(n) = T(n-1) + n
d) T(n) = T(n-1) + c
Answer: c
Explanation: Function to find the minimum element index takes n time.The recursive call is made to one less
element than in the previous call so the overall recurrence relation becomes T(n) = T(n-1) + n.
Answer: a
Explanation: Out of the given options selection sort is the only algorithm which is not stable. It is because
the order of identical elements in sorted output may be different from input array.
5. What will be the best case time complexity of recursive selection sort?
a) O(n)
b) O(n2)
c) O(log n)
d) O(n log n)
Answer: b
Explanation: Selection sort’s algorithm is such that it finds the index of minimum element in each iteration
even if the given array is already sorted. Thus its best case time complexity becomes O(n2).
advertisement
Answer: a
Explanation: In selection sort we need to compare elements in order to find the minimum element in each
iteration. So we can say that it uses comparisons in order to sort the array. Thus it qualifies as a comparison
based sort.
Answer: c
Explanation: The overall recurrence relation of recursive selection sort is given by T(n) = T(n-1) + n. It is
found to be equal to O(n2). It is unvaried throughout the three cases.
Answer: a
Explanation: A bidirectional variant of selection sort is called cocktail sort. It’s an algorithm which finds
both the minimum and maximum values in the array in every pass. This reduces the number of scans of the
array by a factor of 2.
9. Choose correct C++ code for recursive selection sort from the following.
a)
#include <iostream>
using namespace std;
int minIndex(int a[], int i, int j)
{
if (i == 0)
return i;
int k = minIndex(a, i + 1, j);
return (a[i] < a[k])? i : k;
}
void recursiveSelectionSort(int a[], int n, int index = 0)
{
if (index == n)
return;
int x = minIndex(a, index, n-1);
if (x == index)
{
swap(a[x], a[index]);
}
recursiveSelectionSort(a, n, index + 1);
}
int main()
{
int arr[] = {5,3,2,4,1};
int n = sizeof(arr)/sizeof(arr[0]);
recursiveSelectionSort(arr, n);
return 0;
}
b)
#include <iostream>
using namespace std;
int minIndex(int a[], int i, int j)
{
if (i == j)
return i;
int k = minIndex(a, i + 1, j);
return (a[i] < a[k])? i : k;
}
void recursiveSelectionSort(int a[], int n, int index = 0)
{
if (index == n)
return;
int x = minIndex(a, index, n-1);
if (x != index)
{
swap(a[x], a[index]);
}
recursiveSelectionSort(a, n, index + 1);
}
int main()
{
int arr[] = {5,3,2,4,1};
int n = sizeof(arr)/sizeof(arr[0]);
recursiveSelectionSort(arr, n);
return 0;
}
c)
#include <iostream>
using namespace std;
int minIndex(int a[], int i, int j)
{
if (i == j)
return i;
int k = minIndex(a, i + 1, j);
return (a[i] > a[k])? i : k;
}
void recursiveSelectionSort(int a[], int n, int index = 0)
{
if (index == n)
return;
int x = minIndex(a, index, n-1);
if (x != index)
{
swap(a[x], a[index]);
}
recursiveSelectionSort(a, n, index + 1);
}
int main()
{
int arr[] = {5,3,2,4,1};
int n = sizeof(arr)/sizeof(arr[0]);
recursiveSelectionSort(arr, n);
return 0;
}
d)
#include <iostream>
using namespace std;
int minIndex(int a[], int i, int j)
{
if (i == j)
return i;
int k = minIndex(a, i + 1, j);
return (a[i] > a[k])? i : k;
}
void recursiveSelectionSort(int a[], int n, int index = 0)
{
if (index == 0)
return;
int x = minIndex(a, index, n-1);
if (x == index)
{
swap(a[x], a[index]);
}
recursiveSelectionSort(a, n, index + 1);
}
int main()
{
int arr[] = {5,3,2,4,1};
int n = sizeof(arr)/sizeof(arr[0]);
recursiveSelectionSort(arr, n);
return 0;
}
Answer: b
Explanation: Using the function recursiveSelectionSort() we find the element that needs to be placed at the
current index. For finding the minimum element index we use another function minIndex(). After finding
the minimum element index the current element is swapped with this element in the function
recursiveSelectionSort().
10. What is the number of swaps required to sort the array arr={5,3,2,4,1} using recursive selection sort?
a) 0
b) 1
c) 2
d) 3
Answer: c
Explanatio
1. Which of the following methods can be used to find the largest and smallest element in an array?
a) Recursion
b) Iteration
c) Both recursion and iteration
d) No method is suitable
Answer: c
Explanation: Both recursion and iteration can be used to find the largest and smallest element in an array.
2. Consider the following iterative code snippet to find the largest element:
Which of the following lines should be inserted to complete the above code?
a) arr[i] > max_element
b) arr[i] < max_element
c) arr[i] == max_element
d) arr[i] != max_element
Answer: a
Explanation: The line “arr[i] > max_element” should be inserted to complete the above code snippet.
3. Consider the following code snippet to find the smallest element in an array:
Which of the following lines should be inserted to complete the above code?
a) arr[i] > min_element
b) arr[i] < min_element
c) arr[i] == min_element
d) arr[i] != min_element
Answer: b
Explanation: The line “arr[i] < min_element” should be inserted to complete the above code.
advertisement
#include<stdio.h>
int get_max_element(int *arr,int n)
{
int i, max_element = arr[0];
for(i = 1; i < n; i++)
if(arr[i] > max_element)
max_element = arr[i];
return max_element;
}
int get_min_element(int *arr, int n)
{
int i, min_element = arr[0];
for(i = 1; i < n; i++)
if(arr[i] < min_element)
min_element = arr[i];
return min_element;
}
int main()
{
int n = 7, arr[7] = {5,2,4,7,8,1,3};
int max_element = get_max_element(arr,n);
int min_element = get_min_element(arr,n);
printf("%d %d",max_element,min_element);
return 0;
}
a) 5 3
b) 3 5
c) 8 1
d) 1 8
Answer: c
Explanation: The program prints the values of the largest and the smallest elements in the array, which are 8
and 1 respectively.
#include<stdio.h>
int get_max_element(int *arr,int n)
{
int i, max_element = arr[0];
for(i = 1; i < n; i++)
if(arr[i] > max_element)
max_element = arr[i];
return max_element;
}
int get_min_element(int *arr, int n)
{
int i, min_element;
for(i = 1; i < n; i++)
if(arr[i] < min_element)
min_element = arr[i];
return min_element;
}
int main()
{
int n = 7, arr[7] = {1,1,1,0,-1,-1,-1};
int max_element = get_max_element(arr,n);
int min_element = get_min_element(arr,n);
printf("%d %d",max_element,min_element);
return 0;
}
a) 1 -1
b) -1 1
c) 1 Garbage value
d) Depends on the compiler
Answer: c
Explanation: Since the min_element variable is not initialised, some compilers will auto initialise as 0 which
produces -1 as output whereas some compilers won’t initialise automatically. In that case, the result will be a
garbage value hence the output depends on the compiler.
6. What is the time complexity of the following iterative implementation used to find the largest and
smallest element in an array?
#include<stdio.h>
int get_max_element(int *arr,int n)
{
int i, max_element = arr[0];
for(i = 1; i < n; i++)
if(arr[i] > max_element)
max_element = arr[i];
return max_element;
}
int get_min_element(int *arr, int n)
{
int i, min_element;
for(i = 1; i < n; i++)
if(arr[i] < min_element)
min_element = arr[i];
return min_element;
}
int main()
{
int n = 7, arr[7] = {1,1,1,0,-1,-1,-1};
int max_element = get_max_element(arr,n);
int min_element = get_min_element(arr,n);
printf("%d %d",max_element,min_element);
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(n/2)
Answer: b
Explanation: The time complexity of the above iterative implementation used to find the largest and the
smallest element in an array is O(n).
7. Consider the following recursive implementation to find the largest element in an array.
Which of the following lines should be inserted to complete the above code?
a) max_of_two(arr[idx], recursive_max_element(arr, len, idx))
b) recursive_max_element(arr, len, idx)
c) max_of_two(arr[idx], recursive_max_element(arr, len, idx + 1))
d) recursive_max_element(arr, len, idx + 1)
Answer: c
Explanation: The line “max_of_two(arr[idx], recursive_max_element(arr, len, idx + 1))” should be inserted
to complete the above code.
#include<stdio.h>
int max_of_two(int a, int b)
{
if(a > b)
return a;
return b;
}
int min_of_two(int a, int b)
{
if(a < b)
return a;
return b;
}
int recursive_max_element(int *arr, int len, int idx)
{
if(idx == len - 1)
return arr[idx];
return max_of_two(arr[idx], recursive_max_element(arr, len, idx + 1));
}
int recursive_min_element(int *arr, int len, int idx)
{
if(idx == len - 1)
return arr[idx];
return min_of_two(arr[idx], recursive_min_element(arr, len, idx + 1));
}
int main()
{
int n = 10, idx = 0, arr[] = {5,2,6,7,8,9,3,-1,1,10};
int max_element = recursive_max_element(arr,n,idx);
int min_element = recursive_min_element(arr,n,idx);
printf("%d %d",max_element,min_element);
return 0;
}
a) -1 10
b) 10 -1
c) 1 10
d) 10 1
Answer: b
Explanation: The program prints the values of the largest and the smallest element in the array, which are 10
and -1 respectively.
9. What is the time complexity of the following recursive implementation used to find the largest and the
smallest element in an array?
#include<stdio.h>
int max_of_two(int a, int b)
{
if(a > b)
return a;
return b;
}
int min_of_two(int a, int b)
{
if(a < b)
return a;
return b;
}
int recursive_max_element(int *arr, int len, int idx)
{
if(idx == len - 1)
return arr[idx];
return max_of_two(arr[idx], recursive_max_element(arr, len, idx + 1));
}
int recursive_min_element(int *arr, int len, int idx)
{
if(idx == len - 1)
return arr[idx];
return min_of_two(arr[idx], recursive_min_element(arr, len, idx + 1));
}
int main()
{
int n = 10, idx = 0, arr[] = {5,2,6,7,8,9,3,-1,1,10};
int max_element = recursive_max_element(arr,n,idx);
int min_element = recursive_min_element(arr,n,idx);
printf("%d %d",max_element,min_element);
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
Answer: b
Explanation: The time complexity of the above recursive implementation used to find the largest and
smallest element in an array is O(n).
10. How many times is the function recursive_min_element() called when the following code is executed?
a) 9
b) 10
c) 11
d) 12
Answer: b
Explanation: The function recursive_min_element() is called 10 times when the above code is executed.
#include<stdio.h>
int max_of_two(int a, int b)
{
if(a > b)
return a;
return b;
}
int min_of_two(int a, int b)
{
if(a < b)
return a;
return b;
}
int recursive_max_element(int *arr, int len, int idx)
{
if(idx == len - 1)
return arr[idx];
return max_of_two(arr[idx], recursive_max_element(arr, len, idx + 1));
}
int recursive_min_element(int *arr, int len, int idx)
{
if(idx == len - 1)
return arr[idx];
return min_of_two(arr[idx], recursive_min_element(arr, len, idx + 1));
}
int main()
{
int n = 5, idx = 0, arr[] = {1,1,1,1,1};
int max_element = recursive_max_element(arr,n,idx);
int min_element = recursive_min_element(arr,n,idx);
printf("%d %d",max_element,min_element);
return 0;
}
a) 1 1
b) 0 0
c) compile time error
d) runtime error
Answer: a
Explanation: The progr
1. Which of the following methods can be used to find the largest and smallest number in a linked list?
a) Recursion
b) Iteration
c) Both Recursion and iteration
d) Impossible to find the largest and smallest numbers
Answer: c
Explanation: Both recursion and iteration can be used to find the largest and smallest number in a linked list.
2. Consider the following code snippet to find the largest element in a linked list:
struct Node{
int val;
struct Node *next;
}*head;
int get_max()
{
struct Node* temp = head->next;
int max_num = temp->val;
while(______)
{
if(temp->val > max_num)
max_num = temp->val;
temp = temp->next;
}
return max_num;
}
Which of the following lines should be inserted to complete the above code?
a) temp->next != 0
b) temp != 0
c) head->next != 0
d) head != 0
Answer: b
Explanation: The line “temp != 0” should be inserted to complete the above code.
3. Consider the following code snippet to find the smallest element in a linked list:
struct Node
{
int val;
struct Node* next;
}*head;
int get_min()
{
struct Node* temp = head->next;
int min_num = temp->val;
while(temp != 0)
{
if(_________)
min_num = temp->val;
temp = temp->next;
}
return min_num;
}
Which of the following lines should be inserted to complete the above code?
a) temp > min_num
b) val > min_min
c) temp->val < min_num
d) temp->val > min_num
Answer: c
Explanation: The line “temp->val = min_num” should be inserted to complete the above code.
Join [email protected]
a) 5
b) 1
c) runtime error
d) garbage value
Answer: c
Explanation: The variable temp will always point to the first element in the linked list due to the line “temp
= head->next” in the while loop. So, it will be an infinite while loop and the program will produce a runtime
error.
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int val;
struct Node* next;
}*head;
int get_max()
{
struct Node* temp = head->next;
int max_num = temp->val;
while(temp != 0)
{
if(temp->val > max_num)
max_num = temp->val;
temp = temp->next;
}
return max_num;
}
int get_min()
{
struct Node* temp = head->next;
int min_num = temp->val;
while(temp != 0)
{
if(temp->val < min_num)
min_num = temp->val;
temp = temp->next;
}
return min_num;
}
int main()
{
int i, n = 9, arr[9] ={8,3,3,4,5,2,5,6,7};
struct Node *temp, *newNode;
head = (struct Node*)malloc(sizeof(struct Node));
head -> next =0;
temp = head;
for(i=0;i<n;i++)
{
newNode =(struct Node*)malloc(sizeof(struct Node));
newNode->next = 0;
newNode->val = arr[i];
temp->next =newNode;
temp = temp->next;
}
int max_num = get_max();
int min_num = get_min();
printf("%d %d",max_num,min_num);
return 0;
}
a) 2 2
b) 8 8
c) 2 8
d) 8 2
Answer: d
Explanation: The program prints the largest and smallest elements in the linked list, which are 8 and 2
respectively.
6. What is the time complexity of the following iterative code used to find the smallest and largest element
in a linked list?
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int val;
struct Node* next;
}*head;
int get_max()
{
struct Node* temp = head->next;
int max_num = temp->val;
while(temp != 0)
{
if(temp->val > max_num)
max_num = temp->val;
temp = temp->next;
}
return max_num;
}
int get_min()
{
struct Node* temp = head->next;
int min_num = temp->val;
while(temp != 0)
{
if(temp->val < min_num)
min_num = temp->val;
temp = temp->next;
}
return min_num;
}
int main()
{
int i, n = 9, arr[9] ={8,3,3,4,5,2,5,6,7};
struct Node *temp, *newNode;
head = (struct Node*)malloc(sizeof(struct Node));
head -> next =0;
temp = head;
for(i=0;i<n;i++)
{
newNode =(struct Node*)malloc(sizeof(struct Node));
newNode->next = 0;
newNode->val = arr[i];
temp->next =newNode;
temp = temp->next;
}
int max_num = get_max();
int min_num = get_min();
printf("%d %d",max_num,min_num);
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
Answer: b
Explanation: The time complexity of the above iterative code used to find the largest and smallest element in
a linked list is O(n).
7. Consider the following recursive implementation to find the largest element in a linked list:
struct Node
{
int val;
struct Node* next;
}*head;
int max_of_two(int a, int b)
{
if(a > b)
return a;
return b;
}
int recursive_get_max(struct Node* temp)
{
if(temp->next == 0)
return temp->val;
return max_of_two(______, _______);
}
Which of the following arguments should be passed to the function max_of two() to complete the above
code?
a) temp->val,recursive_get_max(temp->next)
b) temp, temp->next
c) temp->val, temp->next->val
d) temp->next->val, temp
Answer: a
Explanation: The arguments {temp->val,recursive_get_max(temp->next)} should be passed to the function
max_of_two() to complete the above code.
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int val;
struct Node* next;
}*head;
int max_of_two(int a, int b)
{
if(a > b)
return a;
return b;
}
int recursive_get_max(struct Node* temp)
{
if(temp->next == 0)
return temp->val;
return max_of_two(temp->val,recursive_get_max(temp->next));
}
int min_of_two(int a, int b)
{
if(a < b)
return a;
return b;
}
int recursive_get_min(struct Node* temp)
{
if(temp->next == 0)
return temp->val;
return min_of_two(temp->val,recursive_get_min(temp->next));
}
int main()
{
int n = 9, arr[9] ={1,3,2,4,5,0,5,6,7},i;
struct Node *temp, *newNode;
head = (struct Node*)malloc(sizeof(struct Node));
head -> next =0;
temp = head;
for(i=0;i<n;i++)
{
newNode =(struct Node*)malloc(sizeof(struct Node));
newNode->next = 0;
newNode->val = arr[i];
temp->next =newNode;
temp = temp->next;
}
int max_num = recursive_get_max(head->next);
int min_num = recursive_get_min(head->next);
printf("%d %d",max_num,min_num);
return 0;
}
a) 7 1
b) 0 7
c) 7 0
d) 1 1
Answer: c
Explanation: The program prints the largest and the smallest elements in the linked list, which are 7 and 0
respectively.
9. What is the time complexity of the recursive implementation used to find the largest and smallest element
in a linked list?
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int val;
struct Node* next;
}*head;
int max_of_two(int a, int b)
{
if(a > b)
return a;
return b;
}
int recursive_get_max(struct Node* temp)
{
if(temp->next == 0)
return temp->val;
return max_of_two(temp->val,recursive_get_max(temp->next));
}
int min_of_two(int a, int b)
{
if(a < b)
return a;
return b;
}
int recursive_get_min(struct Node* temp)
{
if(temp->next == 0)
return temp->val;
return min_of_two(temp->val,recursive_get_min(temp->next));
}
int main()
{
int n = 9, arr[9] ={1,3,2,4,5,0,5,6,7},i;
struct Node *temp, *newNode;
head = (struct Node*)malloc(sizeof(struct Node));
head -> next =0;
temp = head;
for(i=0;i<n;i++)
{
newNode =(struct Node*)malloc(sizeof(struct Node));
newNode->next = 0;
newNode->val = arr[i];
temp->next =newNode;
temp = temp->next;
}
int max_num = recursive_get_max(head->next);
int min_num = recursive_get_min(head->next);
printf("%d %d",max_num,min_num);
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
Answer: b
Explanation: The time complexity of the above recursive implementation used to find the largest and
smallest element in linked list is O(n).
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int val;
struct Node* next;
}*head;
int min_of_two(int a, int b)
{
if(a < b)
return a;
return b;
}
int recursive_get_min(struct Node* temp)
{
if(temp->next == 0)
return temp->val;
return min_of_two(temp->val,recursive_get_min(temp->next));
}
int main()
{
int n = 5, arr[5] ={1,1,1,1,1},i;
struct Node *temp, *newNode;
head = (struct Node*)malloc(sizeof(struct Node));
head -> next =0;
temp = head;
for(i=0;i<n;i++)
{
newNode =(struct Node*)malloc(sizeof(struct Node));
newNode->next = 0;
newNode->val = arr[i];
temp->next =newNode;
temp = temp->next;
}
int min_num = recursive_get_min(head->next);
printf("%d",min_num);
return 0;
}
a) 1
b) 0
c) compile time error
d) runtime error
Answer: a
Explanation: The program prints the smallest element in the linked list, which is 1.
11. How many times will the function recursive_get_min() be called when the following code is executed?
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int val;
struct Node* next;
}*head;
int min_of_two(int a, int b)
{
if(a < b)
return a;
return b;
}
int recursive_get_min(struct Node* temp)
{
if(temp->next == 0)
return temp->val;
return min_of_two(temp->val,recursive_get_min(temp->next));
}
int main()
{
int n = 5, arr[5] ={1,1,1,1,1},i;
struct Node *temp, *newNode;
head = (struct Node*)malloc(sizeof(struct Node));
head -> next =0;
temp = head;
for(i=0;i<n;i++)
{
newNode =(struct Node*)malloc(sizeof(struct Node));
newNode->next = 0;
newNode->val = arr[i];
temp->next =newNode;
temp = temp->next;
}
int min_num = recursive_get_min(head->next);
printf("%d",min_num);
return 0;
}
a) 4
b) 5
c) 6
d) 7
Answer: b
Explanation: The function recursive_get_min() will be called 5 times when the above code is executed.
1. Which of the following techniques can be used to search an element in an unsorted array?
a) Iterative linear search
b) Recursive binary search
c) Iterative binary search
d) Normal binary search
Answer: a
Explanation: Iterative linear search can be used to search an element in an unsorted array.
Note: Binary search can be used only when the array is sorted.
Answer: d
Explanation: Iterative linear search, Recursive linear search and Recursive binary search can be applied to
search for an element in the above given array.
#include<stdio.h>
int search_num(int *arr, int num, int len)
{
int i;
for(i = 0; i < len; i++)
if(arr[i] == num)
return i;
return -1;
}
int main()
{
int arr[5] ={1,2,3,4,5},num=3,len = 5;
int indx = search_num(arr,num,len);
printf("Index of %d is %d",num,indx);
return 0;
}
a) Search and returns the index of all the occurrences of the number that is searched
b) Search and returns the index of the first occurrence of the number that is searched
c) Search and returns of the last occurrence of the number that is searched
d) Returns the searched element from the given array
Answer: b
Explanation: The code finds the index of the first occurrence of the number that is searched.
advertisement
#include<stdio.h>
int search_num(int *arr, int num, int len)
{
int i;
for(i = 0; i < len; i++)
if(arr[i] == num)
return i;
return -1;
}
int main()
{
int arr[5] ={1,3,3,3,5},num=3,len = 5;
int indx = search_num(arr,num,len);
printf("Index of %d is %d",num,indx);
return 0;
}
a) Index of 3 is 0
b) Index of 3 is 1
c) Index of 3 is 2
d) Index of 3 is 3
Answer: b
Explanation: The program prints the index of the first occurrence of 3, which is 1.
5. What is the time complexity of the following code used to search an element in an array?
#include<stdio.h>
int search_num(int *arr, int num, int len)
{
int i;
for(i = 0; i < len; i++)
if(arr[i] == num)
return i;
return -1;
}
int main()
{
int arr[5] ={1,3,3,3,5},num=3,len = 5;
int indx = search_num(arr,num,len);
printf("Index of %d is %d",num,indx);
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
Answer: b
Explanation: The time complexity of the above code used to search an element in an array is O(n).
#include<stdio.h>
int recursive_search_num(int *arr, int num, int idx, int len)
{
if(idx == len)
return -1;
if(arr[idx] == num)
return idx;
return __________;
}
int main()
{
int arr[5] ={1,3,3,3,5},num=2,len = 5;
int indx = recursive_search_num(arr,num,0,len);
printf("Index of %d is %d",num,indx);
return 0;
}
Which of the following recursive calls should be added to complete the above code?
a) recursive_search_num(arr, num+1, idx, len);
b) recursive_search_num(arr, num, idx, len);
c) recursive_search_num(arr, num, idx+1, len);
d) recursive_search_num(arr, num+1, idx+1, len);
Answer: c
Explanation: The recursive call “recursive_search_num(arr, num, idx+1, len)” should be added to complete
the above code.
#include<stdio.h>
int recursive_search_num(int *arr, int num, int idx, int len)
{
if(idx == len)
return -1;
if(arr[idx] == num)
return idx;
return recursive_search_num(arr, num, idx+1, len);
}
int main()
{
int arr[8] ={1,2,3,3,3,5,6,7},num=5,len = 8;
int indx = recursive_search_num(arr,num,0,len);
printf("Index of %d is %d",num,indx);
return 0;
}
a) Index of 5 is 5
b) Index of 5 is 6
c) Index of 5 is 7
d) Index of 5 is 8
Answer: a
Explanation: The program prints the index of 5, which is 5.
8. How many times is the function recursive_search_num() called when the following code is executed?
#include<stdio.h>
int recursive_search_num(int *arr, int num, int idx, int len)
{
if(idx == len)
return -1;
if(arr[idx] == num)
return idx;
return recursive_search_num(arr, num, idx+1, len);
}
int main()
{
int arr[8] ={1,2,3,3,3,5,6,7},num=5,len = 8;
int indx = recursive_search_num(arr,num,0,len);
printf("Index of %d is %d",num,indx);
return 0;
}
a) 5
b) 6
c) 7
d) 8
Answer: b
Explanation: The function recursive_search_num() is called 6 times when the above code is executed.
9. What is the time complexity of the following recursive implementation of linear search?
#include<stdio.h>
int recursive_search_num(int *arr, int num, int idx, int len)
{
if(idx == len)
return -1;
if(arr[idx] == num)
return idx;
return recursive_search_num(arr, num, idx+1, len);
}
int main()
{
int arr[8] ={1,2,3,3,3,5,6,7},num=5,len = 8;
int indx = recursive_search_num(arr,num,0,len);
printf("Index of %d is %d",num,indx);
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
Answer: b
Explanation: The time com
#include<stdio.h>
int recursive_search_num(int *arr, int num, int idx, int len)
{
if(idx == len)
return -1;
if(arr[idx] == num)
return idx;
return recursive_search_num(arr, num, idx+1, len);
}
int main()
{
int arr[8] ={-11,2,-3,0,3,5,-6,7},num = -2,len = 8;
int indx = recursive_search_num(arr,num,0,len);
printf("Index of %d is %d",num,indx);
return 0;
}
a) Index of -2 is 1
b) Index of -2 is 0
c) Index of -2 is -1
d) None of the mentioned
Answer: c
Explanation: The program prints the index of the first occurrence of -2. Since, -2 doesn’t exist in the array,
the program prints -1.
Answer: c
Explanation: The above code counts the number of occurrences of the number 0.
advertisement
#include<stdio.h>
int recursive_binary_search(int *arr, int num, int lo, int hi)
{
if(lo > hi)
return -1;
int mid = (lo + hi)/2;
if(arr[mid] == num)
return mid;
else if(arr[mid] < num)
__________;
else
hi = mid - 1;
return recursive_binary_search(arr, num, lo, hi);
}
int main()
{
int arr[8] ={0,0,0,0,3,5,6,7},num = 7,len = 8;
int indx = recursive_binary_search(arr,num,0,len-1);
printf("Index of %d is %d",num,indx);
return 0;
}
Which of the following lines should be added to complete the above code?
a) hi = mid – 1
b) mid = (lo + hi)/2
c) mid = lo – 1
d) lo = mid + 1
Answer: d
Explanation: The line “lo = mid + 1” should be added to complete the above code.
4. What is the output of the following code?
#include<stdio.h>
int recursive_binary_search(int *arr, int num, int lo, int hi)
{
if(lo > hi)
return -1;
int mid = (lo + hi)/2;
if(arr[mid] == num)
return mid;
else if(arr[mid] < num)
lo = mid + 1;
else
hi = mid - 1;
return recursive_binary_search(arr, num, lo, hi);
}
int main()
{
int arr[8] = {1,2,3,4,5,6,7,8},num = 7,len = 8;
int indx = recursive_binary_search(arr,num,0,len-1);
printf("Index of %d is %d",num,indx);
return 0;
}
a) Index of 7 is 4
b) Index of 7 is 5
c) Index of 7 is 6
d) Index of 7 is 7
Answer: c
Explanation: The program prints the index of number 7, which is 6.
#include<stdio.h>
int recursive_binary_search(int *arr, int num, int lo, int hi)
{
if(lo > hi)
return -1;
int mid = (lo + hi)/2;
if(arr[mid] == num)
return mid;
else if(arr[mid] < num)
lo = mid + 1;
else
hi = mid - 1;
return recursive_binary_search(arr, num, lo, hi);
}
int main()
{
int arr[8] = {0,0,0,0,3,5,6,7},num = 0,len = 8;
int indx = recursive_binary_search(arr,num,0,len-1);
printf("Index of %d is %d",num,indx);
return 0;
}
a) Index of 0 is 0
b) Index of 0 is 1
c) Index of 0 is 2
d) Index of 0 is 3
Answer: d
Explanation: In this case, when the function recursive_binary_search() is called for the first time we have: lo
= 0 and hi = 7. So, the value of mid is:
mid = (lo + hi)/2 = (0 + 7)/2 = 3. Since, arr[mid] = arr[3] = 0, the function returns the value of mid, which is
3.
6. What is the time complexity of the above recursive implementation of binary search?
a) O(n)
b) O(2n)
c) O(logn)
d) O(n!)
Answer: c
Explanation: The time complexity of the above recursive implementation of binary search is O(logn).
7. In which of the below cases will the following code produce a wrong output?
Answer: c
Explanation: Since the array {5,4,3,2,1} is sorted in descending order, it will produce a wrong output.
8. How many times is the function recursive_binary_search() called when the following code is executed?
#include<stdio.h>
int recursive_binary_search(int *arr, int num, int lo, int hi)
{
if(lo > hi)
return -1;
int mid = (lo + hi)/2;
if(arr[mid] == num)
return mid;
else if(arr[mid] < num)
lo = mid + 1;
else
hi = mid - 1;
return recursive_binary_search(arr, num, lo, hi);
}
int main()
{
int arr[5] = {1,2,3,4,5},num = 1,len = 5;
int indx = recursive_binary_search(arr,num,0,len-1);
printf("Index of %d is %d",num,indx);
return 0;
}
a) 0
b) 1
c) 2
d) 3
Answer: c
Explanation: The function recursive_binary_search() is called 2 times, when the above code is executed.
#include<stdio.h>
int recursive_binary_search(int *arr, int num, int lo, int hi)
{
if(lo > hi)
return -1;
int mid = (lo + hi)/2;
if(arr[mid] == num)
return mid;
else if(arr[mid] < num)
lo = mid + 1;
else
hi = mid - 1;
return recursive_binary_search(arr, num, lo, hi);
}
int main()
{
int arr[5] = {5,4,3,2,1},num = 1,len = 5;
int indx = recursive_binary_search(arr,num,0,len-1);
printf("Index of %d is %d",num,indx);
return 0;
}
a) Index of 1 is 4
b) Index of 1 is 5
c) Index of 1 is -1
d) Index of 1 is 0
Answer: c
Explanation: Since the array is sorted in descending order, the above implementation of binary search will
not work for the given array.
1. Which of the following methods can be used to search an element in a linked list?
a) Iterative linear search
b) Iterative binary search
c) Recursive binary search
d) Normal binary search
Answer: a
Explanation: Iterative linear search can be used to search an element in a linked list. Binary search can be
used only when the list is sorted.
Which of the following lines should be inserted to complete the above code?
a) temp = next
b) temp->next = temp
c) temp = temp->next
d) return 0
Answer: c
Explanation: The line “temp = temp->next” should be inserted to complete the above code.
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int val;
struct Node* next;
}*head;
int linear_search(int value)
{
struct Node *temp = head->next;
while(temp != 0)
{
if(temp->val == value)
return 1;
temp = temp->next;
}
return 0;
}
int main()
{
int arr[5] = {1,2,3,4,5};
int n = 5,i;
head = (struct Node*)malloc(sizeof(struct Node));
head->next = 0;
struct Node *temp;
temp = head;
for(i=0; i<n; i++)
{
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->next = 0;
newNode->val = arr[i];
temp->next = newNode;
temp = temp->next;
}
int ans = linear_search(60);
if(ans == 1)
printf("Found");
else
printf("Not found");
return 0;
}
Answer: c
Explanation: The above code checks if a number is present in a linked list.
advertisement
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int val;
struct Node* next;
}*head;
int linear_search(int value)
{
struct Node *temp = head->next;
while(temp != 0)
{
if(temp->val == value)
return 1;
temp = temp->next;
}
return 0;
}
int main()
{
int arr[5] = {1,2,3,4,5};
int n = 5,i;
head = (struct Node*)malloc(sizeof(struct Node));
head->next = 0;
struct Node *temp;
temp = head;
for(i=0; i<n; i++)
{
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->next = 0;
newNode->val = arr[i];
temp->next = newNode;
temp = temp->next;
}
int ans = linear_search(-1);
if(ans == 1)
printf("Found");
else
printf("Not found");
return 0;
}
a) Found
b) Not found
c) Compile time error
d) Runtime error
Answer: b
Explanation: Since the number -1 is not present in the linked list, the program prints not found.
5. What is the time complexity of the following implementation of linear search on a linked list?
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int val;
struct Node* next;
}*head;
int linear_search(int value)
{
struct Node *temp = head->next;
while(temp != 0)
{
if(temp->val == value)
return 1;
temp = temp->next;
}
return 0;
}
int main()
{
int arr[5] = {1,2,3,4,5};
int n = 5,i;
head = (struct Node*)malloc(sizeof(struct Node));
head->next = 0;
struct Node *temp;
temp = head;
for(i=0; i<n; i++)
{
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->next = 0;
newNode->val = arr[i];
temp->next = newNode;
temp = temp->next;
}
int ans = linear_search(-1);
if(ans == 1)
printf("Found");
else
printf("Not found");
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
Answer: b
Explanation: The time complexity of the above implementation of linear search on a linked list is O(n).
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int val;
struct Node* next;
}*head;
int linear_search(int value)
{
struct Node *temp = head->next;
while(temp -> next != 0)
{
if(temp->val == value)
return 1;
temp = temp->next;
}
return 0;
}
int main()
{
int arr[6] = {1,2,3,4,5,6};
int n = 6,i;
head = (struct Node*)malloc(sizeof(struct Node));
head->next = 0;
struct Node *temp;
temp = head;
for(i=0; i<n; i++)
{
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->next = 0;
newNode->val = arr[i];
temp->next = newNode;
temp = temp->next;
}
int ans = linear_search(60);
if(ans == 1)
printf("Found");
else
printf("Not found");
return 0;
}
a) Found
b) Not found
c) Compile time error
d) Runtime error
Answer: b
Explanation: The condition in the while loop “temp->next == 0”, checks if the current element is the last
element. If the current element is the last element, the value of the current element is not compared with the
value to be searched. So, even though the number 6 is present in the linked list, it will print not found.
Answer: a
Explanation: Since linked list doesn’t allow random access, binary search cannot be applied on a sorted
linked list in O(Logn) time.
8. What will be time complexity when binary search is applied on a linked list?
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
Answer: b
Explanation: The time complexity will be O(n) when binary search is applied on a linked list.
struct Node
{
int val;
struct Node* next;
}*head;
int linear_search(struct Node *temp,int value)
{
if(temp == 0)
return 0;
if(temp->val == value)
return 1;
return _________;
}
Which of the following lines should be inserted to complete the above code?
a) 1
b) 0
c) linear_search(temp, value)
d) linear_search(temp->next, value)
Answer: d
Explanation: The line “linear_search(temp->next, value)”, should be inserted to complete the above code.
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int val;
struct Node* next;
}*head;
int linear_search(struct Node *temp,int value)
{
if(temp == 0)
return 0;
if(temp->val == value)
return 1;
return linear_search(temp->next, value);
}
int main()
{
int arr[6] = {1,2,3,4,5,6};
int n = 6,i;
head = (struct Node*)malloc(sizeof(struct Node));
head->next = 0;
struct Node *temp;
temp = head;
for(i=0; i<n; i++)
{
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->next = 0;
newNode->val = arr[i];
temp->next = newNode;
temp = temp->next;
}
int ans = linear_search(head->next,6);
if(ans == 1)
printf("Found");
else
printf("Not found");
return 0;
}
a) Found
b) Not found
c) Compile time error
d) Runtime error
Answer: a
Explanation: Since the element 6 is present in the linked list, the program prints “Found”.
11. How many times is the function linear_search() called when the following code is executed?
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int val;
struct Node* next;
}*head;
int linear_search(struct Node *temp,int value)
{
if(temp == 0)
return 0;
if(temp->val == value)
return 1;
return linear_search(temp->next, value);
}
int main()
{
int arr[6] = {1,2,3,4,5,6};
int n = 6,i;
head = (struct Node*)malloc(sizeof(struct Node));
head->next = 0;
struct Node *temp;
temp = head;
for(i=0; i<n; i++)
{
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->next = 0;
newNode->val = arr[i];
temp->next = newNode;
temp = temp->next;
}
int ans = linear_search(head->next,6);
if(ans == 1)
printf("Found");
else
printf("Not found");
return 0;
}
a) 5
b) 6
c) 7
d) 8
Answer: b
Explanation: The function linear_search() is called 6 times when the above code is executed.
12. What is the time complexity of the following recursive implementation of linear search?
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int val;
struct Node* next;
}*head;
int linear_search(struct Node *temp,int value)
{
if(temp == 0)
return 0;
if(temp->val == value)
return 1;
return linear_search(temp->next, value);
}
int main()
{
int arr[6] = {1,2,3,4,5,6};
int n = 6,i;
head = (struct Node*)malloc(sizeof(struct Node));
head->next = 0;
struct Node *temp;
temp = head;
for(i=0; i<n; i++)
{
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->next = 0;
newNode->val = arr[i];
temp->next = newNode;
temp = temp->next;
}
int ans = linear_search(head->next,6);
if(ans == 1)
printf("Found");
else
printf("Not found");
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
Answer: b
Explanat
#include<stdio.h>
int func(int x, int y)
{
if (y == 0)
return 1;
else if (y%2 == 0)
return func(x, y/2)*func(x, y/2);
else
return x*func(x, y/2)*func(x, y/2);
}
int main()
{
int x = 2;
int y = 3;
printf("%d", func(x, y));
return 0;
}
a) 9
b) 6
c) 8
d) 5
Answer: c
Explanation: The given program calculates the value of x raised to power y. Thus 23 = 8.
2. What will be the time complexity of the following code which raises an integer x to the power y?
#include<stdio.h>
int power(int x, int y)
{
if (y == 0)
return 1;
else if (y%2 == 0)
return power(x, y/2)*power(x, y/2);
else
return x*power(x, y/2)*power(x, y/2);
}
int main()
{
int x = 2;
int y = 3;
printf("%d", power(x, y));
return 0;
}
a) O(n)
b) O(log n)
c) O(n log n)
d) O(n2)
Answer: a
Explanation: The recurrence relation for the above code is given by T(n)=2T(n/2)+c. By using master
theorem we can calculate the result for this relation. It is found to be equal to O(n).
advertisement
#include<stdio.h>
int power(int x, int y)
{
if (y == 0)
return 1;
else if (y%2 == 0)
return power(x, y/2)*power(x, y/2);
else
return x*power(x, y/2)*power(x, y/2);
}
int main()
{
int x = 2;
int y = 3;
printf("%d", power(x, y));
return 0;
}
a) O(1)
b) O(n)
c) O(log n)
d) O(n log n)
Answer: a
Explanation: The space complexity of the given code will be equal to O(1) as it uses only constant space in
the memory.
4. Recursive program to raise an integer x to power y uses which of the following algorithm?
a) Dynamic programming
b) Backtracking
c) Divide and conquer
d) Greedy algorithm
Answer: c
Explanation: The recursive approach uses divide and conquer algorithm as we break the problem into
smaller parts and then solve the smaller parts and finally combine their results to get the overall solution.
Answer: d
Explanation: We can optimize the code for finding power of a number by calculating x raised to power y/2
only once and using it depending on whether y is even or odd.
#include<stdio.h>
int power(int x, int y)
{
int temp;
if( y == 0)
return 1;
temp = power(x, y/2);
if (y%2 == 0)
return temp*temp;
else
return x*temp*temp;
}
int main()
{
int x = 2;
int y = 3;
printf("%d", power(x, y));
return 0;
}
a) O(1)
b) O(n)
c) O(log n)
d) O(n log n)
Answer: c
Explanation: The given code is the optimized version for finding the power of a number. It forms a
recurrence relation given by T(n)=T(n/2)+c which can be solved using master theorem. It is calculated to be
equal to O(log n).
7. What is the advantage of iterative code for finding power of number over recursive code?
a) Iterative code requires less time
b) Iterative code requires less space
c) Iterative code is more compiler friendly
d) It has no advantage
Answer: b
Explanation: Both iterative and recursive approach can be implemented in log n time but the recursive code
requires memory in call stack which makes it less preferable.
8. Which of the following correctly implements iterative code for finding power of a number?
a)
#include <stdio.h>
int power(int x, int y)
{
int res = 1;
while (y > 0)
{
if (y & 1)
res = res * x;
y = y >> 1;
x = x * x;
}
return res;
}
int main()
{
int x = 3;
unsigned int y = 5;
printf("%d", power(x, y));
return 0;
}
b)
#include <stdio.h>
int power(int x, int y)
{
int res = 1;
while (y > 0)
{
if (y && 1)
res = res * x;
y = y >> 1;
x = x * x;
}
return res;
}
int main()
{
int x = 3;
unsigned int y = 5;
printf("%d", power(x, y));
return 0;
}
c)
#include <stdio.h>
int power(int x, int y)
{
int res = 1;
while (y > 0)
{
if (y && 1)
res = x * x;
y = y >> 1;
x = x * y;
}
return res;
}
int main()
{
int x = 3;
unsigned int y = 5;
printf("%d", power(x, y));
return 0;
}
d)
#include <stdio.h>
int power(int x, int y)
{
int res = 1;
while (y > 0)
{
if (y & 1)
res = x * x;
y = y >> 1;
x = x * y;
}
return res;
}
int main()
{
int x = 3;
unsigned int y = 5;
printf("%d", power(x, y));
return 0;
}
Answer: a
Explanation: It represents the iterative version of required code. It has a time and space complexity of O(log
n) and O(1) respectively.
Answer: b
Explanation: The recursive code requires memory in call stack which makes it less preferable as compared
to iterative approach.
a) Error
b) 1/4
c) 4
d) 0.25
Answer: d
Explanation: The given code is capable of handling negative powers too. Thus, the output will be 2-2 = 0.25.
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)
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
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
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.
advertisement
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: The first recursive call moves n-1 disks from a to b using c. Then we move a disk from a to c.
Finally the second recursive call moves n-1 disks from b to c using a.
8. Recursive solution of tower of hanoi problem is an example of which of the following algorithm?
a) Dynamic programming
b) Backtracking
c) Greedy algorithm
d) Divide and conquer
Answer: d
Explanation: The recursive approach uses divide and conquer algorithm as we break the problem into
smaller parts and then solve the smaller parts and finally combine their results to get the overall solution.
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
Answer: b
Explanation: Number of moves = 24-1=16-1=15
Time for 1 m
Answer: a
Explanation: Master’s theorem is a direct method for solving recurrences. We can solve any recurrence that
falls under any one of the three cases of master’s theorem.
Answer: b
Explanation: There are primarily 3 cases under master’s theorem. We can solve any recurrence that falls
under any one of these three cases.
3. What is the result of the recurrences which fall under first case of Master’s theorem (let the recurrence be
given by T(n)=aT(n/b)+f(n) and f(n)=nc?
a) T(n) = O(n^logba)
b) T(n) = O(nc log n)
c) T(n) = O(f(n))
d) T(n) = O(n2)
Answer: a
Explanation: In first case of master’s theorem the necessary condition is that c < logba. If this condition is
true then T(n) = O(n^logba).
4. What is the result of the recurrences which fall under second case of Master’s theorem (let the recurrence
be given by T(n)=aT(n/b)+f(n) and f(n)=nc?
a) T(n) = O(nlogba)
b) T(n) = O(nc log n)
c) T(n) = O(f(n))
d) T(n) = O(n2)
Answer: b
Explanation: In second case of master’s theorem the necessary condition is that c = logba. If this condition is
true then T(n) = O(nc log n)
5. What is the result of the recurrences which fall under third case of Master’s theorem (let the recurrence be
given by T(n)=aT(n/b)+f(n) and f(n)=nc?
a) T(n) = O(nlogba)
b) T(n) = O(nc log n)
c) T(n) = O(f(n))
d) T(n) = O(n2)
Answer: c
Explanation: In third case of master’s theorem the necessary condition is that c > logba. If this condition is
true then T(n) = O(f(n)).
advertisement
Answer: b
Explanation: No we cannot solve all the recurrences by only using master’s theorem. We can solve only
those which fall under the three cases prescribed in the theorem.
7. Under what case of Master’s theorem will the recurrence relation of merge sort fall?
a) 1
b) 2
c) 3
d) It cannot be solved using master’s theorem
Answer: b
Explanation: The recurrence relation of merge sort is given by T(n) = 2T(n/2) + O(n). So we can observe
that c = Logba so it will fall under case 2 of master’s theorem.
8. Under what case of Master’s theorem will the recurrence relation of stooge sort fall?
a) 1
b) 2
c) 3
d) It cannot be solved using master’s theorem
Answer: a
Explanation: The recurrence relation of stooge sort is given as T(n) = 3T(2/3n) + O(1). It is found too be
equal to O(n2.7) using master’s theorem first case.
Answer: b
Explanation: The second case of master’s theorem can be extended for a case where f(n) = nc (log n)k and the
resulting recurrence becomes T(n)= O(nc (log n))k+1.
10. What is the result of the recurrences which fall under the extended second case of Master’s theorem (let
the recurrence be given by T(n)=aT(n/b)+f(n) and f(n)=nc(log n)k?
a) T(n) = O(nlogba)
b) T(n) = O(nc log n)
c) T(n)= O(nc (log n)k+1
d) T(n) = O(n2)
Answer: c
Explanation: In the extended second case of master’s theorem the necessary condition is that c = logba. If
this condition is true then T(n)= O(nc(log n))k+1.
11. Under what case of Master’s theorem will the recurrence relation of binary search fall?
a) 1
b) 2
c) 3
d) It cannot be solved using master’s theorem
Answer: b
Explanation: Th
Answer: c
Explanation: The given recurrence can be solved by using the second case of Master’s theorem.
T(n) = O(nc log n) = Here nc = n2
So the solution becomes T(n) = O(n2log n).
Answer: c
Explanation: The given recurrence can be solved by using the third case (as f(n) > log21) of Master’s
theorem.
T(n) = O(f(n)) = Here f(n) = 2n.
So the solution becomes T(n) = O(2n).
Answer: d
Explanation: The given recurrence can be solved by using the first case of Master’s theorem. So the solution
becomes T(n) = O(n2).
Answer: d
Explanation: The given recurrence cannot be solved by using the Master’s theorem. It is because this
recurrence relation does not fit into any case of Master’s theorem.
Answer: d
Explanation: The given recurrence cannot be solved by using the Master’s theorem. It is because in this
recurrence relation a < 1 so master’s theorem cannot be applied.
advertisement
6. Solve the following recurrence using Master’s theorem.
T(n) = 4 T (n/2) + n!
a) T(n) = O(n!)
b) T(n) = O(n! log n)
c) T(n) = O(n2log n)
d) cannot be solved using master’s theorem
Answer: a
Explanation: The given recurrence can be solved by using the third case of Master’s theorem. So the
solution becomes T(n) = O(n!).
Answer: a
Explanation: The given recurrence can be solved by using the extended second case of Master’s theorem. So
the solution becomes T(n) = O(n (log n)2).
Int sum(int n)
{
If(n==1)
return 1;
else
return n+sum(n-1);
}
a) T(n) = T(n/2) + n
b) T(n) = T(n-1) + n
c) T(n) = T(n-1) + O(1)
d) T(n) = T(n/2) + O(1)
Answer: c
Explanation: As after every recursive call the integer up to which the sum is to be calculated decreases by 1.
So the recurrence relation for the given code will be T(n) = T(n-1) + O(1).
a) T(n) = T(n/2) + n
b) T(n) = T(n-1) + n
c) T(n) = T(n-1) + O(1)
d) T(n) = T(n/2) + O(1)
Answer: d
Explanation: As after every recursive call the integer up to which the power is to be calculated decreases by
half. So the recurrence relation for the given code will be T(n) = T(n/2) + O(1). It can be solved by using
master’s theorem.
a) O(log n)
b) O(n)
c) O(n log n)
d) O(n2)
Answer: a
Explanation: As the recurrence re
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
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
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.
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.
advertisement
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
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
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
Answer: d
Explanation: Assuming items to be divisible-
The value/weight ratio ar
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
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
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
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
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.
advertisement
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
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
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
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
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)
Answer: d
Explan
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.
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.
advertisement
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
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
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
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
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
Answer: a
Explanation: The
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.
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.
Join [email protected]
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
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
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.
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
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
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
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
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
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
Answer: c
Explanation: The 27*27 bo
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.
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
Answer: b
Explanation: N-queen problem does not provide an optimal solution of only three values of n (i.e.) n=2,3.
advertisement
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)
Answer: a
Explanation: Of the following given options for optimal solutions of 4-queens problem, (3, 1, 4, 2) is the
right option.
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)
Answer: b
Explanation: Th
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
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
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
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
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.
advertisement
6. A greedy algorithm can be used to solve all the dynamic programming problems.
a) True
b) False
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
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
Answer: c
Explanation: Th
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
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.
advertisement
#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
Explanation: The value of n is 50000. The function is recursive and it’s time complexity is exponential. So,
the function will be called almost 250000 times. Now, even though NO variables are stored by the function, the
space required to store the addresses of these function calls will be enormous. Stack memory is utilized to
store these addresses and only a particular amount of stack memory can be used by any program. So, after a
certain function call, no more stack space will be available and it will lead to stack overflow causing runtime
error.
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)
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
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
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
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
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
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
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
Answer: d
Explanation: The progra
1. You are given infinite coins of denominations v1, v2, v3,…..,vn and a sum S. The coin change problem is
to find the minimum number of coins required to get the sum S. This problem can be solved using
____________
a) Greedy algorithm
b) Dynamic programming
c) Divide and conquer
d) Backtracking
Answer: b
Explanation: The coin change problem has overlapping subproblems(same subproblems are solved multiple
times) and optimal substructure(the solution to the problem can be found by finding optimal solutions for
subproblems). So, dynamic programming can be used to solve the coin change problem.
2. Suppose you have coins of denominations 1, 3 and 4. You use a greedy algorithm, in which you choose
the largest denomination coin which is not greater than the remaining sum. For which of the following sums,
will the algorithm NOT produce an optimal answer?
a) 20
b) 12
c) 6
d) 5
Answer: c
Explanation: Using the greedy algorithm, three coins {4,1,1} will be selected to make a sum of 6. But, the
optimal answer is two coins {3,3}.
3. Suppose you have coins of denominations 1,3 and 4. You use a greedy algorithm, in which you choose
the largest denomination coin which is not greater than the remaining sum. For which of the following sums,
will the algorithm produce an optimal answer?
a) 14
b) 10
c) 6
d) 100
Answer: d
Explanation: Using the greedy algorithm, three coins {4,1,1} will be selected to make a sum of 6. But, the
optimal answer is two coins {3,3}. Similarly, four coins {4,4,1,1} will be selected to make a sum of 10. But,
the optimal answer is three coins {4,3,3}. Also, five coins {4,4,4,1,1} will be selected to make a sum of 14.
But, the optimal answer is four coins {4,4,3,3}. For a sum of 100, twenty-five coins {all 4’s} will be
selected and the optimal answer is also twenty-five coins {all 4’s}.
#include<stdio.h>
int main()
{
int coins[10]={1,3,4},lookup[100000];
int i,j,tmp,num_coins = 3,sum=100;
lookup[0]=0;
for(i = 1; i <= sum; i++)
{
int min_coins = i;
for(j = 0;j < num_coins; j++)
{
tmp = i - coins[j];
if(tmp < 0)
continue;
if(lookup[tmp] < min_coins)
______________;
}
lookup[i] = min_coins + 1;
}
printf("%d",lookup[sum]);
return 0;
}
a) lookup[tmp] = min_coins
b) min_coins = lookup[tmp]
c) break
d) continue
Answer: b
Explanation: min_coins = lookup[tmp] will complete the code.
advertisement
5. You are given infinite coins of N denominations v1, v2, v3,…..,vn and a sum S. The coin change problem
is to find the minimum number of coins required to get the sum S. What is the time complexity of a dynamic
programming implementation used to solve the coin change problem?
a) O(N)
b) O(S)
c) O(N2)
d) O(S*N)
Answer: d
Explanation: The time complexity is O(S*N).
6. Suppose you are given infinite coins of N denominations v1, v2, v3,…..,vn and a sum S. The coin change
problem is to find the minimum number of coins required to get the sum S. What is the space complexity of
a dynamic programming implementation used to solve the coin change problem?
a) O(N)
b) O(S)
c) O(N2)
d) O(S*N)
Answer: b
Explanation: To get the optimal solution for a sum S, the optimal solution is found for each sum less than
equal to S and each solution is stored. So, the space complexity is O(S).
7. You are given infinite coins of denominations 1, 3, 4. What is the total number of ways in which a sum of
7 can be achieved using these coins if the order of the coins is not important?
a) 4
b) 3
c) 5
d) 6
Answer: c
Explanation: A sum of 7 can be achieved in the following ways:
{1,1,1,1,1,1,1}, {1,1,1,1,3}, {1,3,3}, {1,1,1,4}, {3,4}.
Therefore, the sum can be achieved in 5 ways.
8. You are given infinite coins of denominations 1, 3, 4. What is the minimum number of coins required to
achieve a sum of 7?
a) 1
b) 2
c) 3
d) 4
Answer: b
Explanation: A sum of 7 can be achieved by using a minimum of two coins {3,4}.
9. You are given infinite coins of denominations 5, 7, 9. Which of the following sum CANNOT be achieved
using these coins?
a) 50
b) 21
c) 13
d) 23
Answer: c
Explanation: One way to achieve a sum of 50 is to use ten coins of 5. A sum of 21 can be achieved by using
three coins of 7. One way to achieve a sum of 23 is to use two coins of 7 and one coin of 9. A sum of 13
cannot be achieved.
10. You are given infinite coins of denominations 3, 5, 7. Which of the following sum CANNOT be
achieved using these coins?
a) 15
b) 16
c) 17
d) 4
Answer: d
Explanation: Sums can be achieved as follows:
15 = {5,5,5}
16 = {3,3,5,5}
17 = {3,7,7}
we can’t achieve for sum=4 because our available denominations are 3,5,7 and sum of any two
denominations is greater than 4.
#include<stdio.h>
int main()
{
int coins[10]={1,3,4},lookup[100];
int i,j,tmp,num_coins = 3,sum=10;
lookup[0]=0;
for(i=1;i<=sum;i++)
{
int min_coins = i;
for(j=0;j<num_coins;j++)
{
tmp=i-coins[j];
if(tmp<0)
continue;
if(lookup[tmp] < min_coins)
min_coins=lookup[tmp];
}
lookup[i] = min_coins + 1;
}
printf("%d",lookup[sum]);
return 0;
}
a) 2
b) 3
c) 4
d) 5
Answer: b
Explanation: The program prints the minimum number of coins required to get a sum of 10, which is 3.
#include<stdio.h>
int main()
{
int coins[10]={1,3,4},lookup[100];
int i,j,tmp,num_coins = 3,sum=14;
lookup[0]=0;
for(i=1;i<=sum;i++)
{
int min_coins = i;
for(j=0;j<num_coins;j++)
{
tmp=i-coins[j];
if(tmp<0)
continue;
if(lookup[tmp] < min_coins)
min_coins=lookup[tmp];
}
lookup[i] = min_coins + 1;
}
printf("%d",lookup[sum]);
return 0;
}
a) 2
b) 3
c) 4
d) 5
Answer: c
Explanation: The program p
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
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.
advertisement
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)
Answer: a
Explanation: The naive method uses two for loops. The outer loop runs from 0 to n,
i.e. i = 0 : n.
The inner loop runs from i to n, i.e. j = i : n.
Therefore, the inner loop runs:
n times when the outer loop runs the first time.
(n-1) times when the outer loop runs the second time.
:
:
:
2 times when the outer loop runs (n-1)th time.
1 time when the outer loop runs nth time.
Therefore, time complexity = n + (n-1) + (n-2) + …… + 2 + 1 = n * (n + 1) /2 = O(n2).
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)
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
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)
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)
Answer: b
Explanat
1. Which line should be inserted in the blank to complete the following dynamic programming
implementation of the maximum sub-array sum problem?
#include<stdio.h>
int max_num(int a,int b)
{
if(a> b)
return a;
return b;
}
int maximum_subarray_sum(int *arr, int len)
{
int sum[len], idx;
sum[0] = arr[0];
for(idx = 1; idx < len; idx++)
sum[idx] = _______________________;
int mx = sum[0];
for(idx = 0; idx < len; idx++)
if(sum[idx] > mx)
mx =sum[idx];
return mx;
}
int main()
{
int arr[] = {-2, -5, 6, -2, 3, -1, 0,-5, 6}, len = 9;
int ans = maximum_subarray_sum(arr, len);
printf("%d",ans);
return 0;
}
a) max_num(sum[idx – 1] + arr[idx], arr[idx])
b) sum[idx – 1] + arr[idx].
c) min_num(sum[idx – 1] + arr[idx], arr[idx])
d) arr[idx].
Answer: a
Explanation: The array “sum” is used to store the maximum sub-array sum. The appropriate way to do this
is by using:
sum[idx] = max_num(sum[idx – 1] + arr[idx], arr[idx]).
2. What is the time complexity of the following dynamic programming algorithm used to find the maximum
sub-array sum?
#include<stdio.h>
int max_num(int a,int b)
{
if(a> b)
return a;
return b;
}
int maximum_subarray_sum(int *arr, int len)
{
int sum[len], idx;
sum[0] = arr[0];
for(idx = 1; idx < len; idx++)
sum[idx] = max_num(sum[idx - 1] + arr[idx], arr[idx]);
int mx = sum[0];
for(idx = 0; idx < len; idx++)
if(sum[idx] > mx)
mx =sum[idx];
return mx;
}
int main()
{
int arr[] = {-2, -5, 6, -2, 3, -1, 0,-5, 6}, len = 9;
int ans = maximum_subarray_sum(arr, len);
printf("%d",ans);
return 0;
}
a) O(n)
b) O(logn)
c) O(nlogn)
d) O(n2)
Answer: a
Explanation: The time complexity of the above dynamic programming algorithm used to solve maximum
sub-array sum is O(n).
advertisement
3. What is the space complexity of the following dynamic programming algorithm used to find the
maximum sub-array sum?
#include<stdio.h>
int max_num(int a,int b)
{
if(a> b)
return a;
return b;
}
int maximum_subarray_sum(int *arr, int len)
{
int sum[len], idx;
sum[0] = arr[0];
for(idx = 1; idx < len; idx++)
sum[idx] = max_num(sum[idx - 1] + arr[idx], arr[idx]);
int mx = sum[0];
for(idx = 0; idx < len; idx++)
if(sum[idx] > mx)
mx =sum[idx];
return mx;
}
int main()
{
int arr[] = {-2, -5, 6, -2, 3, -1, 0,-5, 6}, len = 9;
int ans = maximum_subarray_sum(arr, len);
printf("%d",ans);
return 0;
}
a) O(n)
b) O(1)
c) O(n!)
d) O(n2)
Answer: a
Explanation: The above dynamic programming algorithm uses space equal to the length of the array to store
the sum values. So, the space complexity is O(n).
4. Consider the following code snippet. Which property is shown by line 4 of the below code snippet?
a) Optimal substructure
b) Overlapping subproblems
c) Both overlapping subproblems and optimal substructure
d) Greedy substructure
Answer: a
Explanation: The current sum (i.e. sum[idx]) uses the previous sum (i.e. sum[idx – 1]) to get an optimal
value. So, line 4 shows the optimal substructure property.
Answer: d
Explanation: The array “sum” is used to store the previously calculated values, so that they aren’t
recalculated. So, line 4 uses the memoization technique.
Answer: b
Explanation: All the elements of the array are positive. So, the maximum sub-array sum is equal to the sum
of all the elements, which is 36.
#include<stdio.h>
int max_num(int a,int b)
{
if(a> b)
return a;
return b;
}
int maximum_subarray_sum(int *arr, int len)
{
int sum[len], idx;
sum[0] = arr[0];
for(idx = 1; idx < len; idx++)
sum[idx] = max_num(sum[idx - 1] + arr[idx], arr[idx]);
int mx = sum[0];
for(idx = 0; idx < len; idx++)
if(sum[idx] > mx)
mx =sum[idx];
return mx;
}
int main()
{
int arr[] = {-20, 23, 10, 3, -10, 11, -5},len = 7;
int ans = maximum_subarray_sum(arr, len);
printf("%d",ans);
return 0;
}
a) 27
b) 37
c) 36
d) 26
Answer: b
Explanation: The program prints the value of maximum sub-array sum, which is 37.
8. What is the value stored in sum[4] after the following program is executed?
#include<stdio.h>
int max_num(int a,int b)
{
if(a> b)
return a;
return b;
}
int maximum_subarray_sum(int *arr, int len)
{
int sum[len], idx;
sum[0] = arr[0];
for(idx = 1; idx < len; idx++)
sum[idx] = max_num(sum[idx - 1] + arr[idx], arr[idx]);
int mx = sum[0];
for(idx = 0; idx < len; idx++)
if(sum[idx] > mx)
mx =sum[idx];
return mx;
}
int main()
{
int arr[] = {-2, 14, 11, -13, 10, -5, 11, -6, 3, -5},len = 10;
int ans = maximum_subarray_sum(arr, len);
printf("%d",ans);
return 0;
}
a) 28
b) 25
c) 22
d) 12
Answer: c
Explanation: After the
Answer: c
Explanation: Kadane’s algorithm is used to find the maximum sub-array sum for a given array.
Answer: b
Explanation: Kadane’s algorithm uses dynamic programming.
3. For which of the following inputs would Kadane’s algorithm produce the INCORRECT output?
a) {0,1,2,3}
b) {-1,0,1}
c) {-1,-2,-3,0}
d) {-4,-3,-2,-1}
Answer: d
Explanation: Kadane’s algorithm works if the input array contains at least one non-negative element. Every
element in the array {-4,-3,-2,-1} is negative. Hence Kadane’s algorithm won’t work.
4. For which of the following inputs would Kadane’s algorithm produce a WRONG output?
a) {1,0,-1}
b) {-1,-2,-3}
c) {1,2,3}
d) {0,0,0}
Answer: b
Explanation: Kadane’s algorithm doesn’t work for all negative numbers. So, the answer is {-1,-2,-3}.
advertisement
#include<stdio.h>
int max_num(int a, int b)
{
if(a > b)
return a;
return b;
}
int kadane_algo(int *arr, int len)
{
int ans, sum, idx;
ans =0;
sum =0;
for(idx =0; idx < len; idx++)
{
sum = max_num(0,sum + arr[idx]);
ans = ___________;
}
return ans;
}
int main()
{
int arr[] = {-2, -3, 4, -1, -2, 1, 5, -3},len=7;
int ans = kadane_algo(arr,len);
printf("%d",ans);
return 0;
}
Answer: d
Explanation: The maximum of sum and ans, is stored in ans. So, the answer is max_num(sum, ans).
6. What is the time complexity of Kadane’s algorithm?
a) O(1)
b) O(n)
c) O(n2)
d) O(5)
Answer: b
Explanation: The time complexity of Kadane’s algorithm is O(n) because there is only one for loop which
scans the entire array exactly once.
Answer: a
Explanation: Kadane’s algorithm uses a constant space. So, the space complexity is O(1).
#include<stdio.h>
int max_num(int a, int b)
{
if(a > b)
return a;
return b;
}
int kadane_algo(int *arr, int len)
{
int ans, sum, idx;
ans =0;
sum =0;
for(idx =0; idx < len; idx++)
{
sum = max_num(0,sum + arr[idx]);
ans = max_num(sum,ans);
}
return ans;
}
int main()
{
int arr[] = {2, 3, -3, -1, 2, 1, 5, -3}, len = 8;
int ans = kadane_algo(arr,len);
printf("%d",ans);
return 0;
}
a) 6
b) 7
c) 8
d) 9
Answer: d
Explanation: Kadane’s algorithm produces the maximum sub-array sum, which is equal to 9.
a) 1
b) -1
c) -2
d) 0
Answer: d
Explanation: Kadane’s algorithm produces a wrong output when all the elements are negative. The output
produced is 0.
1. #include<stdio.h>
2. int max_num(int a, int b)
3. {
4. if(a > b)
5. return a;
6. return b;
7. }
8. int kadane_algo(int *arr, int len)
9. {
10. int ans = 0, sum = 0, idx;
11. for(idx =0; idx < len; idx++)
12. {
13. sum = max_num(0,sum + arr[idx]);
14. ans = max_num(sum,ans);
15. }
16. return ans;
17. }
18. int main()
19. {
20. int arr[] = {-2, -3, -3, -1, -2, -1, -5, -3},len = 8;
21. int ans = kadane_algo(arr,len);
22. printf("%d",ans);
23. return 0;
24. }
What changes should be made to the Kadane’s algorithm so that it produces the right output even when all
array elements are negative?
Answer: c
Explanation: Both cha
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
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
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
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
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.
advertisement
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)
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]
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)
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)
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).
#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
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
Answer: c
Explanation: The value s
1. Given a rod of length n and the selling prices of all pieces smaller than equal to n, find the most beneficial
way of cutting the rod into smaller pieces. This problem is called the rod cutting problem. Which of these
methods can be used to solve the rod cutting problem?
a) Brute force
b) Dynamic programming
c) Recursion
d) Brute force, Dynamic programming and Recursion
Answer: d
Explanation: Brute force, Dynamic programming and Recursion can be used to solve the rod cutting
problem.
2. You are given a rod of length 5 and the prices of each length are as follows:
length price
1 2
2 5
3 6
4 9
5 9
What is the maximum value that you can get after cutting the rod and selling the pieces?
a) 10
b) 11
c) 12
d) 13
Answer: c
Explanation: The pieces {1,2 2} give the maximum value of 12.
3. Consider the brute force implementation of the rod cutting problem in which all the possible cuts are
found and the maximum value is calculated. What is the time complexity of this brute force
implementation?
a) O(n2)
b) O(n3)
c) O(nlogn)
d) O(2n)
Answer: d
Explanation: The brute force implementation finds all the possible cuts. This takes O(2n) time.
4. You are given a rod of length 10 and the following prices.
length price
1 2
2 5
3 6
4 9
5 9
6 17
7 17
8 18
9 20
10 22
Answer: c
Explanation: The pieces {2,2,6} give the maximum value of 27.
advertisement
#include<stdio.h>
#include<limits.h>
int max_of_two(int a, int b)
{
if(a > b)
return a;
return b;
}
int rod_cut(int *prices, int len)
{
int max_price = INT_MIN; // INT_MIN is the min value an integer can take
int i;
if(len <= 0 )
return 0;
for(i = 0; i < len; i++)
max_price = max_of_two(_____________); // subtract 1 because index starts from
0
return max_price;
}
int main()
{
int prices[]={2, 5, 6, 9, 9, 17, 17, 18, 20, 22},len_of_rod = 10;
int ans = rod_cut(prices, len_of_rod);
printf("%d",ans);
return 0;
}
#include<stdio.h>
#include<limits.h>
int max_of_two(int a, int b)
{
if(a > b)
return a;
return b;
}
int rod_cut(int *prices, int len)
{
int max_price = INT_MIN; // INT_MIN is the min value an integer can take
int i;
if(len <= 0 )
return 0;
for(i = 0; i < len; i++)
// subtract 1 because index starts from 0
max_price = max_of_two(max_price, prices[i] + rod_cut(prices,len - i - 1));
return max_price;
}
int main()
{
int prices[]={2, 5, 6, 9, 9, 17, 17, 18, 20, 22},len_of_rod = 10;
int ans = rod_cut(prices, len_of_rod);
printf("%d",ans);
return 0;
}
a) O(n)
b) O(n2)
c) O(n3)
d) O(2n)
Answer: d
Explanation: The time complexity of the above recursive implementation is O(2n).
#include<stdio.h>
#include<limits.h>
int max_of_two(int a, int b)
{
if(a > b)
return a;
return b;
}
int rod_cut(int *prices, int len)
{
int max_price = INT_MIN; // INT_MIN is the min value an integer can take
int i;
if(len <= 0 )
return 0;
for(i = 0; i < len; i++)
// subtract 1 because index starts from 0
max_price = max_of_two(max_price, prices[i] + rod_cut(prices,len - i - 1));
return max_price;
}
int main()
{
int prices[]={2, 5, 6, 9, 9, 17, 17, 18, 20, 22},len_of_rod = 10;
int ans = rod_cut(prices, len_of_rod);
printf("%d",ans);
return 0;
}
a) O(1)
b) O(logn)
c) O(nlogn)
d) O(n!)
Answer: a
Explanation: The space complexity of the above recursive implementation is O(1) because it uses a constant
space.
8. What will be the value stored in max_value when the following code is executed?
#include<stdio.h>
#include<limits.h>
int max_of_two(int a, int b)
{
if(a > b)
return a;
return b;
}
int rod_cut(int *prices, int len)
{
int max_price = INT_MIN; // INT_MIN is the min value an integer can take
int i;
if(len <= 0 )
return 0;
for(i = 0; i < len; i++)
// subtract 1 because index starts from 0
max_price = max_of_two(prices[i] + rod_cut(prices,len - i - 1), max_price);
return max_price;
}
int main()
{
int prices[]={2, 5, 6, 9, 9, 17, 17, 18, 20, 22},len_of_rod = 3;
int ans = rod_cut(prices, len_of_rod);
printf("%d",ans);
return 0;
}
a) 5
b) 6
c) 7
d) 8
Answer: c
Explanation: The value stored in max_value after the code is executed is equal to 7.
9. For every rod cutting problem there will be a unique set of pieces that give the maximum price.
a) True
b) False
Answer: b
Explanation: Consider a rod of length 3. The prices are {2,3,6} for lengths {1,2,3} respectively. The pieces
{1,1,1} and {3} both give the maximum value of 6.
10.Consider the following dynamic programming implementation of the rod cutting problem:
#include<stdio.h>
#include<limits.h>
int rod_cut(int *prices, int len)
{
int max_val[len + 1];
int i,j,tmp_price,tmp_idx;
max_val[0] = 0;
for(i = 1; i <= len; i++)
{
int tmp_max = INT_MIN; // minimum value an integer can hold
for(j = 1; j <= i; j++)
{
tmp_idx = i - j;
//subtract 1 because index of prices starts from 0
tmp_price = _____________;
if(tmp_price > tmp_max)
tmp_max = tmp_price;
}
max_val[i] = tmp_max;
}
return max_val[len];
}
int main()
{
int prices[]={2, 5, 6, 9, 9, 17, 17, 18, 20, 22},len_of_rod = 5;
int ans = rod_cut(prices, len_of_rod);
printf("%d",ans);
return 0;
}
Answer: a
Explanation: prices[j-1] + max_val[tmp_idx] completes the code.
11. What is the time complexity of the following dynamic programming implementation of the rod cutting
problem?
#include<stdio.h>
#include<limits.h>
int rod_cut(int *prices, int len)
{
int max_val[len + 1];
int i,j,tmp_price,tmp_idx;
max_val[0] = 0;
for(i = 1; i <= len; i++)
{
int tmp_max = INT_MIN; // minimum value an integer can hold
for(j = 1; j <= i; j++)
{
tmp_idx = i - j;
//subtract 1 because index of prices starts from 0
tmp_price = prices[j-1] + max_val[tmp_idx];
if(tmp_price > tmp_max)
tmp_max = tmp_price;
}
max_val[i] = tmp_max;
}
return max_val[len];
}
int main()
{
int prices[]={2, 5, 6, 9, 9, 17, 17, 18, 20, 22},len_of_rod = 5;
int ans = rod_cut(prices, len_of_rod);
printf("%d",ans);
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(2n)
Answer: c
Explanation: The time complexity of the above dynamic programming implementation of the rod cutting
problem is O(n2).
12. What is the space complexity of the following dynamic programming implementation of the rod cutting
problem?
#include<stdio.h>
#include<limits.h>
int rod_cut(int *prices, int len)
{
int max_val[len + 1];
int i,j,tmp_price,tmp_idx;
max_val[0] = 0;
for(i = 1; i <= len; i++)
{
int tmp_max = INT_MIN; // minimum value an integer can hold
for(j = 1; j <= i; j++)
{
tmp_idx = i - j;
//subtract 1 because index of prices starts from 0
tmp_price = prices[j-1] + max_val[tmp_idx];
if(tmp_price > tmp_max)
tmp_max = tmp_price;
}
max_val[i] = tmp_max;
}
return max_val[len];
}
int main()
{
int prices[]={2, 5, 6, 9, 9, 17, 17, 18, 20, 22},len_of_rod = 5;
int ans = rod_cut(prices, len_of_rod);
printf("%d",ans);
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(2n)
Answer: b
Explanation: The space complexity of the above dynamic programming implementation of the rod cutting
problem is O(n) because it uses a space equal to the length of the rod.
#include<stdio.h>
#include<limits.h>
int rod_cut(int *prices, int len)
{
int max_val[len + 1];
int i,j,tmp_price,tmp_idx;
max_val[0] = 0;
for(i = 1; i <= len; i++)
{
int tmp_max = INT_MIN; // minimum value an integer can hold
for(j = 1; j <= i; j++)
{
tmp_idx = i - j;
//subtract 1 because index of prices starts from 0
tmp_price = prices[j-1] + max_val[tmp_idx];
if(tmp_price > tmp_max)
tmp_max = tmp_price;
}
max_val[i] = tmp_max;
}
return max_val[len];
}
int main()
{
int prices[]={2, 5, 6, 9, 9, 17, 17, 18, 20, 22},len_of_rod = 5;
int ans = rod_cut(prices, len_of_rod);
printf("%d",ans);
return 0;
}
a) 9
b) 10
c) 11
d) 12
Answer: d
Explanation: The program prints the maximum price that can be achieved by cutting the rod into pieces,
which is equal to 27.
14. What is the value stored in max_val[5] after the following program is executed?
#include<stdio.h>
#include<limits.h>
int rod_cut(int *prices, int len)
{
int max_val[len + 1];
int i,j,tmp_price,tmp_idx;
max_val[0] = 0;
for(i = 1; i <= len; i++)
{
int tmp_max = INT_MIN; // minimum value an integer can hold
for(j = 1; j <= i; j++)
{
tmp_idx = i - j;
//subtract 1 because index of prices starts from 0
tmp_price = prices[j-1] + max_val[tmp_idx];
if(tmp_price > tmp_max)
tmp_max = tmp_price;
}
max_val[i] = tmp_max;
}
return max_val[len];
}
int main()
{
int prices[]={2, 5, 6, 9, 9, 17, 17, 18, 20, 22},len_of_rod = 5;
int ans = rod_cut(prices, len_of_rod);
printf("%d",ans);
return 0;
}
a) 12
b) 27
c) 10
d) 17
Answer: a
Explanation: The value s
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
Answer: d
Explanation: Both recursion and dynamic programming can be used to solve minimum number of jumps
problem.
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
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
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}.
In both the cases the number of jumps is 3, which is minimum. Hence, it is possible to reach the end of the
array in multiple ways using minimum number of jumps.
advertisement
#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
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
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
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
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)
Answer: b
Explanation: The space complexity of the above dynamic programming implementation is O(n).
#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
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.
#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
Answer: a
Explanation: The program prints the minimum jumps required to reach the end of the array, which is 1 and
so the outpu
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
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
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)
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).
advertisement
Answer: b
Explanation: The Knapsack problem cannot be solved using the greedy algorithm.
7. Consider 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] = ______________;
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)
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)
Answer: c
Explanation: The space complexity of the above dynamic programming implementation of the Knapsack
problem is O(nW).
#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
Answer: d
Explanation
1. Which of the following methods can be used to solve the matrix chain multiplication problem?
a) Dynamic programming
b) Brute force
c) Recursion
d) Dynamic Programming, Brute force, Recursion
Answer: d
Explanation: Dynamic Programming, Brute force, Recursion methods can be used to solve the matrix chain
multiplication problem.
2. Which of the following is the recurrence relation for the matrix chain multiplication problem where mat[i-
1] * mat[i] gives the dimension of the ith matrix?
a) dp[i,j] = 1 if i=j
dp[i,j] = min{dp[i,k] + dp[k+1,j]}
b) dp[i,j] = 0 if i=j
dp[i,j] = min{dp[i,k] + dp[k+1,j]}
c) dp[i,j] = 1 if i=j
dp[i,j] = min{dp[i,k] + dp[k+1,j]} + mat[i-1]*mat[k]*mat[j].
d) dp[i,j] = 0 if i=j
dp[i,j] = min{dp[i,k] + dp[k+1,j]} + mat[i-1]*mat[k]*mat[j].
Answer: d
Explanation: The recurrence relation is given by:
dp[i,j] = 0 if i=j
dp[i,j] = min{dp[i,k] + dp[k+1,j]} + mat[i-1]*mat[k]*mat[j].
3. Consider the two matrices P and Q which are 10 x 20 and 20 x 30 matrices respectively. What is the
number of multiplications required to multiply the two matrices?
a) 10*20
b) 20*30
c) 10*30
d) 10*20*30
Answer: d
Explanation: The number of multiplications required is 10*20*30.
4. Consider the matrices P, Q and R which are 10 x 20, 20 x 30 and 30 x 40 matrices respectively. What is
the minimum number of multiplications required to multiply the three matrices?
a) 18000
b) 12000
c) 24000
d) 32000
Answer: a
Explanation: The minimum number of multiplications are 18000. This is the case when the matrices are
parenthesized as (P*Q)*R.
5. Consider the matrices P, Q, R and S which are 20 x 15, 15 x 30, 30 x 5 and 5 x 40 matrices respectively.
What is the minimum number of multiplications required to multiply the four matrices?
a) 6050
b) 7500
c) 7750
d) 12000
Answer: c
Explanation: The minimum number of multiplications required is 7750.
6. Consider the brute force implementation in which we find all the possible ways of multiplying the given
set of n matrices. What is the time complexity of this implementation?
a) O(n!)
b) O(n3)
c) O(n2)
d) Exponential
Answer: d
Explanation: The time complexity of finding all the possible ways of multiplying a set of n matrices is given
by (n-1)th Catalan number which is exponential.
7. Consider the following dynamic programming implementation of the matrix chain problem:
advertisement
#include<stdio.h>
#include<limits.h>
int mat_chain_multiplication(int *mat, int n)
{
int arr[n][n];
int i,k,row,col,len;
for(i=1;i<n;i++)
arr[i][i] = 0;
for(len = 2; len < n; len++)
{
for(row = 1; row <= n - len + 1; row++)
{
col = row + len - 1;
arr[row][col] = INT_MAX;
for(k = row; k <= col - 1; k++)
{
int tmp = ________________________;
if(tmp < arr[row][col])
arr[row][col] = tmp;
}
}
}
return arr[1][n - 1];
}
int main()
{
int mat[6] = {20,5,30,10,40};
int ans = mat_chain_multiplication(mat,5);
printf("%d",ans);
return 0;
}
Which of the following lines should be inserted to complete the above code?
a) arr[row][k] – arr[k + 1][col] + mat[row – 1] * mat[k] * mat[col];
b) arr[row][k] + arr[k + 1][col] – mat[row – 1] * mat[k] * mat[col];
c) arr[row][k] + arr[k + 1][col] + mat[row – 1] * mat[k] * mat[col];
d) arr[row][k] – arr[k + 1][col] – mat[row – 1] * mat[k] * mat[col];
Answer: c
Explanation: The line arr[row][k] + arr[k + 1][col] + mat[row – 1] * mat[k] * mat[col] should be inserted to
complete the above code.
8. What is the time complexity of the following dynamic programming implementation of the matrix chain
problem?
#include<stdio.h>
#include<limits.h>
int mat_chain_multiplication(int *mat, int n)
{
int arr[n][n];
int i,k,row,col,len;
for(i=1;i<n;i++)
arr[i][i] = 0;
for(len = 2; len < n; len++)
{
for(row = 1; row <= n - len + 1; row++)
{
col = row + len - 1;
arr[row][col] = INT_MAX;
for(k = row; k <= col - 1; k++)
{
int tmp = arr[row][k] + arr[k + 1][col] + mat[row - 1] * mat[k] *
mat[col];
if(tmp < arr[row][col])
arr[row][col] = tmp;
}
}
}
return arr[1][n - 1];
}
int main()
{
int mat[6] = {20,5,30,10,40};
int ans = mat_chain_multiplication(mat,5);
printf("%d",ans);
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
Answer: d
Explanation: The time complexity of the above dynamic programming implementation of the matrix chain
multiplication is O(n3).
9. What is the space complexity of the following dynamic programming implementation of the matrix chain
problem?
#include<stdio.h>
#include<limits.h>
int mat_chain_multiplication(int *mat, int n)
{
int arr[n][n];
int i,k,row,col,len;
for(i=1;i<n;i++)
arr[i][i] = 0;
for(len = 2; len < n; len++)
{
for(row = 1; row <= n - len + 1; row++)
{
col = row + len - 1;
arr[row][col] = INT_MAX;
for(k = row; k <= col - 1; k++)
{
int tmp = arr[row][k] + arr[k + 1][col] + mat[row - 1] * mat[k] *
mat[col];
if(tmp < arr[row][col])
arr[row][col] = tmp;
}
}
}
return arr[1][n - 1];
}
int main()
{
int mat[6] = {20,5,30,10,40};
int ans = mat_chain_multiplication(mat,5);
printf("%d",ans);
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
Answer: c
Explanation: The space complexity of the above dynamic programming implementation of the matrix chain
multiplication is O(n2).
#include<stdio.h>
#include<limits.h>
int mat_chain_multiplication(int *mat, int n)
{
int arr[n][n];
int i,k,row,col,len;
for(i=1;i<n;i++)
arr[i][i] = 0;
for(len = 2; len < n; len++)
{
for(row = 1; row <= n - len + 1; row++)
{
col = row + len - 1;
arr[row][col] = INT_MAX;
for(k = row; k <= col - 1; k++)
{
int tmp = arr[row][k] + arr[k + 1][col] + mat[row - 1] * mat[k] *
mat[col];
if(tmp < arr[row][col])
arr[row][col] = tmp;
}
}
}
return arr[1][n - 1];
}
int main()
{
int mat[6] = {20,30,40,50};
int ans = mat_chain_multiplication(mat,4);
printf("%d",ans);
return 0;
}
a) 64000
b) 70000
c) 120000
d) 150000
Answer: a
Explanation: The program prints the minimum number of multiplications required, which is 64000.
11. What is the value stored in arr[2][3] when the following code is executed?
#include<stdio.h>
#include<limits.h>
int mat_chain_multiplication(int *mat, int n)
{
int arr[n][n];
int i,k,row,col,len;
for(i=1;i<n;i++)
arr[i][i] = 0;
for(len = 2; len < n; len++)
{
for(row = 1; row <= n - len + 1; row++)
{
col = row + len - 1;
arr[row][col] = INT_MAX;
for(k = row; k <= col - 1; k++)
{
int tmp = arr[row][k] + arr[k + 1][col] + mat[row - 1] * mat[k] *
mat[col];
if(tmp < arr[row][col])
arr[row][col] = tmp;
}
}
}
return arr[1][n - 1];
}
int main()
{
int mat[6] = {20,30,40,50};
int ans = mat_chain_multiplication(mat,4);
printf("%d",ans);
return 0;
}
a) 64000
b) 60000
c) 24000
d) 12000
Answer: b
Explanation: The value stored in arr[2][3] when the above code is executed is 60000.
a) 2000
b) 3000
c) 4000
d) 5000
Answer: c
Explanation: The program prints the minimum number of multiplications required to multiply the given
matrices, which is 4000.
#include<stdio.h>
#include<limits.h>
int mat_chain_multiplication(int *mat, int n)
{
int arr[n][n];
int i,k,row,col,len;
for(i=1;i<n;i++)
arr[i][i] = 0;
for(len = 2; len < n; len++)
{
for(row = 1; row <= n - len + 1; row++)
{
col = row + len - 1;
arr[row][col] = INT_MAX;
for(k = row; k <= col - 1; k++)
{
int tmp = arr[row][k] + arr[k + 1][col] + mat[row - 1] * mat[k] *
mat[col];
if(tmp < arr[row][col])
arr[row][col] = tmp;
}
}
}
return arr[1][n-1];
}
int main()
{
int mat[6] = {20,25,30,35,40};
int ans = mat_chain_multiplication(mat,5);
printf("%d",ans);
return 0;
}
a) 32000
b) 28000
c) 64000
d) 70000
Answer: c
Explanation: The output of
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
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
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
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)
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.
advertisement
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)
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)
Answer: d
Explanation: The space complexity of the above dynamic programming implementation of the longest
common subsequence is O(mn).
#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
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
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
Answer: a
Explanation: The value stored in arr[2][3] is 1.
#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
Answer: d
Explanation: The p
1. Which of the following methods can be used to solve the longest palindromic subsequence problem?
a) Dynamic programming
b) Recursion
c) Brute force
d) Dynamic programming, Recursion, Brute force
Answer: d
Explanation: Dynamic programming, Recursion, Brute force can be used to solve the longest palindromic
subsequence problem.
Answer: d
Explanation: ‘adba’ is not a palindromic sequence.
3. For which of the following, the length of the string is not equal to the length of the longest palindromic
subsequence?
a) A string that is a palindrome
b) A string of length one
c) A string that has all the same letters(e.g. aaaaaa)
d) Some strings of length two
Answer: d
Explanation: A string of length 2 for eg: ab is not a palindrome.
4. What is the length of the longest palindromic subsequence for the string “ababcdabba”?
a) 6
b) 7
c) 8
d) 9
Answer: b
Explanation: The longest palindromic subsequence is “abbabba” and its length is 7.
5. What is the time complexity of the brute force algorithm used to find the length of the longest palindromic
subsequence?
a) O(1)
b) O(2n)
c) O(n)
d) O(n2)
Answer: b
Explanation: In the brute force algorithm, all the subsequences are found and the length of the longest
palindromic subsequence is calculated. This takes exponential time.
6. For every non-empty string, the length of the longest palindromic subsequence is at least one.
a) True
b) False
Answer: a
Explanation: A single character of any string can always be considered as a palindrome and its length is one.
Answer: b
Explanation: Longest palindromic subsequence is an example of 2D dynamic programming.
advertisement
#include<stdio.h>
#include<string.h>
int max_num(int a, int b)
{
if(a > b)
return a;
return b;
}
int lps(char *str1)
{
int i,j,len;
len = strlen(str1);
char str2[len + 1];
strcpy(str2, str1);
______________;
int arr[len + 1][len + 1];
for(i = 0; i <= len; i++)
arr[i][0] = 0;
for(i = 0; i <= len; i++)
arr[0][i] = 0;
for(i = 1; i <= len; i++)
{
for(j = 1; j <= len; 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[len][len];
}
int main()
{
char str1[] = "ababcdabba";
int ans = lps(str1);
printf("%d",ans);
return 0;
}
Answer: a
Explanation: To find the longest palindromic subsequence, we need to reverse the copy of the string, which
is done by strrev.
9. What is the time complexity of the following dynamic programming implementation to find the longest
palindromic subsequence where the length of the string is n?
#include<stdio.h>
#include<string.h>
int max_num(int a, int b)
{
if(a > b)
return a;
return b;
}
int lps(char *str1)
{
int i,j,len;
len = strlen(str1);
char str2[len + 1];
strcpy(str2, str1);
strrev(str2);
int arr[len + 1][len + 1];
for(i = 0; i <= len; i++)
arr[i][0] = 0;
for(i = 0; i <= len; i++)
arr[0][i] = 0;
for(i = 1; i <= len; i++)
{
for(j = 1; j <= len; 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[len][len];
}
int main()
{
char str1[] = "ababcdabba";
int ans = lps(str1);
printf("%d",ans);
return 0;
}
a) O(n)
b) O(1)
c) O(n2)
d) O(2)
Answer: c
Explanation: The time complexity of the above dynamic programming implementation to find the longest
palindromic subsequence is O(n2).
10. What is the space complexity of the following dynamic programming implementation to find the longest
palindromic subsequence where the length of the string is n?
#include<stdio.h>
#include<string.h>
int max_num(int a, int b)
{
if(a > b)
return a;
return b;
}
int lps(char *str1)
{
int i,j,len;
len = strlen(str1);
char str2[len + 1];
strcpy(str2, str1);
strrev(str2);
int arr[len + 1][len + 1];
for(i = 0; i <= len; i++)
arr[i][0] = 0;
for(i = 0; i <= len; i++)
arr[0][i] = 0;
for(i = 1; i <= len; i++)
{
for(j = 1; j <= len; 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[len][len];
}
int main()
{
char str1[] = "ababcdabba";
int ans = lps(str1);
printf("%d",ans);
return 0;
}
a) O(n)
b) O(1)
c) O(n2)
d) O(2)
Answer: c
Explanation: The space complexity of the above dynamic programming implementation to find the longest
palindromic subsequence is O(n2).
11. What is the value stored in arr[3][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 lps(char *str1)
{
int i,j,len;
len = strlen(str1);
char str2[len + 1];
strcpy(str2, str1);
strrev(str2);
int arr[len + 1][len + 1];
for(i = 0; i <= len; i++)
arr[i][0] = 0;
for(i = 0; i <= len; i++)
arr[0][i] = 0;
for(i = 1; i <= len; i++)
{
for(j = 1; j <= len; 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[len][len];
}
int main()
{
char str1[] = "ababcdabba";
int ans = lps(str1);
printf("%d",ans);
return 0;
}
a) 2
b) 3
c) 4
d) 5
Answer: a
Explanation: The value stored in arr[3][3] when the above code is executed is 2.
#include<stdio.h>
#include<string.h>
int max_num(int a, int b)
{
if(a > b)
return a;
return b;
}
int lps(char *str1)
{
int i,j,len;
len = strlen(str1);
char str2[len + 1];
strcpy(str2, str1);
strrev(str2);
int arr[len + 1][len + 1];
for(i = 0; i <= len; i++)
arr[i][0] = 0;
for(i = 0; i <= len; i++)
arr[0][i] = 0;
for(i = 1; i <= len; i++)
{
for(j = 1; j <= len; 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[len][len];
}
int main()
{
char str1[] = "abcd";
int ans = lps(str1);
printf("%d",ans);
return 0;
}
a) 0
b) 1
c) 2
d) 3
Answer: b
Explanation: The program prints the length of the longest palindromic subsequence, which is 1.
#include<stdio.h>
#include<string.h>
int max_num(int a, int b)
{
if(a > b)
return a;
return b;
}
int lps(char *str1)
{
int i,j,len;
len = strlen(str1);
char str2[len + 1];
strcpy(str2, str1);
strrev(str2);
int arr[len + 1][len + 1];
for(i = 0; i <= len; i++)
arr[i][0] = 0;
for(i = 0; i <= len; i++)
arr[0][i] = 0;
for(i = 1; i <= len; i++)
{
for(j = 1; j <= len; 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[len][len];
}
int main()
{
char str1[] = "abdgkagdjbccbba";
int ans = lps(str1);
printf("%d",ans);
return 0;
}
a) 5
b) 7
c) 9
d) 11
Answer: c
1. Which of the following methods can be used to solve the edit distance problem?
a) Recursion
b) Dynamic programming
c) Both dynamic programming and recursion
d) Greedy Algorithm
Answer: c
Explanation: Both dynamic programming and recursion can be used to solve the edit distance problem.
2. The edit distance satisfies the axioms of a metric when the costs are non-negative.
a) True
b) False
Answer: a
Explanation: d(s,s) = 0, since each string can be transformed into itself without any change.
d(s1, s2) > 0 when s1 != s2, since the transformation would require at least one operation.
d(s1, s2) = d(s2, s1)
d(s1, s3) <= d(s1, s2) + d(s2, s3)
Thus, the edit distance satisfies the axioms of a metric.
Answer: d
Explanation: All of the mentioned are the applications of the edit distance problem.
4. In which of the following cases will the edit distance between two strings be zero?
a) When one string is a substring of another
b) When the lengths of the two strings are equal
c) When the two strings are equal
d) The edit distance can never be zero
Answer: c
Explanation: The edit distance will be zero only when the two strings are equal.
5. Suppose each edit (insert, delete, replace) has a cost of one. Then, the maximum edit distance cost
between the two strings is equal to the length of the larger string.
a) True
b) False
Answer: a
Explanation: Consider the strings “abcd” and “efghi”. The string “efghi” can be converted to “abcd” by
deleting “i” and converting “efgh” to “abcd”. The cost of transformation is 5, which is equal to the length of
the larger string.
6. Consider the strings “monday” and “tuesday”. What is the edit distance between the two strings?
a) 3
b) 4
c) 5
d) 6
Answer: b
Explanation: “monday” can be converted to “tuesday” by replacing “m” with “t”, “o” with “u”, “n” with “e”
and inserting “s” at the appropriate position. So, the edit distance is 4.
7. Consider the two strings “”(empty string) and “abcd”. What is the edit distance between the two strings?
a) 0
b) 4
c) 2
d) 3
Answer: b
Explanation: The empty string can be transformed into “abcd” by inserting “a”, “b”, “c” and “d” at
appropriate positions. Thus, the edit distance is 4.
advertisement
8. Consider the following dynamic programming implementation of the edit distance problem:
#include<stdio.h>
#include<string.h>
int get_min(int a, int b)
{
if(a < b)
return a;
return b;
}
int edit_distance(char *s1, char *s2)
{
int len1,len2,i,j,min;
len1 = strlen(s1);
len2 = strlen(s2);
int arr[len1 + 1][len2 + 1];
for(i = 0;i <= len1; i++)
arr[i][0] = i;
for(i = 0; i <= len2; i++)
arr[0][i] = i;
for(i = 1; i <= len1; i++)
{
for(j = 1; j <= len2; j++)
{
min = get_min(arr[i-1][j],arr[i][j-1]) + 1;
if(s1[i - 1] == s2[j - 1])
{
if(arr[i-1][j-1] < min)
min = arr[i-1][j-1];
}
else
{
if(arr[i-1][j-1] + 1 < min)
min = arr[i-1][j-1] + 1;
}
_____________;
}
}
return arr[len1][len2];
}
int main()
{
char s1[] = "abcd", s2[] = "defg";
int ans = edit_distance(s1, s2);
printf("%d",ans);
return 0;
}
Which of the following lines should be added to complete the above code?
a) arr[i-1][j] = min
b) arr[i][j-1] = min
c) arr[i-1][j-1] = min
d) arr[i][j] = min
Answer: d
Explanation: The line arr[i][j] = min completes the above code.
9. What is the time complexity of the following dynamic programming implementation of the edit distance
problem where “m” and “n” are the lengths of two strings?
#include<stdio.h>
#include<string.h>
int get_min(int a, int b)
{
if(a < b)
return a;
return b;
}
int edit_distance(char *s1, char *s2)
{
int len1,len2,i,j,min;
len1 = strlen(s1);
len2 = strlen(s2);
int arr[len1 + 1][len2 + 1];
for(i = 0;i <= len1; i++)
arr[i][0] = i;
for(i = 0; i <= len2; i++)
arr[0][i] = i;
for(i = 1; i <= len1; i++)
{
for(j = 1; j <= len2; j++)
{
min = get_min(arr[i-1][j],arr[i][j-1]) + 1;
if(s1[i - 1] == s2[j - 1])
{
if(arr[i-1][j-1] < min)
min = arr[i-1][j-1];
}
else
{
if(arr[i-1][j-1] + 1 < min)
min = arr[i-1][j-1] + 1;
}
arr[i][j] = min;
}
}
return arr[len1][len2];
}
int main()
{
char s1[] = "abcd", s2[] = "defg";
int ans = edit_distance(s1, s2);
printf("%d",ans);
return 0;
}
a) O(1)
b) O(m + n)
c) O(mn)
d) O(n)
Answer: c
Explanation: The time complexity of the above dynamic programming implementation of the edit distance
problem is O(mn).
10. What is the space complexity of the following dynamic programming implementation of the edit
distance problem where “m” and “n” are the lengths of the two strings?
#include<stdio.h>
#include<string.h>
int get_min(int a, int b)
{
if(a < b)
return a;
return b;
}
int edit_distance(char *s1, char *s2)
{
int len1,len2,i,j,min;
len1 = strlen(s1);
len2 = strlen(s2);
int arr[len1 + 1][len2 + 1];
for(i = 0;i <= len1; i++)
arr[i][0] = i;
for(i = 0; i <= len2; i++)
arr[0][i] = i;
for(i = 1; i <= len1; i++)
{
for(j = 1; j <= len2; j++)
{
min = get_min(arr[i-1][j],arr[i][j-1]) + 1;
if(s1[i - 1] == s2[j - 1])
{
if(arr[i-1][j-1] < min)
min = arr[i-1][j-1];
}
else
{
if(arr[i-1][j-1] + 1 < min)
min = arr[i-1][j-1] + 1;
}
arr[i][j] = min;
}
}
return arr[len1][len2];
}
int main()
{
char s1[] = "abcd", s2[] = "defg";
int ans = edit_distance(s1, s2);
printf("%d",ans);
return 0;
}
a) O(1)
b) O(m + n)
c) O(mn)
d) O(n)
Answer: c
Explanation: The space complexity of the above dynamic programming implementation of the edit distance
problem is O(mn).
#include<stdio.h>
#include<string.h>
int get_min(int a, int b)
{
if(a < b)
return a;
return b;
}
int edit_distance(char *s1, char *s2)
{
int len1,len2,i,j,min;
len1 = strlen(s1);
len2 = strlen(s2);
int arr[len1 + 1][len2 + 1];
for(i = 0;i <= len1; i++)
arr[i][0] = i;
for(i = 0; i <= len2; i++)
arr[0][i] = i;
for(i = 1; i <= len1; i++)
{
for(j = 1; j <= len2; j++)
{
min = get_min(arr[i-1][j],arr[i][j-1]) + 1;
if(s1[i - 1] == s2[j - 1])
{
if(arr[i-1][j-1] < min)
min = arr[i-1][j-1];
}
else
{
if(arr[i-1][j-1] + 1 < min)
min = arr[i-1][j-1] + 1;
}
arr[i][j] = min;
}
}
return arr[len1][len2];
}
int main()
{
char s1[] = "abcd", s2[] = "defg";
int ans = edit_distance(s1, s2);
printf("%d",ans);
return 0;
}
a) 1
b) 2
c) 3
d) 4
Answer: d
Explanation: The program prints the edit distance between the strings “abcd” and “defg”, which is 4.
12. What is the value stored in arr[2][2] when the following code is executed?
#include<stdio.h>
#include<string.h>
int get_min(int a, int b)
{
if(a < b)
return a;
return b;
}
int edit_distance(char *s1, char *s2)
{
int len1,len2,i,j,min;
len1 = strlen(s1);
len2 = strlen(s2);
int arr[len1 + 1][len2 + 1];
for(i = 0;i <= len1; i++)
arr[i][0] = i;
for(i = 0; i <= len2; i++)
arr[0][i] = i;
for(i = 1; i <= len1; i++)
{
for(j = 1; j <= len2; j++)
{
min = get_min(arr[i-1][j],arr[i][j-1]) + 1;
if(s1[i - 1] == s2[j - 1])
{
if(arr[i-1][j-1] < min)
min = arr[i-1][j-1];
}
else
{
if(arr[i-1][j-1] + 1 < min)
min = arr[i-1][j-1] + 1;
}
arr[i][j] = min;
}
}
return arr[len1][len2];
}
int main()
{
char s1[] = "abcd", s2[] = "defg";
int ans = edit_distance(s1, s2);
printf("%d",ans);
return 0;
}
a) 1
b) 2
c) 3
d) 4
Answer: b
Explanation: The value stored in arr[2][2] when the above code is executed is 2.
#include<stdio.h>
#include<string.h>
int get_min(int a, int b)
{
if(a < b)
return a;
return b;
}
int edit_distance(char *s1, char *s2)
{
int len1,len2,i,j,min;
len1 = strlen(s1);
len2 = strlen(s2);
int arr[len1 + 1][len2 + 1];
for(i = 0;i <= len1; i++)
arr[i][0] = i;
for(i = 0; i <= len2; i++)
arr[0][i] = i;
for(i = 1; i <= len1; i++)
{
for(j = 1; j <= len2; j++)
{
min = get_min(arr[i-1][j],arr[i][j-1]) + 1;
if(s1[i - 1] == s2[j - 1])
{
if(arr[i-1][j-1] < min)
min = arr[i-1][j-1];
}
else
{
if(arr[i-1][j-1] + 1 < min)
min = arr[i-1][j-1] + 1;
}
arr[i][j] = min;
}
}
return arr[len1][len2];
}
int main()
{
char s1[] = "pqrstuv", s2[] = "prstuv";
int ans = edit_distance(s1, s2);
printf("%d",ans);
return 0;
}
a) 1
b) 2
c) 3
d) 4
Answer: a
Explanation: The c
Answer: c
Explanation: Wagner–Fischer belongs to the dynamic programming type of algorithms.
Answer: c
Explanation: Wagner–Fischer algorithm is used to find the edit distance between two strings.
3. What is the edit distance between the strings “abcd” and “acbd” when the allowed operations are
insertion, deletion and substitution?
a) 1
b) 2
c) 3
d) 4
Answer: b
Explanation: The string “abcd” can be changed to “acbd” by substituting “b” with “c” and “c” with “b”.
Thus, the edit distance is 2.
4. For which of the following pairs of strings is the edit distance maximum?
a) sunday & monday
b) monday & tuesday
c) tuesday & wednesday
d) wednesday & thursday
Answer: d
Explanation: The edit distances are 2, 4, 4 and 5 respectively. Hence, the maximum edit distance is between
the strings wednesday and thursday.
Join [email protected]
int get_min(int a, int b)
{
if(a < b)
return a;
return b;
}
int edit_distance(char *s1, char *s2)
{
int len1,len2,i,j,min;
len1 = strlen(s1);
len2 = strlen(s2);
int arr[len1 + 1][len2 + 1];
for(i = 0;i <= len1; i++)
arr[i][0] = i;
for(i = 0; i <= len2; i++)
arr[0][i] = i;
for(i = 1; i <= len1; i++)
{
for(j = 1; j <= len2; j++)
{
min = get_min(arr[i-1][j],arr[i][j-1]) + 1;
if(s1[i - 1] == s2[j - 1])
{
if(arr[i-1][j-1] < min)
____________;
}
else
{
if(arr[i-1][j-1] + 1 < min)
min = arr[i-1][j-1] + 1;
}
arr[i][j] = min;
}
}
return arr[len1][len2];
}
Which of the following lines should be inserted to complete the above code?
a) arr[i][j] = min
b) min = arr[i-1][j-1] – 1;
c) min = arr[i-1][j-1].
d) min = arr[i-1][j-1] + 1;
Answer: c
Explanation: The line min = arr[i-1][j-1] completes the above code.
6. What is the time complexity of the Wagner–Fischer algorithm where “m” and “n” are the lengths of the
two strings?
a) O(1)
b) O(n+m)
c) O(mn)
d) O(nlogm)
Answer: c
Explanation: The time complexity of the Wagner–Fischer algorithm is O(mn).
7. What is the space complexity of the above implementation of Wagner–Fischer algorithm where “m” and
“n” are the lengths of the two strings?
a) O(1)
b) O(n+m)
c) O(mn)
d) O(nlogm)
Answer: c
Explanation: The space complexity of the above Wagner–Fischer algorithm is O(mn).
#include<stdio.h>
#include<string.h>
int get_min(int a, int b)
{
if(a < b)
return a;
return b;
}
int edit_distance(char *s1, char *s2)
{
int len1,len2,i,j,min;
len1 = strlen(s1);
len2 = strlen(s2);
int arr[len1 + 1][len2 + 1];
for(i = 0;i <= len1; i++)
arr[i][0] = i;
for(i = 0; i <= len2; i++)
arr[0][i] = i;
for(i = 1; i <= len1; i++)
{
for(j = 1; j <= len2; j++)
{
min = get_min(arr[i-1][j],arr[i][j-1]) + 1;
if(s1[i - 1] == s2[j - 1])
{
if(arr[i-1][j-1] < min)
min = arr[i-1][j-1];
}
else
{
if(arr[i-1][j-1] + 1 < min)
min = arr[i-1][j-1] + 1;
}
arr[i][j] = min;
}
}
return arr[len1][len2];
}
int main()
{
char s1[] = "somestring", s2[] = "anotherthing";
int ans = edit_distance(s1, s2);
printf("%d",ans);
return 0;
}
a) 6
b) 7
c) 8
d) 9
Answer: a
Explanation: The program prints the edit distance between the strings “somestring” and “anotherthing”,
which is 6.
9. What is the value stored in arr[3][3] when the below code is executed?
#include<stdio.h>
#include<string.h>
int get_min(int a, int b)
{
if(a < b)
return a;
return b;
}
int edit_distance(char *s1, char *s2)
{
int len1,len2,i,j,min;
len1 = strlen(s1);
len2 = strlen(s2);
int arr[len1 + 1][len2 + 1];
for(i = 0;i <= len1; i++)
arr[i][0] = i;
for(i = 0; i <= len2; i++)
arr[0][i] = i;
for(i = 1; i <= len1; i++)
{
for(j = 1; j <= len2; j++)
{
min = get_min(arr[i-1][j],arr[i][j-1]) + 1;
if(s1[i - 1] == s2[j - 1])
{
if(arr[i-1][j-1] < min)
min = arr[i-1][j-1];
}
else
{
if(arr[i-1][j-1] + 1 < min)
min = arr[i-1][j-1] + 1;
}
arr[i][j] = min;
}
}
return arr[len1][len2];
}
int main()
{
char s1[] = "somestring", s2[] = "anotherthing";
int ans = edit_distance(s1, s2);
printf("%d",ans);
return 0;
}
a) 1
b) 2
c) 3
d) 4
Answer: c
Explanation: The value stored in arr[3][3] is 3.
#include<stdio.h>
#include<string.h>
int get_min(int a, int b)
{
if(a < b)
return a;
return b;
}
int edit_distance(char *s1, char *s2)
{
int len1,len2,i,j,min;
len1 = strlen(s1);
len2 = strlen(s2);
int arr[len1 + 1][len2 + 1];
for(i = 0;i <= len1; i++)
arr[i][0] = i;
for(i = 0; i <= len2; i++)
arr[0][i] = i;
for(i = 1; i <= len1; i++)
{
for(j = 1; j <= len2; j++)
{
min = get_min(arr[i-1][j],arr[i][j-1]) + 1;
if(s1[i - 1] == s2[j - 1])
{
if(arr[i-1][j-1] < min)
min = arr[i-1][j-1];
}
else
{
if(arr[i-1][j-1] + 1 < min)
min = arr[i-1][j-1] + 1;
}
arr[i][j] = min;
}
}
return arr[len1][len2];
}
int main()
{
char s1[] = "abcd", s2[] = "dcba";
int ans = edit_distance(s1, s2);
printf("%d",ans);
return 0;
}
a) 1
b) 2
c) 3
d) 4
Answer: d
Explanation: The program pr
Answer: d
Explanation: Catalan numbers are given by: (2n!)/((n+1)!n!).
For n = 0, we get C0 = 1.
For n = 3, we get C3 = 5.
For n = 4, we get C4 = 14.
For n = 5, we get C3 = 42.
Answer: d
Explanation: Catalan numbers are given by: (2n!)/((n+1)!n!).
First Catalan number is given by n = 0.
So the 6th Catalan number will be given by n = 5, which is 42.
Answer: d
Explanation: Counting the number of Dyck words, Counting the number of expressions containing n pairs of
parenthesis, Counting the number of ways in which a convex polygon can be cut into triangles by
connecting vertices with straight lines are the applications of Catalan numbers where as creation of head and
tails for a given number of tosses is an application of Pascal’s triangle.
4. Which of the following methods can be used to find the nth Catalan number?
a) Recursion
b) Binomial coefficients
c) Dynamic programming
d) Recursion, Binomial Coefficients, Dynamic programming
Answer: d
Explanation: All of the mentioned methods can be used to find the nth Catalan number.
advertisement
#include<stdio.h>
int cat_number(int n)
{
int i,j,arr[n],k;
arr[0] = 1;
for(i = 1; i < n; i++)
{
arr[i] = 0;
for(j = 0,k = i - 1; j < i; j++,k--)
______________________;
}
return arr[n-1];
}
int main()
{
int ans, n = 8;
ans = cat_number(n);
printf("%d\n",ans);
return 0;
}
Answer: c
Explanation: The line arr[i] += arr[j] * arr[k] reflects the recursive formula Cn = ∑Ci*C(n-i).
6. Which of the following implementations of Catalan numbers has the smallest time complexity?
a) Dynamic programming
b) Binomial coefficients
c) Recursion
d) All have equal time complexity
Answer: b
Explanation: The time complexities are as follows:
Dynamic programming: O(n2)
Recursion: Exponential
Binomial coefficients: O(n).
#include<stdio.h>
int cat_number(int n)
{
int i,j,arr[n],k;
arr[0] = 1;
for(i = 1; i < n; i++)
{
arr[i] = 0;
for(j = 0,k = i - 1; j < i; j++,k--)
arr[i] += arr[j] * arr[k];
}
return arr[n-1];
}
int main()
{
int ans, n = 8;
ans = cat_number(n);
printf("%d\n",ans);
return 0;
}
a) 42
b) 132
c) 429
d) 1430
Answer: c
Explanation: The program prints the 8th Catalan number, which is 429.
8. Which of the following implementations of Catalan numbers has the largest space complexity(Don’t
consider the stack space)?
a) Dynamic programming
b) Binomial coefficients
c) Recursion
d) All have equal space complexities
Answer: a
Explanation: The space complexities are as follows:
Dynamic programming: O(n)
Recursion: O(1)
Binomial coefficients: O(1).
9. What will be the value stored in arr[5] when the following code is executed?
#include<stdio.h>
int cat_number(int n)
{
int i,j,arr[n],k;
arr[0] = 1;
for(i = 1; i < n; i++)
{
arr[i] = 0;
for(j = 0,k = i - 1; j < i; j++,k--)
arr[i] += arr[j] * arr[k];
}
return arr[n-1];
}
int main()
{
int ans, n = 10;
ans = cat_number(n);
printf("%d\n",ans);
return 0;
}
a) 14
b) 42
c) 132
d) 429
Answer: b
Explanation: The 6th Catalan number will be stored in arr[5], which is 42.
10. Which of the following errors will occur when the below code is executed?
#include<stdio.h>
int cat_number(int n)
{
int i,j,arr[n],k;
arr[0] = 1;
for(i = 1; i < n; i++)
{
arr[i] = 0;
for(j = 0,k = i - 1; j < i; j++,k--)
arr[i] += arr[j] * arr[k];
}
return arr[n-1];
}
int main()
{
int ans, n = 100;
ans = cat_number(n);
printf("%d\n",ans);
return 0;
}
a) Segmentation fault
b) Array size too large
c) Integer value out of range
d) Array index out of range
Answer: c
Explanatio
1. Which of the following methods can be used to solve the assembly line scheduling problem?
a) Recursion
b) Brute force
c) Dynamic programming
d) All of the mentioned
Answer: d
Explanation: All of the above mentioned methods can be used to solve the assembly line scheduling
problem.
2. What is the time complexity of the brute force algorithm used to solve the assembly line scheduling
problem?
a) O(1)
b) O(n)
c) O(n2)
d) O(2n)
Answer: d
Explanation: In the brute force algorithm, all the possible ways are calculated which are of the order of 2n.
3. In the dynamic programming implementation of the assembly line scheduling problem, how many lookup
tables are required?
a) 0
b) 1
c) 2
d) 3
Answer: c
Explanation: In the dynamic programming implementation of the assembly line scheduling problem, 2
lookup tables are required one for storing the minimum time and the other for storing the assembly line
number.
For the optimal solution which should be the starting assembly line?
a) Line 1
b) Line 2
c) All of the mentioned
d) None of the mentioned
Answer: b
Explanation: For the optimal solution, the starting assembly line is line 2.
advertisement
time_to_reach[2][3] = {{17, 2, 7}, {19, 4, 9}}
time_spent[2][4] = {{6, 5, 15, 7}, {5, 10, 11, 4}}
entry_time[2] = {8, 10}
exit_time[2] = {10, 7}
num_of_stations = 4
For the optimal solution, which should be the exit assembly line?
a) Line 1
b) Line 2
c) All of the mentioned
d) None of the mentioned
Answer: b
Explanation: For the optimal solution, the exit assembly line is line 2.
Answer: d
Explanation: The minimum time required is 43.
The path is S2,1 -> S1,2 -> S2,3 -> S2,4, where Si,j : i = line number, j = station number
#include<stdio.h>
int get_min(int a, int b)
{
if(a<b)
return a;
return b;
}
int minimum_time_required(int reach[][3],int spent[][4], int *entry, int *exit, int n)
{
int t1[n], t2[n],i;
t1[0] = entry[0] + spent[0][0];
t2[0] = entry[1] + spent[1][0];
for(i = 1; i < n; i++)
{
t1[i] = get_min(t1[i-1]+spent[0][i], t2[i-1]+reach[1][i-1]+spent[0][i]);
__________;
}
return get_min(t1[n-1]+exit[0], t2[n-1]+exit[1]);
}
Which of the following lines should be inserted to complete the above code?
a) t2[i] = get_min(t2[i-1]+spent[1][i], t1[i-1]+reach[0][i-1]+spent[1][i])
b) t2[i] = get_min(t2[i-1]+spent[1][i], t1[i-1]+spent[1][i])
c) t2[i] = get_min(t2[i-1]+spent[1][i], t1[i-1]+reach[0][i-1])
d) none of the mentioned
Answer: a
Explanation: The line t2[i] = get_min(t2[i-1]+spent[1][i], t1[i-1]+reach[0][i-1]+spent[1][i]) should be added
to complete the above code.
8. What is the time complexity of the above dynamic programming implementation of the assembly line
scheduling problem?
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
Answer: b
Explanation: The time complexity of the above dynamic programming implementation of the assembly line
scheduling problem is O(n).
9. What is the space complexity of the above dynamic programming implementation of the assembly line
scheduling problem?
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
Answer: b
Explanation: The space complexity of the above dynamic programming implementation of the assembly line
scheduling problem is O(n).
#include<stdio.h>
int get_min(int a, int b)
{
if(a<b)
return a;
return b;
}
int minimum_time_required(int reach[][3],int spent[][4], int *entry, int *exit, int n)
{
int t1[n], t2[n], i;
t1[0] = entry[0] + spent[0][0];
t2[0] = entry[1] + spent[1][0];
for(i = 1; i < n; i++)
{
t1[i] = get_min(t1[i-1]+spent[0][i], t2[i-1]+reach[1][i-1]+spent[0][i]);
t2[i] = get_min(t2[i-1]+spent[1][i], t1[i-1]+reach[0][i-1]+spent[1][i]);
}
return get_min(t1[n-1]+exit[0], t2[n-1]+exit[1]);
}
int main()
{
int time_to_reach[][3] = {{6, 1, 5},
{2, 4, 7}};
int time_spent[][4] = {{6, 5, 4, 7},
{5, 10, 2, 6}};
int entry_time[2] = {5, 6};
int exit_time[2] = {8, 9};
int num_of_stations = 4;
int ans = minimum_time_required(time_to_reach, time_spent,
entry_time, exit_time, num_of_stations);
printf("%d",ans);
return 0;
}
a) 32
b) 33
c) 34
d) 35
Answer: c
Explanation: The program prints the optimal time required to build the car chassis, which is 34.
11. What is the value stored in t1[2] when the following code is executed?
#include<stdio.h>
int get_min(int a, int b)
{
if(a<b)
return a;
return b;
}
int minimum_time_required(int reach[][3],int spent[][4], int *entry, int *exit, int n)
{
int t1[n], t2[n],i;
t1[0] = entry[0] + spent[0][0];
t2[0] = entry[1] + spent[1][0];
for(i = 1; i < n; i++)
{
t1[i] = get_min(t1[i-1]+spent[0][i], t2[i-1]+reach[1][i-1]+spent[0][i]);
t2[i] = get_min(t2[i-1]+spent[1][i], t1[i-1]+reach[0][i-1]+spent[1][i]);
}
return get_min(t1[n-1]+exit[0], t2[n-1]+exit[1]);
}
int main()
{
int time_to_reach[][3] = {{6, 1, 5},
{2, 4, 7}};
int time_spent[][4] = {{6, 5, 4, 7},
{5, 10, 2, 6}};
int entry_time[2] = {5, 6};
int exit_time[2] = {8, 9};
int num_of_stations = 4;
int ans = minimum_time_required(time_to_reach, time_spent,
entry_time, exit_time, num_of_stations);
printf("%d",ans);
return 0;
}
a) 16
b) 18
c) 20
d) 22
Answer: c
Explanation: The value stored in t1[2] when the above code is executed is 20.
12. What is the value stored in t2[3] when the following code is executed?
#include<stdio.h>
int get_min(int a, int b)
{
if(a<b)
return a;
return b;
}
int minimum_time_required(int reach[][3],int spent[][4], int *entry, int *exit, int n)
{
int t1[n], t2[n],i;
t1[0] = entry[0] + spent[0][0];
t2[0] = entry[1] + spent[1][0];
for(i = 1; i < n; i++)
{
t1[i] = get_min(t1[i-1]+spent[0][i], t2[i-1]+reach[1][i-1]+spent[0][i]);
t2[i] = get_min(t2[i-1]+spent[1][i], t1[i-1]+reach[0][i-1]+spent[1][i]);
}
return get_min(t1[n-1]+exit[0], t2[n-1]+exit[1]);
}
int main()
{
int time_to_reach[][3] = {{6, 1, 5},
{2, 4, 7}};
int time_spent[][4] = {{6, 5, 4, 7},
{5, 10, 2, 6}};
int entry_time[2] = {5, 6};
int exit_time[2] = {8, 9};
int num_of_stations = 4;
int ans = minimum_time_required(time_to_reach, time_spent,
entry_time, exit_time, num_of_stations);
printf("%d",ans);
return 0;
}
a) 19
b) 23
c) 25
d) 27
Answer: c
Explanation: The value stored in t2[3] when the above code is executed is 25.
13. What is the output of the following code?
#include<stdio.h>
int get_min(int a, int b)
{
if(a<b)
return a;
return b;
}
int minimum_time_required(int reach[][4],int spent[][5], int *entry, int *exit, int n)
{
int t1[n], t2[n], i;
t1[0] = entry[0] + spent[0][0];
t2[0] = entry[1] + spent[1][0];
for(i = 1; i < n; i++)
{
t1[i] = get_min(t1[i-1]+spent[0][i], t2[i-1]+reach[1][i-1]+spent[0][i]);
t2[i] = get_min(t2[i-1]+spent[1][i], t1[i-1]+reach[0][i-1]+spent[1][i]);
}
return get_min(t1[n-1]+exit[0], t2[n-1]+exit[1]);
}
int main()
{
int time_to_reach[][4] = {{16, 10, 5, 12},
{12, 4, 17, 8}};
int time_spent[][5] = {{13, 5, 20, 19, 9},
{15, 10, 12, 16, 13}};
int entry_time[2] = {12, 9};
int exit_time[2] = {10, 13};
int num_of_stations = 5;
int ans = minimum_time_required(time_to_reach, time_spent,
entry_time, exit_time, num_of_stations);
printf("%d",ans);
return 0;
}
a) 62
b) 69
c) 75
d) 88
Answer: d
Explanation: The program prints th
1. Given a string, you have to find the minimum number of characters to be inserted in the string so that the
string becomes a palindrome. Which of the following methods can be used to solve the problem?
a) Greedy algorithm
b) Recursion
c) Dynamic programming
d) Both recursion and dynamic programming
Answer: d
Explanation: Dynamic programming and recursion can be used to solve the problem.
2. In which of the following cases the minimum no of insertions to form palindrome is maximum?
a) String of length one
b) String with all same characters
c) Palindromic string
d) Non palindromic string
Answer: d
Explanation: In string of length one, string with all same characters and a palindromic string the no of
insertions is zero since the strings are already palindromes. To convert a non-palindromic string to a
palindromic string, the minimum length of string to be added is 1 which is greater than all the other above
cases. Hence the minimum no of insertions to form palindrome is maximum in non-palindromic strings.
3. In the worst case, the minimum number of insertions to be made to convert the string into a palindrome is
equal to the length of the string.
a) True
b) False
Answer: b
Explanation: In the worst case, the minimum number of insertions to be made to convert the string into a
palindrome is equal to length of the string minus one. For example, consider the string “abc”. The string can
be converted to “abcba” by inserting “a” and “b”. The number of insertions is two, which is equal to length
minus one.
4. Consider the string “efge”. What is the minimum number of insertions required to make the string a
palindrome?
a) 0
b) 1
c) 2
d) 3
Answer: b
Explanation: The string can be converted to “efgfe” by inserting “f” or to “egfge” by inserting “g”. Thus,
only one insertion is required.
5. Consider the string “abbccbba”. What is the minimum number of insertions required to make the string a
palindrome?
a) 0
b) 1
c) 2
d) 3
Answer: a
Explanation: The given string is already a palindrome. So, no insertions are required.
6. Which of the following problems can be used to solve the minimum number of insertions to form a
palindrome problem?
a) Minimum number of jumps problem
b) Longest common subsequence problem
c) Coin change problem
d) Knapsack problems
Answer: b
Explanation: A variation of longest common subsequence can be used to solve the minimum number of
insertions to form a palindrome problem.
7. Consider the following dynamic programming implementation:
advertisement
#include<stdio.h>
#include<string.h>
int max(int a, int b)
{
if(a > b)
return a;
return b;
}
int min_ins(char *s)
{
int len = strlen(s), i, j;
int arr[len + 1][len + 1];
char rev[len + 1];
strcpy(rev, s);
strrev(rev);
for(i = 0;i <= len; i++)
arr[i][0] = 0;
for(i = 0; i <= len; i++)
arr[0][i] = 0;
for(i = 1; i <= len; i++)
{
for(j = 1; j <= len; j++)
{
if(s[i - 1] == rev[j - 1])
arr[i][j] = arr[i - 1][j - 1] + 1;
else
arr[i][j] = max(arr[i - 1][j], arr[i][j - 1]);
}
}
return _____________;
}
int main()
{
char s[] = "abcda";
int ans = min_ins(s);
printf("%d",ans);
return 0;
}
Answer: d
Explanation: arr[len][len] contains the length of the longest palindromic subsequence. So, len – arr[len][len]
gives the minimum number of insertions required to form a palindrome.
8. What is the time complexity of the following dynamic programming implementation of the minimum
number of insertions to form a palindrome problem?
#include<stdio.h>
#include<string.h>
int max(int a, int b)
{
if(a > b)
return a;
return b;
}
int min_ins(char *s)
{
int len = strlen(s), i, j;
int arr[len + 1][len + 1];
char rev[len + 1];
strcpy(rev, s);
strrev(rev);
for(i = 0;i <= len; i++)
arr[i][0] = 0;
for(i = 0; i <= len; i++)
arr[0][i] = 0;
for(i = 1; i <= len; i++)
{
for(j = 1; j <= len; j++)
{
if(s[i - 1] == rev[j - 1])
arr[i][j] = arr[i - 1][j - 1] + 1;
else
arr[i][j] = max(arr[i - 1][j], arr[i][j - 1]);
}
}
return len - arr[len][len];
}
int main()
{
char s[] = "abcda";
int ans = min_ins(s);
printf("%d",ans);
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(mn)
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 of the minimum
number of insertions to form a palindrome problem?
#include<stdio.h>
#include<string.h>
int max(int a, int b)
{
if(a > b)
return a;
return b;
}
int min_ins(char *s)
{
int len = strlen(s), i, j;
int arr[len + 1][len + 1];
char rev[len + 1];
strcpy(rev, s);
strrev(rev);
for(i = 0;i <= len; i++)
arr[i][0] = 0;
for(i = 0; i <= len; i++)
arr[0][i] = 0;
for(i = 1; i <= len; i++)
{
for(j = 1; j <= len; j++)
{
if(s[i - 1] == rev[j - 1])
arr[i][j] = arr[i - 1][j - 1] + 1;
else
arr[i][j] = max(arr[i - 1][j], arr[i][j - 1]);
}
}
return len - arr[len][len];
}
int main()
{
char s[] = "abcda";
int ans = min_ins(s);
printf("%d",ans);
return 0;
}
a) O(1)
b) O(n)
c) O(n2)
d) O(mn)
Answer: c
Explanation: The space complexity of the above dynamic programming implementation is O(n2).
#include<stdio.h>
#include<string.h>
int max(int a, int b)
{
if(a > b)
return a;
return b;
}
int min_ins(char *s)
{
int len = strlen(s), i, j;
int arr[len + 1][len + 1];
char rev[len + 1];
strcpy(rev, s);
strrev(rev);
for(i = 0;i <= len; i++)
arr[i][0] = 0;
for(i = 0; i <= len; i++)
arr[0][i] = 0;
for(i = 1; i <= len; i++)
{
for(j = 1; j <= len; j++)
{
if(s[i - 1] == rev[j - 1])
arr[i][j] = arr[i - 1][j - 1] + 1;
else
arr[i][j] = max(arr[i - 1][j], arr[i][j - 1]);
}
}
return len - arr[len][len];
}
int main()
{
char s[] = "abcda";
int ans = min_ins(s);
printf("%d",ans);
return 0;
}
a) 1
b) 2
c) 3
d) 4
Answer: b
Explanation: The length of the longest palindromic subsequence is 3. So, the output will be 5 – 3 = 2.
11. What is the value stored in arr[2][4] when the following code is executed?
#include<stdio.h>
#include<string.h>
int max(int a, int b)
{
if(a > b)
return a;
return b;
}
int min_ins(char *s)
{
int len = strlen(s), i, j;
int arr[len + 1][len + 1];
char rev[len + 1];
strcpy(rev, s);
strrev(rev);
for(i = 0;i <= len; i++)
arr[i][0] = 0;
for(i = 0; i <= len; i++)
arr[0][i] = 0;
for(i = 1; i <= len; i++)
{
for(j = 1; j <= len; j++)
{
if(s[i - 1] == rev[j - 1])
arr[i][j] = arr[i - 1][j - 1] + 1;
else
arr[i][j] = max(arr[i - 1][j], arr[i][j - 1]);
}
}
return len - arr[len][len];
}
int main()
{
char s[] = "abcda";
int ans = min_ins(s);
printf("%d",ans);
return 0;
}
a) 2
b) 3
c) 4
d) 5
Answer: a
Explanation: The value stored in arr[2][4] when the above code is executed is 2.
a) 0
b) 2
c) 4
d) 6
Answer: a
Explanation: Since the str
1. Given a 2D matrix, find a submatrix that has the maximum sum. Which of the following methods can be
used to solve this problem?
a) Brute force
b) Recursion
c) Dynamic programming
d) Brute force, Recursion, Dynamic programming
Answer: d
Explanation: Brute force, Recursion and Dynamic programming can be used to find the submatrix that has
the maximum sum.
2. In which of the following cases, the maximum sum rectangle is the 2D matrix itself?
a) When all the elements are negative
b) When all the elements are positive
c) When some elements are positive and some negative
d) When diagonal elements are positive and rest are negative
Answer: a
Explanation: When all the elements of a matrix are positive, the maximum sum rectangle is the 2D matrix
itself.
3. Consider the following statements and select which of the following statement are true.
Statement 1: The maximum sum rectangle can be 1X1 matrix containing the largest element If the matrix
size is 1X1
Statement 2: The maximum sum rectangle can be 1X1 matrix containing the largest element If all the
elements are zero
Statement 3: The maximum sum rectangle can be 1X1 matrix containing the largest element If all the
elements are negative
a) Only statement 1 is correct
b) Only statement 1 and Statement 2 are correct
c) Only statement 1 and Statement 3 are correct
d) Statement 1, Statement 2 and Statement 3 are correct
Answer: d
Explanation: If the matrix size is 1×1 then the element itself is the maximum sum of that 1×1 matrix. If all
elements are zero, then the sum of any submatrix of the given matrix is zero. If all elements are negative,
then the maximum element in that matrix is the highest sum in that matrix which is again 1X1 submatrix of
the given matrix. Hence all three statements are correct.
4. Consider a matrix in which all the elements are non-zero(at least one positive and at least one negative
element). In this case, the sum of the elements of the maximum sum rectangle cannot be zero.
a) True
b) False
Answer: a
Explanation: If a matrix contains all non-zero elements with at least one positive and at least on negative
element, then the sum of elements of the maximum sum rectangle cannot be zero.
5. Consider the 2×3 matrix {{1,2,3},{1,2,3}}. What is the sum of elements of the maximum sum rectangle?
a) 3
b) 6
c) 12
d) 18
Answer: c
Explanation: Since all the elements of the 2×3 matrix are positive, the maximum sum rectangle is the matrix
itself and the sum of elements is 12.
6. Consider the 2×2 matrix {{-1,-2},{-3,-4}}. What is the sum of elements of the maximum sum rectangle?
a) 0
b) -1
c) -7
d) -12
Answer: b
Explanation: Since all the elements of the 2×2 matrix are negative, the maximum sum rectangle is {-1}, a
1×1 matrix containing the largest element. The sum of elements of the maximum sum rectangle is -1.
7. Consider the 3×3 matrix {{2,1,-3},{6,3,4},{-2,3,0}}. What is the sum of the elements of the maximum
sum rectangle?
a) 13
b) 16
c) 14
d) 19
Answer: c
Explanation: The complete matrix represents the maximum sum rectangle and it’s sum is 14.
advertisement
8. What is the time complexity of the brute force implementation of the maximum sum rectangle problem?
a) O(n)
b) O(n2)
c) O(n3)
d) O(n4)
Answer: d
Explanation: The time complexity of the brute force implementation of the maximum sum rectangle
problem is O(n4).
9. The dynamic programming implementation of the maximum sum rectangle problem uses which of the
following algorithm?
a) Hirschberg’s algorithm
b) Needleman-Wunsch algorithm
c) Kadane’s algorithm
d) Wagner Fischer algorithm
Answer: c
Explanation: The dynamic programming implementation of the maximum sum rectangle problem uses
Kadane’s algorithm.
Which of the following lines should be inserted to complete the above code?
a) val = mx_sm
b) return val
c) mx_sm = val
d) return mx_sm
Answer: c
Explanation: The line “mx_sm = val” should be inserted to complete the above code.
11. What is the time complexity of the following dynamic programming implementation of the maximum
sum rectangle problem?
a) O(row*col)
b) O(row)
c) O(col)
d) O(row*col*col)
Answer: d
Explanation: The time complexity of the above dynamic programming implementation of the maximum sum
rectangle is O(row*col*col).
12. What is the space complexity of the following dynamic programming implementation of the maximum
sum rectangle problem?
a) O(row*col)
b) O(row)
c) O(col)
d) O(row*col*col)
Answer: b
Explanation: The space complexity of the above dynamic programming implementation of the maximum
sum rectangle problem is O(row).
#include<stdio.h>
#include<limits.h>
int max_num(int a, int b)
{
if(a > b)
return a;
return b;
}
int kadane_algo(int *arr, int len)
{
int ans, sum, idx;
ans =0;
sum =0;
for(idx =0; idx < len; idx++)
{
sum = max_num(0,sum + arr[idx]);
ans = max_num(sum,ans);
}
return ans;
}
int max_sum_rectangle(int arr[][5],int row,int col)
{
int left, right, tmp[row], mx_sm = INT_MIN, idx, val;
for(left = 0; left < col; left++)
{
for(right = left; right < col; right++)
{
if(right == left)
{
for(idx = 0; idx < row; idx++)
tmp[idx] = arr[idx][right];
}
else
{
for(idx = 0; idx < row; idx++)
tmp[idx] += arr[idx][right];
}
val = kadane_algo(tmp,row);
if(val > mx_sm)
mx_sm = val;
}
}
return mx_sm;
}
int main()
{
int arr[2][5] ={{1, 2, -1, -4, -20}, {-4, -1, 1, 7, -6}};
int row = 2, col = 5;
int ans = max_sum_rectangle(arr,row,col);
printf("%d",ans);
return 0;
}
a) 7
b) 8
c) 9
d) 10
Answer: b
Explanation: The program prints the sum of elements of the maximum sum rectangle, which is 8.
#include<stdio.h>
#include<limits.h>
int max_num(int a, int b)
{
if(a > b)
return a;
return b;
}
int kadane_algo(int *arr, int len)
{
int ans, sum, idx;
ans =0;
sum =0;
for(idx =0; idx < len; idx++)
{
sum = max_num(0,sum + arr[idx]);
ans = max_num(sum,ans);
}
return ans;
}
int max_sum_rectangle(int arr[][5],int row,int col)
{
int left, right, tmp[row], mx_sm = INT_MIN, idx, val=0;
for(left = 0; left < col; left++)
{
for(right = left; right < col; right++)
{
if(right == left)
{
for(idx = 0; idx < row; idx++)
tmp[idx] = arr[idx][right];
}
else
{
for(idx = 0; idx < row; idx++)
tmp[idx] += arr[idx][right];
}
val = kadane_algo(tmp,row);
if(val > mx_sm)
mx_sm = val;
}
}
return mx_sm;
}
int main()
{
int arr[4][5] ={{ 7, 1, -3, -6, -15},
{ 10, -6, 3, -4, 11},
{ -2, -3, -1, 2, -5},
{ 3, 0, 1, 0, 3}};
int row = 4, col = 5;
int ans = max_sum_rectangle(arr,row,col);
printf("%d",ans);
return 0;
}
a) 17
b) 18
c) 19
d) 20
Answer: b
Explanation: The pr
1. Given an array, check if the array can be divided into two subsets such that the sum of elements of the two
subsets is equal. This is the balanced partition problem. Which of the following methods can be used to
solve the balanced partition problem?
a) Dynamic programming
b) Recursion
c) Brute force
d) Dynamic programming, Recursion, Brute force
Answer: d
Explanation: All of the mentioned methods can be used to solve the balanced partition problem.
2. In which of the following cases, it is not possible to have two subsets with equal sum?
a) When the number of elements is odd
b) When the number of elements is even
c) When the sum of elements is odd
d) When the sum of elements is even
Answer: c
Explanation: When the sum of all the elements is odd, it is not possible to have two subsets with equal sum.
3. What is the time complexity of the brute force algorithm used to solve the balanced partition problem?
a) O(1)
b) O(n)
c) O(n2)
d) O(2n)
Answer: d
Explanation: In the brute force implementation, all the possible subsets will be formed. This takes
exponential time.
4. Consider a variation of the balanced partition problem in which we find two subsets such that |S1 – S2| is
minimum. Consider the array {1, 2, 3, 4, 5}. Which of the following pairs of subsets is an optimal solution
for the above problem?
a) {5, 4} & {3, 2, 1}
b) {5} & {4, 3, 2, 1}
c) {4, 2} & {5, 3, 1}
d) {5, 3} & {4, 2, 1}
Answer: d
Explanation: For S1 = {5, 3} and S2 = {4, 2, 1}, sum(S1) – sum(S2) = 1, which is the optimal solution.
#include<stdio.h>
int balanced_partition(int *arr, int len)
{
int sm = 0, i, j;
for(i = 0;i < len; i++)
sm += arr[i];
if(sm % 2 != 0)
return 0;
int ans[sm/2 + 1][len + 1];
for(i = 0; i <= len; i++)
ans[0][i] = 1;
for(i = 1; i <= sm/2; i++)
ans[i][0] = 0;
for(i = 1; i <= sm/2; i++)
{
for(j = 1;j <= len; j++)
{
ans[i][j] = ans[i][j-1];
if(i >= arr[j - 1])
ans[i][j] = _______________;
}
}
return ans[sm/2][len];
}
int main()
{
int arr[] = {3, 4, 5, 6, 7, 1}, len = 6;
int ans = balanced_partition(arr,len);
if(ans == 0)
printf("false");
else
printf("true");
return 0;
}
Which of the following lines should be inserted to complete the above code?
a) ans[i – arr[j – 1]][j – 1]
b) ans[i][j]
c) ans[i][j] || ans[i – arr[j – 1]][j – 1]
d) ans[i][j] && ans[i – arr[j – 1]][j – 1]
Answer: c
Explanation: The line “ans[i][j] || ans[i – arr[j – 1]][j – 1]” completes the above code.
advertisement
6. What is the time complexity of the following dynamic programming implementation of the balanced
partition problem where “n” is the number of elements and “sum” is their sum?
#include<stdio.h>
int balanced_partition(int *arr, int len)
{
int sm = 0, i, j;
for(i = 0;i < len; i++)
sm += arr[i];
if(sm % 2 != 0)
return 0;
int ans[sm/2 + 1][len + 1];
for(i = 0; i <= len; i++)
ans[0][i] = 1;
for(i = 1; i <= sm/2; i++)
ans[i][0] = 0;
for(i = 1; i <= sm/2; i++)
{
for(j = 1;j <= len; j++)
{
ans[i][j] = ans[i][j-1];
if(i >= arr[j - 1])
ans[i][j] = ans[i][j] || ans[i - arr[j - 1]][j - 1];
}
}
return ans[sm/2][len];
}
int main()
{
int arr[] = {3, 4, 5, 6, 7, 1}, len = 6;
int ans = balanced_partition(arr,len);
if(ans == 0)
printf("false");
else
printf("true");
return 0;
}
a) O(sum)
b) O(n)
c) O(sum * n)
d) O(sum + n)
Answer: c
Explanation: The time complexity of the above dynamic programming implementation of the balanced
partition problem is O(sum * n).
7. What is the space complexity of the following dynamic programming implementation of the balanced
partition problem?
#include<stdio.h>
int balanced_partition(int *arr, int len)
{
int sm = 0, i, j;
for(i = 0;i < len; i++)
sm += arr[i];
if(sm % 2 != 0)
return 0;
int ans[sm/2 + 1][len + 1];
for(i = 0; i <= len; i++)
ans[0][i] = 1;
for(i = 1; i <= sm/2; i++)
ans[i][0] = 0;
for(i = 1; i <= sm/2; i++)
{
for(j = 1;j <= len; j++)
{
ans[i][j] = ans[i][j-1];
if(i >= arr[j - 1])
ans[i][j] = ans[i][j] || ans[i - arr[j - 1]][j - 1];
}
}
return ans[sm/2][len];
}
int main()
{
int arr[] = {3, 4, 5, 6, 7, 1}, len = 6;
int ans = balanced_partition(arr,len);
if(ans == 0)
printf("false");
else
printf("true");
return 0;
}
a) O(sum)
b) O(n)
c) O(sum * n)
d) O(sum + n)
Answer: c
Explanation: The space complexity of the above dynamic programming implementation of the balanced
partition problem is O(sum * n).
#include<stdio.h>
int balanced_partition(int *arr, int len)
{
int sm = 0, i, j;
for(i = 0;i < len; i++)
sm += arr[i];
if(sm % 2 != 0)
return 0;
int ans[sm/2 + 1][len + 1];
for(i = 0; i <= len; i++)
ans[0][i] = 1;
for(i = 1; i <= sm/2; i++)
ans[i][0] = 0;
for(i = 1; i <= sm/2; i++)
{
for(j = 1;j <= len; j++)
{
ans[i][j] = ans[i][j-1];
if(i >= arr[j - 1])
ans[i][j] = ans[i][j] || ans[i - arr[j - 1]][j - 1];
}
}
return ans[sm/2][len];
}
int main()
{
int arr[] = {3, 4, 5, 6, 7, 1}, len = 6;
int ans = balanced_partition(arr,len);
if(ans == 0)
printf("false");
else
printf("true");
return 0;
}
a) True
b) False
Answer: a
Explanation: The partitions are S1 = {6, 7} and S2 = {1, 3, 4, 5} and the sum of each partition is 13. So, the
array can be divided into balanced partitions.
9. What is the value stored in ans[3][3] when the following code is executed?
#include<stdio.h>
int balanced_partition(int *arr, int len)
{
int sm = 0, i, j;
for(i = 0;i < len; i++)
sm += arr[i];
if(sm % 2 != 0)
return 0;
int ans[sm/2 + 1][len + 1];
for(i = 0; i <= len; i++)
ans[0][i] = 1;
for(i = 1; i <= sm/2; i++)
ans[i][0] = 0;
for(i = 1; i <= sm/2; i++)
{
for(j = 1;j <= len; j++)
{
ans[i][j] = ans[i][j-1];
if(i >= arr[j - 1])
ans[i][j] = ans[i][j] || ans[i - arr[j - 1]][j - 1];
}
}
return ans[sm/2][len];
}
int main()
{
int arr[] = {3, 4, 5, 6, 7, 1}, len = 6;
int ans = balanced_partition(arr,len);
if(ans == 0)
printf("false");
else
printf("true");
return 0;
}
a) 0
b) 1
c) -1
d) -2
Answer: b
Explanation: The value stored in ans[3][3] indicates if a sum of 3 can be obtained using a subset of the first
3 elements. Since the sum can be obtained the value stored is 1.
10. What is the sum of each of the balanced partitions for the array {5, 6, 7, 10, 3, 1}?
a) 16
b) 32
c) 0
d) 64
Answer: a
Explanation: The sum of all the elements of the array is 32. So, the sum of all the elements of each partition
should be 16.
#include<stdio.h>
int balanced_partition(int *arr, int len)
{
int sm = 0, i, j;
for(i = 0;i < len; i++)
sm += arr[i];
if(sm % 2 != 0)
return 0;
int ans[sm/2 + 1][len + 1];
for(i = 0; i <= len; i++)
ans[0][i] = 1;
for(i = 1; i <= sm/2; i++)
ans[i][0] = 0;
for(i = 1; i <= sm/2; i++)
{
for(j = 1;j <= len; j++)
{
ans[i][j] = ans[i][j-1];
if(i >= arr[j - 1])
ans[i][j] = ans[i][j] || ans[i - arr[j - 1]][j - 1];
}
}
return ans[sm/2][len];
}
int main()
{
int arr[] = {5, 6, 7, 10, 3, 1}, len = 6;
int ans = balanced_partition(arr,len);
if(ans == 0)
printf("false");
else
printf("true");
return 0;
}
a) True
b) False
Answer: a
Explanation: The array can be divided into two partitions S1 = {10, 6} and S2 = {5, 7, 3, 1} and the sum of
all the elements of each partition is 16. So, the answer is true.
a) True
b) False
Answer: b
Explanation: Since the sum of all the elemen
1. You are given n dice each having f faces. You have to find the number of ways in which a sum of S can
be achieved. This is the dice throw problem. Which of the following methods can be used to solve the dice
throw problem?
a) Brute force
b) Recursion
c) Dynamic programming
d) Brute force, Recursion and Dynamic Programming
Answer: d
Explanation: Brute force, Recursion and Dynamic Programming can be used to solve the dice throw
problem.
2. You have n dice each having f faces. What is the number of permutations that can be obtained when you
roll the n dice together?
a) n*n*n…f times
b) f*f*f…n times
c) n*n*n…n times
d) f*f*f…f times
Answer: b
Explanation: Each die can take f values and there are n dice. So, the total number of permutations is f*f*f…
n times.
3. You have 3 dice each having 6 faces. What is the number of permutations that can be obtained when you
roll the 3 dice together?
a) 27
b) 36
c) 216
d) 81
Answer: c
Explanation: The total number of permutations that can be obtained is 6 * 6 * 6 = 216.
4. You have 2 dice each of them having 6 faces numbered from 1 to 6. What is the number of ways in which
a sum of 11 can be achieved?
a) 0
b) 1
c) 2
d) 3
Answer: c
Explanation: The sum of 11 can be achieved when the dice show {6, 5} or {5, 6}.
5. There are n dice with f faces. The faces are numbered from 1 to f. What is the minimum possible sum that
can be obtained when the n dice are rolled together?
a) 1
b) f
c) n
d) n*f
Answer: c
Explanation: The sum will be minimum when all the faces show a value 1. The sum in this case will be n.
6. There are n dice with f faces. The faces are numbered from 1 to f. What is the maximum possible sum that
can be obtained when the n dice are rolled together?
a) 1
b) f*f
c) n*n
d) n*f
Answer: d
Explanation: The sum will be maximum when all the faces show a value f. The sum in this case will be n*f.
7. There are 10 dice having 5 faces. The faces are numbered from 1 to 5. What is the number of ways in
which a sum of 4 can be achieved?
a) 0
b) 2
c) 4
d) 8
Answer: a
Explanation: Since there are 10 dice and the minimum value each die can take is 1, the minimum possible
sum is 10. Hence, a sum of 4 cannot be achieved.
advertisement
8. Consider the following dynamic programming implementation of the dice throw problem:
#include<stdio.h>
int get_ways(int num_of_dice, int num_of_faces, int S)
{
int arr[num_of_dice + 1][S + 1];
int dice, face, sm;
for(dice = 0; dice <= num_of_dice; dice++)
for(sm = 0; sm <= S; sm++)
arr[dice][sm] = 0;
for(sm = 1; sm <= S; sm++)
arr[1][sm] = 1;
for(dice = 2; dice <= num_of_dice; dice++)
{
for(sm = 1; sm <= S; sm++)
{
for(face = 1; face <= num_of_faces && face < sm; face++)
arr[dice][sm] += arr[dice - 1][sm - face];
}
}
return _____________;
}
int main()
{
int num_of_dice = 3, num_of_faces = 4, sum = 6;
int ans = get_ways(num_of_dice, num_of_faces, sum);
printf("%d",ans);
return 0;
}
Which of the following lines should be added to complete the above code?
a) arr[num_of_dice][S]
b) arr[dice][sm]
c) arr[dice][S]
d) arr[S][dice]
Answer: a
Explanation: The line arr[num_of_dice][S] completes the above code.
9. What is time complexity of the following dynamic programming implementation of the dice throw
problem where f is the number of faces, n is the number of dice and s is the sum to be found?
#include<stdio.h>
int get_ways(int num_of_dice, int num_of_faces, int S)
{
int arr[num_of_dice + 1][S + 1];
int dice, face, sm;
for(dice = 0; dice <= num_of_dice; dice++)
for(sm = 0; sm <= S; sm++)
arr[dice][sm] = 0;
for(sm = 1; sm <= S; sm++)
arr[1][sm] = 1;
for(dice = 2; dice <= num_of_dice; dice++)
{
for(sm = 1; sm <= S; sm++)
{
for(face = 1; face <= num_of_faces && face < sm; face++)
arr[dice][sm] += arr[dice - 1][sm - face];
}
}
return arr[num_of_dice][S];
}
int main()
{
int num_of_dice = 3, num_of_faces = 4, sum = 6;
int ans = get_ways(num_of_dice, num_of_faces, sum);
printf("%d",ans);
return 0;
}
a) O(n*f)
b) O(f*s)
c) O(n*s)
d) O(n*f*s)
Answer: d
Explanation: The time complexity of the above dynamic programming implementation is O(n*f*s).
10. What is space complexity of the following dynamic programming implementation of the dice throw
problem where f is the number of faces, n is the number of dice and s is the sum to be found?
#include<stdio.h>
int get_ways(int num_of_dice, int num_of_faces, int S)
{
int arr[num_of_dice + 1][S + 1];
int dice, face, sm;
for(dice = 0; dice <= num_of_dice; dice++)
for(sm = 0; sm <= S; sm++)
arr[dice][sm] = 0;
for(sm = 1; sm <= S; sm++)
arr[1][sm] = 1;
for(dice = 2; dice <= num_of_dice; dice++)
{
for(sm = 1; sm <= S; sm++)
{
for(face = 1; face <= num_of_faces && face < sm; face++)
arr[dice][sm] += arr[dice - 1][sm - face];
}
}
return arr[num_of_dice][S];
}
int main()
{
int num_of_dice = 3, num_of_faces = 4, sum = 6;
int ans = get_ways(num_of_dice, num_of_faces, sum);
printf("%d",ans);
return 0;
}
a) O(n*f)
b) O(f*s)
c) O(n*s)
d) O(n*f*s)
Answer: c
Explanation: The space complexity of the above dynamic programming implementation is O(n*s).
#include<stdio.h>
int get_ways(int num_of_dice, int num_of_faces, int S)
{
int arr[num_of_dice + 1][S + 1];
int dice, face, sm;
for(dice = 0; dice <= num_of_dice; dice++)
for(sm = 0; sm <= S; sm++)
arr[dice][sm] = 0;
for(sm = 1; sm <= S; sm++)
arr[1][sm] = 1;
for(dice = 2; dice <= num_of_dice; dice++)
{
for(sm = 1; sm <= S; sm++)
{
for(face = 1; face <= num_of_faces && face < sm; face++)
arr[dice][sm] += arr[dice - 1][sm - face];
}
}
return arr[num_of_dice][S];
}
int main()
{
int num_of_dice = 3, num_of_faces = 4, sum = 6;
int ans = get_ways(num_of_dice, num_of_faces, sum);
printf("%d",ans);
return 0;
}
a) 10
b) 12
c) 14
d) 16
Answer: a
Explanation: The output of the above code is 10.
12. What will be the value stored in arr[2][2] when the following code is executed?
#include<stdio.h>
int get_ways(int num_of_dice, int num_of_faces, int S)
{
int arr[num_of_dice + 1][S + 1];
int dice, face, sm;
for(dice = 0; dice <= num_of_dice; dice++)
for(sm = 0; sm <= S; sm++)
arr[dice][sm] = 0;
for(sm = 1; sm <= S; sm++)
arr[1][sm] = 1;
for(dice = 2; dice <= num_of_dice; dice++)
{
for(sm = 1; sm <= S; sm++)
{
for(face = 1; face <= num_of_faces && face < sm; face++)
arr[dice][sm] += arr[dice - 1][sm - face];
}
}
return arr[num_of_dice][S];
}
int main()
{
int num_of_dice = 3, num_of_faces = 4, sum = 6;
int ans = get_ways(num_of_dice, num_of_faces, sum);
printf("%d",ans);
return 0;
}
a) 0
b) 1
c) 2
d) 3
Answer: b
Explanation: The value stored in arr[2][2] is 1.
#include<stdio.h>
int get_ways(int num_of_dice, int num_of_faces, int S)
{
int arr[num_of_dice + 1][S + 1];
int dice, face, sm;
for(dice = 0; dice <= num_of_dice; dice++)
for(sm = 0; sm <= S; sm++)
arr[dice][sm] = 0;
for(sm = 1; sm <= S; sm++)
arr[1][sm] = 1;
for(dice = 2; dice <= num_of_dice; dice++)
{
for(sm = 1; sm <= S; sm++)
{
for(face = 1; face <= num_of_faces && face < sm; face++)
arr[dice][sm] += arr[dice - 1][sm - face];
}
}
return arr[num_of_dice][S];
}
int main()
{
int num_of_dice = 4, num_of_faces = 6, sum = 3;
int ans = get_ways(num_of_dice, num_of_faces, sum);
printf("%d",ans);
return 0;
}
a) 0
b) 1
c) 2
d) 3
Answer: a
Explanation: The minimum possible sum is 4. So, the output for sum = 3 is 0.
#include<stdio.h>
int get_ways(int num_of_dice, int num_of_faces, int S)
{
int arr[num_of_dice + 1][S + 1];
int dice, face, sm;
for(dice = 0; dice <= num_of_dice; dice++)
for(sm = 0; sm <= S; sm++)
arr[dice][sm] = 0;
for(sm = 1; sm <= S; sm++)
arr[1][sm] = 1;
for(dice = 2; dice <= num_of_dice; dice++)
{
for(sm = 1; sm <= S; sm++)
{
for(face = 1; face <= num_of_faces && face < sm; face++)
arr[dice][sm] += arr[dice - 1][sm - face];
}
}
return arr[num_of_dice][S];
}
int main()
{
int num_of_dice = 2, num_of_faces = 6, sum = 5;
int ans = get_ways(num_of_dice, num_of_faces, sum);
printf("%d",ans);
return 0;
}
a) 2
b) 3
c) 4
d) 5
Answer: c
Explanation: The output o
1. You are given a boolean expression which consists of operators &, | and ∧ (AND, OR and XOR) and
symbols T or F (true or false). You have to find the number of ways in which the symbols can be
parenthesized so that the expression evaluates to true. This is the boolean parenthesization problem. Which
of the following methods can be used to solve the problem?
a) Dynamic programming
b) Recursion
c) Brute force
d) Dynamic programming, Recursion and Brute force
Answer: d
Explanation: Dynamic programming, Recursion and Brute force can be used to solve the Boolean
parenthesization problem.
2. Consider the expression T & F | T. What is the number of ways in which the expression can be
parenthesized so that the output is T (true)?
a) 0
b) 1
c) 2
d) 3
Answer: c
Explanation: The expression can be parenthesized as T & (F | T) and (T & F) | T so that the output is T.
3. Consider the expression T & F ∧ T. What is the number of ways in which the expression can be
parenthesized so that the output is T (true)?
a) 0
b) 1
c) 2
d) 3
Answer: c
Explanation: The expression can be parenthesized as (T & F) ∧ T or T & (F ∧ T), so that the output is T.
4. Consider the expression T | F ∧ T. In how many ways can the expression be parenthesized so that the
output is F (false)?
a) 0
b) 1
c) 2
d) 3
Answer: b
Explanation: The expression can be parenthesized as (T | F) ∧ T, so that the output is F (false).
5. Which of the following gives the total number of ways of parenthesizing an expression with n + 1 terms?
a) n factorial
b) n square
c) n cube
d) nth catalan number
Answer: d
Explanation: The nth Catalan number gives the total number of ways of parenthesizing an expression with n
+ 1 terms.
advertisement
6. What is the maximum number of ways in which a boolean expression with n + 1 terms can be
parenthesized, such that the output is true?
a) nth catalan number
b) n factorial
c) n cube
d) n square
Answer: a
Explanation: The number of ways will be maximum when all the possible parenthesizations result in a true
value. The number of possible parenthesizations is given by the nth catalan number.
7. Consider the following dynamic programming implementation of the boolean parenthesization problem:
Which of the following lines should be added to complete the “if(op[pos] == ‘|’)” part of the code?
a) False[row][col] += True[row][pos] * False[pos+1][col];
True[row][col] += t_row_pos * t_pos_col + False[row][pos] * False[pos+1][col];
b) False[row][col] += False[row][pos] * True[pos+1][col];
True[row][col] += t_row_pos * t_pos_col – True[row][pos] * True[pos+1][col];
c) False[row][col] += True[row][pos] * True[pos+1][col];
True[row][col] += t_row_pos * t_pos_col + True[row][pos] * True[pos+1][col];
d) False[row][col] += False[row][pos] * False[pos+1][col];
True[row][col] += t_row_pos * t_pos_col – False[row][pos] * False[pos+1][col];
Answer: d
Explanation: The following lines should be added:
False[row][col] += False[row][pos] * False[pos+1][col];
True[row][col] += t_row_pos * t_pos_col + False[row][pos] * False[pos+1][col];
8. Which of the following lines should be added to complete the “if(op[k] == ‘&’)” part of the following
code?
Answer: b
Explanation: The following lines should be added:
True[row][col] += True[row][pos] * True[pos+1][col];
False[row][col] += t_row_pos * t_pos_col – True[row][pos] * True[pos+1][col];
9. What is the time complexity of the following dynamic programming implementation of the boolean
parenthesization problem?
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
Answer: d
Explanation: The time complexity of the above dynamic programming implementation is O(n3).
10. What is the space complexity of the following dynamic programming implementation of the boolean
parenthesization problem?
a) O(1)
b) O(n)
c) O(n2)
d) O(n3)
Answer: c
Explanation: The space complexity of the above dynamic programming implementation is O(n2).
#include<stdio.h>
#include<string.h>
int count_bool_parenthesization(char *sym, char *op)
{
int str_len = strlen(sym);
int True[str_len][str_len],False[str_len][str_len];
int row,col,length,l;
for(row = 0, col = 0; row < str_len; row++,col++)
{
if(sym[row] == 'T')
{
True[row][col] = 1;
False[row][col] = 0;
}
else
{
True[row][col] = 0;
False[row][col] = 1;
}
}
for(length = 1; length < str_len; length++)
{
for(row = 0, col = length; col < str_len; col++, row++)
{
True[row][col] = 0;
False[row][col] = 0;
for(l = 0; l < length; l++)
{
int pos = row + l;
int t_row_pos = True[row][pos] + False[row][pos];
int t_pos_col = True[pos+1][col] + False[pos+1][col];
if(op[pos] == '|')
{
False[row][col] += False[row][pos] * False[pos+1][col];
True[row][col] += t_row_pos * t_pos_col - False[row][pos] *
False[pos+1][col];
}
if(op[pos] == '&')
{
True[row][col] += True[row][pos] * True[pos+1][col];
False[row][col] += t_row_pos * t_pos_col - True[row][pos] *
True[pos+1][col];
}
if(op[pos] == '^')
{
True[row][col] += True[row][pos] * False[pos+1][col]
+ False[row][pos] * True[pos + 1][col];
False[row][col] += True[row][pos] * True[pos+1][col]
+ False[row][pos] * False[pos+1][col];
}
}
}
}
return True[0][str_len-1];
}
int main()
{
char sym[] = "TTTT";
char op[] = "|^^";
int ans = count_bool_parenthesization(sym,op);
printf("%d",ans);
return 0;
}
a) 1
b) 2
c) 3
d) 4
Answer: d
Explanation: The outpu
Answer: c
Explanation: Cipher is an algorithm for performing encryption or decryption. In cryptography, a set of
defined steps are followed to generate ciphers.
Answer: b
Explanation: There are two types of a traditional cipher. First is transposition cipher and the second is
substitution cipher.
3. Which of the following ciphers are created by shuffling the letters of a word?
a) substitution cipher
b) transposition cipher
c) vigenere cipher
d) hill cipher
Answer: b
Explanation: There are two types of traditional ciphers – Transposition and substitution cipher. In
transposition cipher the letters of the given data are shuffled in a particular order, fixed by a given rule.
Answer: a
Explanation: In substitution cipher the plain text is replaced by cipher text according to a fixed rule. There
are two types of substitution cipher – Mono alphabetic and Poly alphabetic cipher.
Answer:d
Explanation: In poly alphabetic cipher each symbol of plain text is replaced by a different cipher text
regardless of its occurrence. Out of the given options, only additive cipher is not a poly alphabetic cipher.
7. What will be the ciphered text for the input string “sanfoundry” with key string as “code” to the program
of keyword cipher?
a) SCMBNUMERY
b) SSCMBNUMERY
c) NIFO
d) NILO
Answer: a
Explanation: Keyword cipher is type of mono alphabetic cipher. In this algorithm the letters
{A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z} by
{C,O,D,E,A,B,F,G,H,I,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z} respectively.
Answer: a
Explanation: In transposition cipher the letters of the given data are shuffled in a particular order, fixed by a
given rule. There are two types of transposition cipher – Rail fence cipher and Columnar transposition
cipher.
#include<bits/stdc++.h>
using namespace std;
string encrypter(string keyword)
{
string encoded = "";
bool arr[26] = {0};
for (int i=0; i<keyword.size(); i++)
{
if(keyword[i] >= 'A' && keyword[i] <= 'Z')
{
if (arr[keyword[i]-65] == 0)
{
encoded += keyword[i];
arr[keyword[i]-65] = 1;
}
}
else if (keyword[i] >= 'a' && keyword[i] <= 'z')
{
if (arr[keyword[i]-97] == 0)
{
encoded += keyword[i] - 32;
alpha[keyword[i]-97] = 1;
}
}
}
for (int i=0; i<26; i++)
{
if(arr[i] == 0)
{
arr[i]=1;
encoded += char(i + 65);
}
}
return encoded;
}
string ciphertxt(string msg, string encoded)
{
string cipher="";
for (int i=0; i<msg.size(); i++)
{
if (msg[i] >='a' && msg[i] <='z')
{
int pos = msg[i] - 97;
cipher += encoded[pos];
}
else if (msg[i] >='A' && msg[i] <='Z')
{
int pos = msg[i] - 65;
cipher += encoded[pos];
}
else
{
cipher += msg[i];
}
}
return cipher;
}
int main()
{
string keyword;
keyword = "cipher";
string encoded = encrypter(keyword);
string message = "hello";
cout << ciphertxt(message,encoded) << endl;
return 0;
}
a) bejjm
b) LFPDAR
c) BEJJM
d) lfpdar
Answer: c
Explanation: The given code is the implementation of keyword cipher. It is an example of mono alphabetic
cipher. The given string is always converted into an uppercase ciphered text.
10. What will be output for the given code taking input string as “sanfoundry”?
package com.sanfoundry.setandstring;
import java.util.Scanner;
public class MonoalphabeticCipher
{
public static char p[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z' };
public static char ch[] = { 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P',
'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z',
'X', 'C', 'V', 'B', 'N', 'M' };
public static String doEncryption(String s)
{
char c[] = new char[(s.length())];
for (int i = 0; i < s.length(); i++)
{
for (int j = 0; j < 26; j++)
{
if (p[j] == s.charAt(i))
{
c[i] = ch[j];
break;
}
}
} return (new String(c));
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the message: ");
String en = doEncryption(sc.next().toLowerCase());
System.out.println("Encrypted message: " + en);
sc.close();
}
}
Answer: a
Explanation: The given code is an example of mono-alphabetic cipher. The code replaces the letters of the
input string by corresponding keyboard letters.
11. In which of the following cipher the plain text and the ciphered text does not have same number of
letters?
a) keyword cipher
b) vigenere cipher
c) transposition cipher
d) additive cipher
Answer: b
Explanation: In tran
Answer: c
Explanation: Cipher is an algorithm for performing encryption or decryption. In cryptography, a set of
defined steps are followed to generate ciphers. These are necessary to prevent data breach.
2. Which of the following ciphers are created by shuffling the letters of a word?
a) rotor cipher
b) rail fence cipher
c) vigenere cipher
d) hill cipher
Answer: b
Explanation: There are two types of traditional ciphers- Transposition and substitution cipher. In
transposition cipher the letters of the given data are shuffled in a particular order, fixed by a given rule. Rail
fence cipher is an example of transposition cipher.
Answer: a
Explanation: In substitution cipher the plain text is replaced by cipher text according to a fixed rule. There
are two types of substitution cipher- Mono alphabetic and Poly alphabetic cipher.
Answer: a
Explanation: Poly alphabetic cipher is a type of substitution cipher. It uses multiple substitution at different
positions in order to cipher the plain text.
Answer: d
Explanation: In poly alphabetic cipher each symbol of plain text is replaced by a different cipher text
regardless of its occurrence. Out of the given options, only affine cipher is not a poly alphabetic cipher.
advertisement
Answer: b
Explanation: There are two types of a traditional cipher. First is transposition cipher and the second is
substitution cipher.
Answer: a
Explanation: Mono alphabetic ciphers can be decoded by using the method frequency analysis. But in poly
alphabetic cipher each symbol of plain text is replaced by a different cipher text regardless of its occurrence.
This makes it very difficult to be decoded by using frequency analysis.
a) vigenere cipher
b) hill cipher
c) keyword cipher
d) rotor cipher
Answer: b
Explanation: The given function represents hill cipher. It is a type of poly alphabetic substitution which is
based on linear algebra.
a) vigenere cipher
b) hill cipher
c) keyword cipher
d) rotor cipher
Answer: a
Explanation: The given function represents the function of hill cipher. It is a type of poly alphabetic
substitution which makes use of the vigenere table for making substitutions in the plain text.
10. In which of the following cipher the plain text and the ciphered text does not have same number of
letters?
a) affine cipher
b) hill cipher
c) columnar cipher
d) additive cipher
Answer: b
Explanation: In transposition cipher and mono alphabetic cipher the number of letters remains the same in
ciphered and deciphered text. But in poly alphabetic cipher the number of letters are different. So here as hill
cipher is the only poly alphabetic cipher so it will be the answer.
11. What will be the ciphered text if the string “SANFOUNDRY” is given as input to the code of vigenere
cipher with keyword as “HELLO”?
a) UEWIIDKLL
b) ZEYQCOCM
c) ZEYQCBROCM
d) ZEYQCBROCMJDH
Answer: c
Explanation: Vigenere cipher is a type of poly alphabetic substitution which uses vigenere table for making
substitutions in the plain text. Using the table we find the solution to be ZEYQCBROCM.
12. What will be the ciphered text if the string “HELLO” is given as input to the code of hill cipher with
keyword as “SANFOUNDRY”?
a) EZJ
b) JEZ
c) ZEJ
d) JZE
Answer: d
Explanation: H
Answer: c
Explanation: Cipher can be defined to be an algorithm that performs encryption or decryption. In
cryptography, a set of defined steps are followed to generate ciphers.
Answer: b
Explanation: Types of traditional ciphers- Transposition and substitution cipher. In transposition cipher the
letters of the given message are shuffled in a particular order, fixed by a given rule.
Answer: c
Explanation: Out of the given options only One time pad cipher is not a type of transposition cipher. It is a
type of substitution cipher.
Answer: d
Explanation: In mono alphabetic cipher each symbol of plain text is replaced by a particular respective
symbol in the cipher text. There are three types of mono alphabetic ciphers- additive, multiplicative and
affine.
Answer: c
Explanation: Route cipher is a transposition cipher. It falls under the category of transposition cipher as it
encrypts the plain text by rearranging its letters.
advertisement
6. Which of the following ciphered text would have used transposition cipher for encryption of the plain text
“SANFOUNDRY”?
a) SSCMBNUMERY
b) TBMGPVOESZ
c) UCNHQWPFTA
d) SNONRAFUDY
Answer: d
Explanation: We know that transposition cipher encrypts the plain text by shuffling the letters of the plain
text. So out of the given options, only “SNONRAFUDY” has the same set of letters as “SANFOUNDRY”.
Answer: a
Explanation: In transposition cipher the letters of the given message are shuffled in a particular order, fixed
by a given rule. Two types of transposition cipher are – Rail fence cipher and Columnar transposition cipher.
8. In which of the following cipher the plain text and the ciphered text have same set of letters?
a) one time pad cipher
b) columnar transposition cipher
c) playfair cipher
d) additive cipher
Answer: b
Explanation: In transposition cipher, the letters remain same in ciphered and plain text. Their position is only
changed whereas in substitution cipher the letters become different in encrypted text. So columnar
transposition cipher will be the correct option.
Answer: a
Explanation: Combining transposition cipher with substitution cipher helps in overcoming its weaknesses.
But it causes the cipher to become more laborious to decode and it becomes more prone to errors.
10. What will be the encrypted text corresponding to plain text “SANFOUNDRY” using rail fence cipher
with key value given to be 2?
a) SNONRAFUDY
b) SORAFUDYNN
c) SNAUDNORFY
d) SANFOUNDRY
Answer: a
Explanation: For encrypting a plain text using rail fence cipher we use a table having a number of rows
equal to key value as shown below. Then we read along the rows to get the ciphered text. So the ciphered
text will be “SNONRAFUDY”.
11. What will be the encrypted text corresponding to plain text “SANFOUNDRY” using columnar
transposition cipher with the keyword as “GAMES”?
a) SNONRAFUDY
b) SORAFUDYNN
c) SNAUDNORFY
d) ANFRSUNDOY
Answer: d
Explanation: For encrypting using columnar cipher we have to arrange the letters of the plain text in a table
wh
Answer: d
Explanation: Pigpen cipher encrypts the plain text by replacing each letter with a corresponding symbol.
Pigpen cipher is an example of geometric substitution cipher.
Answer: a
Explanation: Pigpen cipher is also known by the names like:- freemason’s cipher, napoleon cipher, tic-tac-
toe cipher, masonic cipher. It is a cipher which is believed to be used by freemasons in the 18th century.
Answer: c
Explanation: Pigpen cipher is believed to be used by freemasons in the 18th century. Pigpen cipher is an
example of geometric substitution cipher.
Answer: d
Explanation: Pigpen cipher is the weakest cipher out of the given options. This is because it is a simple
geometric substitution cipher so can be easily cracked using frequency analysis.
5. Which of the following is not a poly alphabetic substitution cipher?
a) vigenere cipher
b) one time pad cipher
c) play fair cipher
d) pigpen cipher
Answer: d
Explanation: Pigpen cipher is the only non poly alphabetic substitution cipher out of the given options. It is
an example of geometric substitution cipher.
advertisement
Answer: a
Explanation: Pigpen cipher encrypts the plain text by replacing each letter with a corresponding symbol.
Pigpen cipher is an example of geometric substitution cipher.
Answer: a
Explanation: Vigenere cipher is more secure as compared to pigpen cipher. It is because pigpen cipher is
geometric substitution cipher and vigenere cipher is poly alphabetic substitution cipher.
Answer: b
Explanation: Pigpen cipher is a very weak cipher as it just replaces letters with corresponding symbols. It
can be easily broken using frequency analysis.
9. What will be the ciphered text corresponding to plain text “ACT” if pigpen cipher is used for encryption?
a) _| |_ >
b) |_ > |_
c) _| |_<
d) |_< _|
Answer: a
Explanation: Pigpen cipher replaces letters of the plain text with corresponding symbols. These symbols are
fragment of a grid.
10. What will be the plain text corresponding to ciphered text “|_ _| >” if pigpen cipher is used for
encryption?
a) cat
b) hat
c) dog
d) rat
Answer: a
Explanation: Pigpen cipher replaces letters of the plain text with corresponding symbols. So by using the
grid we can replace these symbols by their corresponding letters which are “cat” here.
Answer: c
Explanation: Both affin
Answer: c
Explanation: Cipher is an algorithm for performing encryption or decryption. In cryptography, a set of
defined steps are followed to generate ciphers. These are necessary to prevent data breach.
Answer: b
Explanation: Vigenere cipher is a substitution cipher. It falls under the category of poly alphabetic cipher as
it uses multiple substitution at different positions in order to cipher the plain text.
Answer: c
Explanation: Encryption of plain text using vigenre cipher is done by making use of vigenere table. It is also
known as vigenere square.
Answer: a
Explanation: Poly alphabetic cipher is a type of substitution cipher. It uses multiple substitution at different
positions in order to cipher the plain text.
Answer:d
Explanation: In poly alphabetic cipher each symbol of plain text is replaced by a different cipher text
regardless of its occurrence. Out of the given options only multiplicative cipher is not a poly alphabetic
cipher.
advertisement
Answer: a
Explanation: Encryption of plain text using vigenre cipher is done by making use of vigenere table. It
consists of 26 rows and 26 columns which have alphabets written 26 times. These are shifted towards left
after each row.
Answer: a
Explanation: Keyword cipher is less secure than vigenere cipher. It is due to the fact that keyword cipher is
mono alphabetic and thus can be cracked using frequency analysis. But vigenere cipher being a poly
alphabetic cipher cannot be deciphered using this method.
8. What will be the plain text corresponding to cipher text “PROTO” if vigenere cipher is used with
keyword as “HELLO”?
a) SANFOUNDRY
b) WORLD
c) INDIA
d) AMERICA
Answer: c
Explanation: Vigenere cipher is a type of poly alphabetic substitution which uses vigenere table for making
substitutions in the plain text. Using the table we find the plain text to be “INDIA”.
a) vigenere cipher
b) hill cipher
c) keyword cipher
d) rotor cipher
Answer: a
Explanation: The given function represents the function of hill cipher. It is a type of poly alphabetic
substitution which makes use of the vigenere table for making substitutions in the plain text.
10. In which of the following cipher the plain text and the ciphered text does not have a same number of
letters?
a) affine cipher
b) vigenere cipher
c) columnar cipher
d) additive cipher
Answer: b
Explanation: In transposition cipher and mono alphabetic cipher the number of letters remain same in
ciphered and deciphered text. But in poly alphabetic cipher the number of letters are different. So here as
vigenere cipher is the only poly alphabetic cipher so it will be the answer.
11. What will be the ciphered text if the string “SANFOUNDRY” is given as input to the code of vigenere
cipher with keyword as “HELLO”?
a) UEWIIDKLL
b) ZEYQCOCM
c) ZEYQCBROCM
d) ZEYQCBROCMJDH
Answer: c
Explanation: Vigenere cipher is a type of poly alphabetic substitution which uses vigenere table for making
substitution
1. Which of the following cipher does not require a key for encrypting plain text?
a) atbash cipher
b) affine cipher
c) playfair cipher
d) vigenere cipher
Answer: a
Explanation: Out of the given options only atbash cipher does not require a key for encryption. Atbash
cipher is an example of a substitution cipher.
Answer: c
Explanation: Atbash cipher was originally built to encrypt hebrew alphabet. But it can be used to encrypt
any type of alphabets.
Answer: c
Explanation: Atbash cipher is a special case of affine cipher. We have to assume a=b=25 as the key in affine
cipher to get the same encryption.
Answer: d
Explanation: Atbash cipher is the weakest cipher out of the given options. This is because it is a simple
mono alphabetic substitution cipher with almost no security. It can be cracked without even knowing which
technique has been used for encryption.
Answer: d
Explanation: Atbash cipher is the only mono alphabetic substitution cipher out of the given options. All the
remaining options fall under the category of poly alphabetic cipher.
advertisement
Answer: a
Explanation: Atbash cipher is an example of mono alphabetic substitution cipher. It replaces each alphabet
of the plain text with a corresponding letter which we can see in the table below.
A - Z J - Q S - H
B - Y K - P T - G
C - X L - O U - F
D - W M - N V - E
E - V N - M W - D
F - U O - L X - C
G - T P - K Y - B
H - S Q - J Z - A
I - R R - I
8. Atbash cipher cannot be cracked until the exact type of encryption of ciphered text is known.
a) True
b) False
Answer: b
Explanation: Atbash cipher is a very weak cipher. It can be easily broken without even knowing the exact
technique which has been used for encryption. We can just assume the ciphered text to be a substitution
cipher in order to crack it.
9. What will be the ciphered text corresponding to plain text “SECRET” if atbash cipher is used for
encryption?
a) VHIXVG
b) HVXIVG
c) HXVIVG
d) VIHXIV
Answer: b
Explanation: Atbash cipher replaces each alphabet of the plain text with a corresponding letter which we can
see in the table below.
A - Z J - Q S - H
B - Y K - P T - G
C - X L - O U - F
D - W M - N V - E
E - V N - M W - D
F - U O - L X - C
G - T P - K Y - B
H - S Q - J Z - A
I - R R - I
Answer: a
Explanation: Atbash cipher replaces each alphabet of the plain text with a corresponding letter which we can
see in the table below.
A - Z J - Q S - H
B - Y K - P T - G
C - X L - O U - F
D - W M - N V - E
E - V N - M W - D
F - U O - L X - C
G - T P - K Y - B
H - S Q - J Z - A
I - R R - I
Answer: b
Explanation: Atba
Answer: b
Explanation: Gronsfeld cipher is a substitution cipher. It falls under the category of poly alphabetic cipher as
it uses multiple substitutions at different positions in order to cipher the plain text.
Answer: b
Explanation: Encryption of plain text in gronsfeld cipher is done by shifting the letters of plain text on the
basis of key value. So it is similar to caesar cipher.
Answer: c
Explanation: In gronsfeld cipher we shift the letters of the plain text on the basis of the key value. So it
becomes a modified version of the caesar cipher.
Answer: a
Explanation: Gronsfeld cipher is a variation of vigenere cipher. The difference is that vigenere cipher uses
an alphabetical key whereas gronsfeld cipher uses numeric key.
5. Which of the following cipher does not require the use of tabula recta?
a) running key cipher
b) vigenere cipher
c) gronsfeld cipher
d) trithemius cipher
Answer: c
Explanation: Ciphers like running key cipher, vigenere cipher, trithemius cipher etc. makes use of tabula
recta. Whereas gronsfeld cipher does not require tabula recta for encryption of plain text.
advertisement
Answer: b
Explanation: Gronsfeld cipher is a variation of vigenere cipher. The difference is that vigenere cipher uses
an alphabetical key whereas the key of gronsfeld cipher consists of numbers.
Answer: a
Explanation: In gronsfeld cipher we shift the letters of the plain text on the basis of the key value. So it
becomes a more complex version of the caesar cipher and thus harder to crack.
8. What will be the plain text corresponding to cipher text “EETPEG” if gronsfeld cipher is used with key
“4321”?
a) ABACUS
b) ABROAD
c) ABRUPT
d) ABUSED
Answer: b
Explanation: Encryption in gronsfeld cipher takes place by shifting the letters of the plain text by a number
given by the numeric key. So by applying the reverse of this method, we get the deciphered text to be
“ABROAD”.
Answer: a
Explanation: Gronsfeld cipher is a type of substitution cipher. It is a variation of vigenere cipher.
Answer: b
Explanation: Rail fence, hill and route cipher are examples of transposition cipher. Gronsfeld cipher is a
substitution cipher and so is the correct option.
11. What will be the ciphered text corresponding to “SANFOUNDRY” if gronsfeld cipher is used for
encryption with key as “1234”?
a) TCQJPWQHSA
b) TCQJTAULAI
c) TCQJOUNDRY
d) UETNQYTLTC
Answer: a
Explanation: Encryption in gronsfeld cipher takes place by shifting the letters of the plain text by a number
given by the numeric key. So by applying this method, we get the ciphered text to be “TCQJPWQHSA”.
12. What will be the ciphered text corresponding to “ALGORITHM” if gronsfeld cipher is used for
encryption with key “4321”?
a) BNJSSKWLN
b) EOIPVLVIQ
c) BNJSRITHM
d) EOIPRITHM
Answer: b
Explanation: Encryption in gronsfeld cipher takes place by shifting the letters of the plain text by a number
given by the numeric key. So by applying this method, we get the ciphered text to be “EOIPVLVIQ”.
13. What will be the plain text corresponding to cipher text “SCEFJV” if gronsfeld cipher is used with key
“1234”?
a) RABBIT
b) RUSSIA
c) RANGER
d) FRIEND
Answer: a
Explanation: Encryption
Answer: b
Explanation: Beaufort cipher is a substitution cipher. It falls under the category of poly alphabetic cipher as
it uses multiple substitutions at different positions in order to cipher the plain text.
Answer: c
Explanation: Encryption of plain text in beaufort cipher is done by making use of tabula recta. The same
table is also used for encryption in vigenere cipher and running key cipher.
Answer: d
Explanation: A reciprocal cipher is a cipher in which if we try to encrypt the cipher text (using the same
cipher) then we gets the plain text as a result. In other words, the process of decryption and encryption is
exactly the same.
4. Which of the following is a difference between beaufort cipher and vigenere cipher?
a) they use different tables for encryption
b) vigenere cipher is poly alphabetic whereas beaufort cipher is mono alphabetic
c) vigenere cipher uses a key whereas no key is required for using beaufort cipher
d) they use the same table for encryption, but in a different manner
Answer: d
Explanation: Beaufort cipher is a variation of vigenere cipher. They use the same table i.e. tabula recta for
encryption but the table is used in a different manner.
Answer: b
Explanation: Beaufort cipher is a variant of vigenere cipher. The difference is that beaufort cipher uses
tabula recta in a different manner for encryption.
advertisement
Answer: a
Explanation: Beaufort cipher is an example of reciprocal cipher. So that is why the process of decryption is
exactly same as that of encryption in beaufort cipher.
7. What will be the plain text corresponding to cipher text “SEDGKG” if beaufort cipher is used with key as
“KEY”?
a) PRISON
b) DEATHS
c) SAVEUS
d) ABUSED
Answer: c
Explanation: The process of decryption and encryption are exactly the same in beaufort cipher. So the
corresponding plain text would be “SAVEUS”.
Answer: b
Explanation: Beaufort cipher is different from variant beaufort cipher. Variant beaufort cipher is a variant of
beaufort cipher.
9. What will be the ciphered text corresponding to “SANFOUNDRY” if beaufort cipher is used for
encryption with key as “KEY”?
a) SBPISZTKZH
b) TCQJTAULAI
c) SELFQEXBHM
d) SPBISZKTZH
Answer: c
Explanation: For encrypting plain text choose the first letter of plain text (i.e. S) in the first horizontal row.
Then find the first letter of key (i.e. K) in the column obtained in the first step. Finally, choose the leftmost
letter of the row (i.e. S) obtained in the previous step. So the corresponding cipher text is “SELFQEXBHM”.
10. What will be the ciphered text corresponding to “ALGORITHM” if beaufort cipher is used for
encryption with key as “KEY”?
a) BNJSWOAPV
b) KTSWNQRXM
c) AMIRVNZOU
d) MBPHJSNIU
Answer: b
Explanation: For encrypt
Answer: c
Explanation: Cipher is an algorithm for performing encryption or decryption. In cryptography, a set of
defined steps are followed to generate ciphers. These are necessary to prevent a data breach.
Answer: b
Explanation: Autokey cipher is a substitution cipher. It falls under the category of poly alphabetic cipher as
it uses multiple substitutions at different positions in order to cipher the plain text.
Answer: c
Explanation: Encryption of plain text in Autokey cipher is done using the same table which is used for
encryption in vigenere cipher. It is known as vigenere table.
Answer: a
Explanation: Poly alphabetic cipher is a type of substitution cipher. It uses multiple substitution at different
positions in order to cipher the plain text.
Answer: d
Explanation: In poly alphabetic cipher each symbol of plain text is replaced by a different cipher text
regardless of its occurrence. Out of the given options only additive cipher is not a poly alphabetic cipher.
advertisement
Answer: a
Explanation: Autokey cipher like vigenere cipher uses vigenere table in order to encrypt the plain text. The
difference in these cipher is the usage of the keyword.
Answer: a
Explanation: Keyword cipher is less secure than Autokey cipher. It is due to the fact that keyword cipher is
mono alphabetic and thus can be cracked using frequency analysis. But Autokey cipher being a poly
alphabetic cipher cannot be cracked using this method.
8. What will be the plain text corresponding to cipher text “ZEYQC” if autokey cipher is used with keyword
as “SANFOUNDRY”?
a) INDIA
b) WORLD
c) HELLO
d) SECRET
Answer: c
Explanation: Autokey cipher is a type of poly alphabetic substitution which uses vigenere table for making
substitutions in the plain text after generating key using plain text. Using the table we find the plain text to
be “HELLO”.
Answer: b
Explanation: Autoclave cipher is an alternative name given to autokey cipher. It is because the encrypted
text is formed using a key that is generated from a message(plain text) itself.
10. In which of the following cipher the plain text and the ciphered text does not have same number of
letters?
a) affine cipher
b) autokey cipher
c) columnar cipher
d) additive cipher
Answer: b
Explanation: In transposition cipher and mono alphabetic cipher the number of letters remain same in
ciphered and deciphered text. But in poly alphabetic cipher the number of letters are different. So here as
autokey cipher is the only poly alphabetic cipher so it will be the answer.
11. What will be the ciphered text if the string “SECRET” is given as input to the code of autokey cipher
with keyword as “SANFOUNDRY”?
a) KEPWSN
b) EKWPSN
c) EKWPSNFDED
d) KEPWSNFDED
Answer: a
Explanation: For encrypting a plain text in autokey cipher we first add the keyword at the beginning of the
plain text in order to obtain the key for encryption. Then we use the vigenere table for making respective
substitutions.
Answer: b
Explanation: A
Answer: b
Explanation: Playfair cipher is also known by the name of Wheatstone playfair cipher. It is because it was
discovered by Charles Wheatstone but was promoted by Lord Playfair.
Answer: b
Explanation: Playfair cipher is a substitution cipher. It falls under the category of poly alphabetic cipher as it
uses multiple substitution at different positions in order to cipher the plain text.
3. Encryption in Autokey cipher is done using __________
a) a 5×5 table
b) a 13×2 table
c) vigenere table
d) a 6×6 table
Answer: c
Explanation: Encryption of plain text in playfair cipher is done using a 5×5 table. In this table, all the
alphabets of the keyword are arranged row wise by eliminating any duplicates then the remaining letters of
the alphabet are placed. One of the alphabet has to be omitted in order to fit all the alphabets in the table.
Answer: c
Explanation: Poly graphic cipher is a type of substitution cipher in which substitution is performed over a
block of letters. Playfair cipher is an example of poly graphic cipher.
Answer: d
Explanation: Poly graphic cipher is a type of substitution cipher in which substitution is performed over a
block of letters. In diagram substitution, two adjacent letters are substituted simultaneously. Playfair cipher
was the first diagram substitution cipher.
advertisement
Answer: c
Explanation: Out of the given options playfair cipher is the hardest cipher to break using frequency analysis.
It is because it does not substitute letters of the word individually but it encrypts them in pairs of two.
Answer: a
Explanation: Keyword cipher is less secure than playfair cipher. It is due to the fact that keyword cipher is
mono alphabetic and thus can be cracked using frequency analysis. But playfair cipher being a poly graphic
substitution cipher is harder to break using this method.
8. What will be the plain text corresponding to cipher text “BPKYFS” if playfair cipher is used with
keyword as “SECRET” (assuming j is combined with i)?
a) INDIAN
b) WORLD
c) DOLLAR
d) HELLO
Answer: c
Explanation: To decrypt the message we follow the reverse procedure. The table is formed in the same
manner. Applying this we get the plain text to be “DOLLAR”.
9. What is the rule for encryption in playfair cipher if the letters in a pair are identical?
a) then that pair is neglected
b) a null is added in between the letters
c) one of the identical letter is replaced by some other letter
d) then both of the letters are replaced by the letter appearing just next in the row
Answer: b
Explanation: In playfair cipher if the letters in a pair are identical then a null is added in between the letters.
Any letter can be used as a null as long as that letter is not the one being repeated.
10. What is the rule for encryption in playfair cipher if the letters in a pair appear in same row?
a) they are replaced by the letter appearing immediately below them respectively
b) they are replaced by the letter appearing immediately right to them respectively
c) they are replaced by the letter at the corner of the row
d) that pair is neglected
Answer: b
Explanation: If the letters in a pair appear in same row then they are replaced by the letters appearing
immediately right to them respectively. If the element to be replaced appears at the corner of the row then
we wrap around to the left side of that row.
11. What will be the ciphered text if the string “SANFOUNDRY” is given as input to the code of playfair
cipher with keyword as “SECRET” (assuming j is combined with i)?
a) ZHQAPNPAFR
b) AHQAPNPAFR
c) HAQAPNPAFR
d) QHAAPNPAFR
Answer: b
Explanation: For encrypting the plain text using playfair cipher we use a 5×5 table that is constructed by
using keyword. Then we apply rules for encryption in order to get the ciphered text. Table is given as under-
S E C R T
A B D F G
H I K L M
N O P Q U
V W X Y Z
12. What is the rule for encryption in playfair cipher if the letters in a pair appear in same column?
a) they are replaced by the letter appearing immediately below them respectively
b) they are replaced by the letter appearing immediately right to them respectively
c) they are replaced by the letters at the corner of the row
d) that pair is neglected
Answer: a
Explanation: If the letters in a pair appear in the same column then they are replaced by the letters appearing
immediately below them respectively. If the element to be replaced appears at the corner of the column then
we wrap around to the top side of that column.
13. What is the rule for encryption in playfair cipher if the letters in a pair does not appear in same row or
column?
a) they are replaced by the letter appearing immediately below them respectively
b) they are replaced by the letter appearing immediately right to them respectively
c) they are replaced by the letter of the same row at the corner of the rectangle defined by the original pair
respectively
d) that pair is neglected
Answer: c
Explanation
Answer: c
Explanation: Hill cipher uses matrix multiplication in order to encrypt the given plain text. So it requires
prerequisite knowledge of matrix algebra.
Answer: b
Explanation: Hill cipher is a substitution cipher. It falls under the category of poly alphabetic cipher as it
uses multiple substitutions at different positions in order to cipher the plain text.
Answer: a
Explanation: Encryption of plain text in playfair cipher is done using matrix multiplication. Then modulo 26
of the resulting matrix is taken so as to get the ciphered text.
Answer: c
Explanation: Poly graphic cipher is a type of substitution cipher in which substitution is performed over a
block of letters. Hill cipher is an example of poly graphic cipher.
5. Which of the following was the first poly graphic cipher to be able to operate on more than 3 letters at
once?
a) autokey cipher
b) hill cipher
c) one time pad cipher
d) playfair cipher
Answer:b
Explanation: Poly graphic cipher is a type of substitution cipher in which substitution is performed over a
block of letters. Hill cipher was the first poly graphic cipher to be able to operate on more than 3 letters at
once.
advertisement
Answer: b
Explanation: Out of the given options hill cipher is the hardest cipher to break using frequency analysis.
Although it is quite vulnerable to other forms of attack.
Answer: b
Explanation: Both hill cipher and playfair cipher are less vulnerable to frequency analysis. But hill cipher is
quite vulnerable to other forms of attack and thus less secure than playfair cipher.
8. What will be the plain text corresponding to cipher text “YGQ“ if hill cipher is used with keyword as
“GYBNQKURP”?
a) SECRET
b) WORLD
c) DOLLAR
d) HELLO
Answer: a
Explanation: To decrypt the message we follow the reverse procedure. We first find the inverse of the
keyword matrix then multiply it with cipher matrix.
9. What will be the size of a key matrix if the plain text is “SECRET”?
a) 1×6
b) 5×1
c) 6×1
d) 6×6
Answer: d
Explanation: Hill cipher uses a n x n matrix in order to cipher the plain text. In this case n=6 so a 6×6 matrix
will be used.
10. A key matrix used for encryption in hill cipher must be?
a) invertible matrix
b) non invertible matrix
c) square matrix
d) rectangular matrix
Answer: a
Explanation: A key matrix used for encryption in hill cipher must be invertible matrix. Otherwise it will be
impossible to decipher the message.
11. What will be the ciphered text if the plain text “SAN” is encrypted using hill cipher with keyword as
“GYBNQKURP”?
a) RAJ
b) JAR
c) ARJ
d) AJR
Answer: a
Explanation: W
Answer: c
Explanation: Rail fence cipher is also known as zig zag cipher. It is so because the plain text gets ciphered
by arranging the letters in a zig zag fashion.
Answer: c
Explanation: Rail fence cipher is a transposition cipher. It falls under the category of transposition cipher as
it encrypts the plain text by rearranging its letters.
3. Encryption in Rail fence cipher is done using _____________
a) by arranging the letters in a zig zag fashion in a table
b) by randomly arranging letters
c) by arranging letters in vigenere table
d) by swapping adjacent letters
Answer: a
Explanation: Rail fence cipher is a transposition cipher. It encrypts a given plain text by arranging the letters
in a zig zag fashion in a table.
4. Which of the following ciphers are created by shuffling the letters of a word?
a) substitution cipher
b) transposition cipher
c) vigenere cipher
d) hill cipher
Answer: b
Explanation: There are two types of traditional ciphers- Transposition and substitution cipher. In
transposition cipher the letters of the given data are shuffled in a particular order, fixed by a given rule.
Answer:d
Explanation: In poly alphabetic cipher each symbol of plain text is replaced by a different cipher text
regardless of its occurrence. Out of the given options, only additive cipher is not a poly alphabetic cipher.
advertisement
Answer: b
Explanation: There are two types of a traditional cipher. First is transposition cipher and the second is
substitution cipher.
7. The number of columns in the table used for encryption in rail fence cipher depends upon the given key
value.
a) True
b) False
Answer: b
Explanation: The number of columns in the table of rail fence cipher is always equal to the number of letters
in the plain text. It is independent of the given key value.
8. What will be the plain text corresponding to cipher text “SCSEMG” if rail fence cipher is used with key
value 2?
a) MSGSEC
b) SECMSG
c) GSMSEC
d) SECGSM
Answer: b
Explanation: For decryption we reverse the process used in encryption.
S C S
E M G
9. Rail fence cipher is more secure than one time pad cipher.
a) True
b) False
Answer: b
Explanation: One time pad cipher is one of the most secure traditional cipher as it is almost impossible to
crack. Rail fence cipher is not very hard to crack. Thus rail fence cipher is less secure than one time pad
cipher.
10. In which of the following cipher the plain text and the ciphered text have same letters?
a) autokey cipher
b) rail fence cipher
c) vigenere cipher
d) additive cipher
Answer: b
Explanation: In transposition cipher the letters remain the same in ciphered and plain text. Their position is
only changed whereas in substitution cipher the letters become different in encrypted text. So rail fence
cipher will be the correct option.
11. What will be the ciphered text if rail fence cipher is used for encrypting the plain text “SANFOUNDRY”
with the key value given to be 2?
a) SNONRAFUDY
b) SORAFUDYNN
c) SNAUDNORFY
d) SANFOUNDRY
Answer: a
Explanation: For encrypting a plain text using rail fence cipher we use a table having the number of rows
equal to key v
Answer: c
Explanation: Route cipher is a transposition cipher. It falls under the category of transposition cipher as it
encrypts the plain text by rearranging its letters.
Answer: c
Explanation: Route cipher is a transposition cipher. It encrypts the plain text by following an imaginary
pattern on a grid.
4. Which of the following ciphers are created by shuffling the letters of a word?
a) playfair cipher
b) route cipher
c) vigenere cipher
d) hill cipher
Answer: b
Explanation: In transposition cipher the letters of the given data are shuffled in a particular order, fixed by a
given rule. Route cipher is the only transposition cipher out of the given options.
Answer: c
Explanation: Route cipher is closely related to rail fence cipher. In rail fence cipher the plain text is written
in a zig zag fashion in a grid whereas in route cipher the plain text is written horizontally.
advertisement
7. Router cipher becomes less secure when we have to encrypt longer messages.
a) true
b) false
Answer: b
Explanation: The key of route cipher not only defines the size of grid but also the path that is to be followed.
So longer the message is, the harder it becomes to guess the path.
8. What will be the plain text corresponding to cipher text “RSEADC” if with the number of columns are
given to be 3 and route of reading is down the columns?
a) SACRED
b) DERSAC
c) REDSAC
d) SEDRAC
Answer: c
Explanation: For decryption we reverse the process used in encryption. So we arrange the letters of cipher
text down the columns and then read the grid horizontally.
R E D
S A C
9. What will be the plain text corresponding to cipher text “SFNUFACT” if with number of columns are
given to be 3 and route of reading is from the bottom right anti clockwise?
a) FACTSFUN
b) FACTFUNS
c) FUNSFACT
d) FUNFACTS
Answer: d
Explanation: For decryption we reverse the process used in encryption. So we arrange the letters of cipher
text from bottom right anti clockwise and then read the grid horizontally.
F U N F
A C T S
10. What will be the ciphered text if route cipher is used for encrypting the plain text “SANFOUNDRY”
with number of columns given to be 5 and route from the bottom right anti clockwise?
a) SUANNDFROY
b) SORAFUDYNN
c) YOFNASUNDRY
d) SANFOUNDRY
Answer: c
Explanation: For encrypting a plain text using route cipher we use a table having 5 columns as shown below.
Then we read from the bottom right anti clockwise to cipher the plain text.
S A N F O
U N D R Y
11. What will be the ciphered text if route cipher is used for encrypting the plain text “SANFOUNDRY”
with a number of columns given to be 5 and route of reading is down the columns?
a) SUANNDFROY
b) SORAFUDYNN
c) SNAUDNORFY
d) SANFOUNDRY
Answer: a
Explanation: For encrypting a plain text using route cipher we use a table having 5 columns as shown below.
T
Answer: b
Explanation: Trithemius cipher is a substitution cipher. It falls under the category of poly alphabetic cipher
as it uses multiple substitutions at different positions in order to cipher the plain text.
Answer: c
Explanation: Encryption of plain text in trithemius cipher is done by making use of tabula recta. The same
table is also used for encryption in vigenere cipher and running key cipher.
Answer: d
Explanation: If in caesar cipher we consider a shift that increases by 1 by each letter starting at 0 then it is
equivalent to trithemius cipher. So trithemius cipher is a special case of caesar cipher.
4. Which of the following is a difference between trithemius cipher and vigenere cipher?
a) they use different tables for encryption
b) vigenere cipher is poly alphabetic whereas running key cipher is mono alphabetic
c) vigenere cipher uses a key whereas no key is required for using trithemius cipher
d) vigenere cipher is substitution cipher whereas trithemius cipher is transposition cipher
Answer: c
Explanation: Trithemius cipher is a special case of vigenere cipher. The difference is that vigenere cipher
uses a different key every time but a fixed key is used by trithemius cipher.
Answer: d
Explanation: Ciphers like running key cipher, vigenere cipher, trithemius cipher, etc. makes use of tabula
recta. Whereas hill cipher, rail fence cipher and route cipher does not require tabula recta for encryption of
plain text.
advertisement
Answer: b
Explanation: Trithemius cipher is a special case of vigenere cipher. The difference is that vigenere cipher
uses a different key every time but a fixed key is used by trithemius cipher.
Answer: b
Explanation: Trithemius cipher is a special case of vigenere cipher with
ABCDEFGHIJKLMNOPQRSTUVWXYZ as key. So trithemius cipher is easier to crack as the key being
used remains same every time.
8. What will be the plain text corresponding to cipher text “ACCFYX” if trithemius cipher is used?
a) ABACUS
b) ABROAD
c) ABRUPT
d) ABUSED
Answer: a
Explanation: Running key cipher is a type of poly alphabetic substitution which uses tabula recta for making
substitutions in the plain text. Using the table and key as ABCDEFGHIJKLMNOPQRSTUVWXYZ we find
the plain text to be “ABACUS”.
9. Trithemius cipher is harder to crack than caesar cipher.
a) True
b) False
Answer: a
Explanation: Trithemius cipher uses a more complex version of caesar cipher. So trithemius cipher is harder
to crack as compared to caesar cipher.
Answer: c
Explanation: Trithemius cipher is a special case of vigenere cipher and running key cipher is a variation of
vigenere cipher. If one figures out that the cipher being used is trithemius then it is very easy to crack, unlike
running key and vigenere ciphers as these use a secret key for encryption.
11. What will be the ciphered text corresponding to “SANFOUNDRY” if trithemius cipher is used for
encryption?
a) SBPISZTKZH
b) TCQJTAULAI
c) TBOGPVOESZ
d) SPBISZKTZH
Answer: a
Explanation: Encryption in trithemius cipher takes place exactly as in vigenere cipher if we consider the key
to be ABCDEFGHIJKLMNOPQRSTUVWXYZ. So by using the tabula recta we can find the encrypted text
which is “SBPISZTKZH”.
12. What will be the ciphered text corresponding to “ALGORITHM” if trithemius cipher is used for
encryption?
a) BNJSWOAPV
b) BMHPSJUIN
c) AMIRVNZOU
d) MBPHJSNIU
Answer: c
Explanation: Encryption in trithemius cipher takes place exactly as in vigenere cipher if we consider the key
to be ABCDEFGHIJKLMNOPQRSTUVWXYZ. So by using the tabula recta we can find the encrypted text
which is “AMIRVNZOU”.
13. What will be the plain text corresponding to cipher text “RVUVMF” if trithemius cipher is used?
a) RABBIT
b) RUSSIA
c) RANGER
d) FRIEND
Answer: b
Explanation: Trithemius cipher is a type of poly alphabetic substitution which uses tabula recta for making s
Answer: a
Explanation: Polybius square is similar to substitution cipher. It is also known by the name of Polybius
checkboard.
2. How many keys are required for encryption and decryption of data when we use asymmetric cipher?
a) 0
b) 1
c) 2
d) 3
Answer: c
Explanation: Asymmetric cipher makes use of 2 keys for the purpose of encryption. One is known as public
key whereas other is called private key.
Answer: a
Explanation: Polybius square is similar to substitution cipher. Polybius square allows us to cipher the plain
text in such a way that a minimum number of symbols are used in the encrypted text.
4. What is the usual size of polybius square used for encrypting English alphabets?
a) 5 X 5
b) 6 X 6
c) 26 X 26
d) 25 X 25
Answer: a
Explanation: The usual size of poybius square for encrypting English alphabets is 5 X 5. Usually, I and J are
combined so as to fit all English letters in this table.
Answer: c
Explanation: The usual size of poybius square for encrypting English alphabets is 5 X 5. Usually, I and J are
combined so as to fit all English letters in this table.
Answer: a
Explanation: Polybius square is closely related to mono alphabetic substitution cipher and thus is more
vulnerable to frequency analysis. Whereas polybius square being a poly alphabetic cipher is less vulnerable
to frequency analysis and so is more secure.
Answer: b
Explanation: Polybius square cipher is closely related to mono alphabetic cipher. Thus it is quite vulnerable
to frequency analysis much like any other mono alphabetic cipher.
9. Which of the following cipher uses polybius square cipher in its first step of encrypting data?
a) Autokey cipher
b) One time pad cipher
c) ADFGVX cipher
d) Rail fence cipher
Answer: c
Explanation: ADFGVX cipher uses polybius square cipher in its first step of encrypting data. It uses a 6 X 6
version of polybius square.
10. What will be the plain text corresponding to ciphered text “134325” if standard polybius square cipher is
used for encryption?
a) SRH
b) CSK
c) RCB
d) KKR
Answer: b
Explanation: For decoding ciphered text we have to use the polybius square in and find out the letters
corresponding to each pair of coordinate. So in this case the plain text is found to be “CSK”.
11. What will be the encrypted text corresponding to plain text “SAN” using standard polybius square
cipher?
a) 431133
b) 341133
c) 441133
d) 114433
Answer: a
Explanation: For encrypting using polybius square cipher we have to use the table which is shown below
and write (row, col) coordinates corresponding to each letter.
12345
1ABCDE
2 F G H I/J K
3LMNOP
4QRSTU
5VWXYZ
So the ciphered text will be “431133”.
#include <cmath>
#include <iostream>
using namespace std;
void Cipher(string str)
{
int r, c;
for (int i = 0; str[i]; i++)
{
r = ceil((str[i] - 'a') / 5) + 1;
c = ((str[i] - 'a') % 5) + 1;
if (str[i] == 'k')
{
r = r - 1;
c = 5 - c + 1;
}
else if (str[i] >= 'j')
{
if (c == 1)
{
c = 6;
r = r - 1;
}
c = c - 1;
}
cout << r << c;
}
cout << endl;
}
int main()
{
string str = "nsit";
Cipher(str);
}
a) 33344244
b) 44332434
c) 33432444
d) 11444323
Answer: c
Explanation: The given code im
Answer: c
Explanation: The purpose of having an indicator block in running key cipher is to give information to the
receiver about the source of a key being used. It is usually included in the second last block of the message.
Answer: b
Explanation: Running key cipher is a substitution cipher. It falls under the category of poly alphabetic cipher
as it uses multiple substitutions at different positions in order to cipher the plain text.
Answer: c
Explanation: Encryption of plain text in running key cipher is done by making use of tabula recta. The same
table is also used for encryption in vigenere cipher.
4. Which of the following cipher uses a key book or a key text instead of a keyword?
a) vigenere cipher
b) autokey cipher
c) running key cipher
d) affine cipher
Answer: c
Explanation: Running key cipher is a poly alphabetic cipher. It uses a key book or key text instead of a
keyword which is agreed by both parties before encryption takes place.
5. Which of the following is a difference between running key cipher and vigenere cipher?
a) they use different tables for encryption
b) vigenere cipher is poly alphabetic whereas running key cipher is mono alphabetic
c) in vigenere cipher the key is repeated whereas in running key cipher key is not repeated
d) vigenere cipher was used in ancient time whereas running key cipher is used in modern world
Answer: c
Explanation: In running key cipher key is not repeated unlike vigenere cipher. They both use the same table
for encryption.
advertisement
Answer: a
Explanation: Encryption of plain text using running key cipher is done by making use of tabula recta. It
consists of 26 rows and 26 columns which have alphabets written 26 times. These are shifted towards left
after each row.
Answer: a
Explanation: Keyword cipher is less secure than running key cipher. It is due to the fact that keyword cipher
is mono alphabetic and thus can be cracked using frequency analysis. But running key cipher being a poly
alphabetic cipher is harder to crack.
8. What will be the plain text corresponding to cipher text “KEPWSN” if running key cipher is used with
keyword as “SANFOUNDRY”?
a) SECRET
b) QWERTY
c) INDIAN
d) FRIEND
Answer: a
Explanation: Running key cipher is a type of poly alphabetic substitution which uses tabula recta for making
substitutions in the plain text. Using the table we find the plain text to be “SECRET”.
Answer: a
Explanation: Vigenere cipher is a variation of vigenere cipher. The only difference between them is that in
vigenere cipher a random key is chosen whereas in running key cipher key is chosen from a book or a text.
11. What will be the ciphered text corresponding to “SANFOUNDRY” if running key cipher is used for
encryption with keyword as “ONCEUPONATIME”?
a) GNPJIJBQRR
b) GNPIJJBRRQ
c) GPNJJOBQRR
d) GJJNPOBQRI
Answer: a
Explanation: Encryption in running key cipher takes place exactly as in vigenere cipher if we don’t include
the indicator block. So by using the tabula recta we can find the encrypted text which is “GNPJIJBQRR”.
12. What will be the ciphered text corresponding to “ALGORITHM” if running key cipher is used for
encryption with keyword as “DATASTRUCTURE”?
a) LDJOZOBBK
b) DLZOJBKBO
c) ZOLDJBKBO
d) OLZBJDKBO
Answer: b
Explanation: Encryption in running key cipher takes place exactly as in vigenere cipher if we don’t include
the indicator block. So by using the tabula recta we can find the encrypted text which is “DLZOJBKBO”.
13. What will be the plain text corresponding to cipher text “IWRWHS” if running key cipher is used with
keyword as “SANFOUNDRY”?
a) SECRET
b) QWERTY
c) INDIAN
d) FRIEND
Answer: b
Explanatio
Answer: a
Explanation: Polybius square is similar to substitution cipher. It is also known by the name of Polybius
checkboard.
Answer: a
Explanation: Bifid cipher uses polybius square for encrypting the plain text. Bifid cipher combines polybius
square cipher with transposition.
Answer: a
Explanation: Bifid cipher combines polybius square cipher with transposition. It uses fractionation to obtain
diffusion.
4. What will be the key square in bifid cipher for the key “SANFOUNDRY”?
a)
S A N F O
U D R Y B
C E G H I
K L M P Q
T V W X Z
b)
S A N F O
U N D R Y
C E G H I
K L M P Q
T V W X Z
advertisement
c)
A B C D E
F G H I K
L M N O P
Q R D T U
V W X Y Z
d)
S A N F O
U D R Y A
B C G H I
K L M P Q
T V W X Z
Answer: a
Explanation: For forming the key square from the given key we first add the letters of the key in the square
by omitting the repeated letters and then we add the remaining letters of the English alphabet. Usually, I and
J are combined together.
5. Trifid cipher encrypts the plain text by using bifid cipher twice.
a) true
b) false
Answer: b
Explanation: Trifid cipher is a variation of bifid cipher. The only difference between them is that trifid
cipher uses a 3×3 key square instead of 5×5 square.
Answer: b
Explanation: Bifid square combines polybius square with transposition. So the given statement is false.
7. What will be the ciphered text corresponding to “SANFOUNDRY” if bifid cipher is used for encryption
with key as “KEY” with period as 5?
a) SBPISZTKZH
b) PLNSOWGKQM
c) SELFQEXBHM
d) YFSGWNFBW
Answer: b
Explanation: For encrypting the plain text using bifid cipher we first form the polybius square with the help
of given key. After this, the plain text is divided into blocks of length 5 and corresponding coordinates are
noted. So the corresponding cipher text would be “PLNSOWGKQM”.
8. What will be the ciphered text corresponding to “ALGORITHM” if bifid cipher is used for encryption
with key as “KEY” with a period as 5?
a) SBPISZTKZH
b) PLNSOWGKQM
c) SELFQEXBHM
d) YFSGWNFBW
Answer: d
Explanation: For encrypting the plain text using bifid cipher we first form the polybius square with the help
of given key. After this, the plain text is divided into blocks of length 5 and corresponding coordinates are
noted. So the corresponding cipher text would be “YFSGWNFBW”.
9. What will be the plain text corresponding to cipher text “XKS” if the bifid cipher is used with key as
“KEY” and period as 5?
a) IND
b) USA
c) RSA
d) AUS
Answer: b
Explanation: The decryption in bifid cipher begins identically to encryption. Then we find the corresponding
coordinates and then we get the plain text. So the plain text is “USA”.
10. What will be the plain text corresponding to ciphered text “BKC” if the bifid cipher is used for
encryption with key as “KEY” and period 5?
a) MSD
b) SRT
c) KVK
d) VVS
Answer: c
Explanation: The decryption in bifid cipher begins identically to encryption. Then we find the corresponding
coordinates a
Answer: d
Explanation: In Morse Code, the length of the single dot is defined to be 1 Unit. While dash is defined to be
3 Unit. In Morse Code, the space between words is 7 unit.
Answer: a
Explanation: The two signal duration used in Morse code are Dot and Dash. They are also called Dits and
Dahs. While other symbols are expressed in terms of dots and dash.
Answer: a
Explanation: Dot duration is the basic unit of time measurement in Morse code transmission. Both dot and
dash signal are used as time measurement in Morse code.
Answer: c
Explanation: The duration of a dash is 3 times the duration of a dot as duration of dot is defined to be 1 unit
in Morse Code and duration of dash is 3 units in Morse Code.
advertisement
6. In Morse Code, each dot or dash within a character is followed by a period of signal absence. What is the
name of that signal?
a) Slash
b) Space
c) Ampersand
d) Asterisk
Answer: b
Explanation: Each dot or dash within a character is followed by a period of signal absence called Space
Signal which is of 1 Unit. The space signal is used after every word in Morse Code.
Answer: a
Explanation: The duration of Space Signal is 1 Unit and Dot Duration is also 1 Unit. So the duration of
Space Signal is equal to Dot Duration.
Answer: c
Explanation: The letters of a word are separated by a space of 3 dot durations. Since the dot duration is of 1
Unit. So, the letters of a word are separated by a space of 3 Unit.
Answer: c
Explanation: The words are separated by a space of 7 dot durations. Since the dot duration is of 1 Unit. So,
the words are separated by a space of 7 Unit.
10. Is the letter “E” of English alphabet has the shortest code in Morse Code?
a) True
b) False
Answer: a
Explanation: Morse code was designed so that the length of each symbol is inverse to the frequency of
occurrence in text. Therefore, the letter the letter “E”, has a single dot.
11. Is the letter “E” represented by the single dot in Morse code?
a) True
b) False
Answer: a
Explanation: The letter in English, “E”, has a single dot. It is considered to be the smallest Morse Code ever
defined till now while other letters are larger in time duration.
Answer: b
Explanation: The common letter in English, the letter “T”, has the shortest dash code: a single dash. While
the letter in English, “E”, has a single dot. It is considered to be the smallest Morse Code ever defined till
now while other letters are larger in time duration.
13. What is the Morse code for the distress signal is SOS?
a) 3 Dots, 3Dashes, and 3 Dots
b) 3 Dots, 3 Dashes, and 2 Dots
c) 3 Dots, 2 Dashes, and 3 Dots
d) 2 Dots, 3 Dashes, and 3 Dots
Answer: a
Explanation: In an emergency the distress signal is SOS– 3 dots, 3 dashes, and 3 dots – internationally
recognized by treaty. It is used to call emergency help when someone is in need.
Answer: a
Explanation: A code was needed to transmit natural language using only the pulses in a telegraph system.
Morse developed the modern International Morse code.
Answer: b
Explanation: Morse system for telegraphy was first used in 1844 to make indentations on a paper tape when
electric c
1. Which letter of the English alphabet has the shortest code in Morse Code?
a) A
b) C
c) B
d) E
Answer: d
Explanation: Morse code was designed so that the length of each symbol is inverse to the frequency of
occurrence in text. Thus the letter in English, “E”, has a single dot.
2. Which word tells a word rate of Morse code’s shorter code durations for common characters such as “e”
and “t”.?
a) PARIS
b) CODEX
c) PARCOD
d) SPACE
Answer: a
Explanation: PARIS tells about word rate that is typical of natural language words and reflects the benefits
of Morse code’s shorter code durations for common characters such as “e” and “t”.
Answer: a
Explanation: Morse code speed is measured in characters per minute (cpm) as well as in words per minute
(wpm). The transmission rate of the Morse code is also measured is groups per unit (gpm).
Answer: d
Explanation: It was created by Friedrich Clemens Gerke in 1848 and initially used for telegraphy in
Germany. Samuel Morse is the inventor of the telegraph after whom Morse code was named.
advertisement
Answer: d
Explanation: The most common letter in English, the letter “E”, has a single dot. Morse code was designed
so that the length of each symbol is inverse to frequency of occurrence in text.
7. Which word offers a word rate that is typical of 5-letter code groups?
a) PARIS
b) CODEX
c) PARCOD
d) SPACE
Answer: b
Explanation: CODEX word offers a word rate that is typical of 5-letter code groups. PARIS is a standard
word to measure the operator transmission speed of Morse Code.
8. What is the name of special procedural signals that are used to indicate changes in communications
protocol status?
a) Prosigns
b) Aldis
c) BIT
d) Asterisk
Answer: b
Explanation: Prosigns are special unwritten procedural signals which are used to show changes in
communications protocol status or white space text.
Answer: a
Explanation: Since the duration of Space Signal is equal to Dot Duration. So, the space signal is of 1 Unit.
While a dash is 3 units and space between letters is also three units.
10. The letters of a word are separated by a space of how many units?
a) 1 Unit
b) 2 Units
c) 3 Units
d) 4 Units
Answer: c
Explanation: The letters of a word are separated by a space of 3 Unit. The representation of dot symbol has 1
unit, while the dash symbol has 2 units.
11. Which symbol is not defined inside the ITU recommendation on Morse code?
a) $
b) .
c) +
d) ~
Answer: a
Explanation: The symbol $ and & are not defined inside the ITU recommendation on Morse code.
International Telecommunication Union is a union that mandated Morse code worldwide.
Answer: d
Explanation: There is no standard representation for the exclamation mark (!) in Morse code. The other
symbols have been defined by the International Telecommunication Union.
13. In which year the symbol @ was added to the official Morse character set by ITU-R?
a) 2003
b) 2004
c) 2005
d) 2006
Answer: b
Explanation: On May 24, 2004, the symbol @ was added to the official Morse character set by International
Telecommunication Union.
14. Which device was used to generate high speed Morse Code?
a) Iambic Paddle
b) Note Paddle
c) Vibrolex
d) KSM Radio
Answer: a
Explanation: Iambic Paddle was used to generate high speed Morse Code in conjunction with an electronic
keyer. It was commercially manufactured.
Answer: a
Explanation: Alfre
Answer: d
Explanation: There are two types of the traditional cipher. One is transposition cipher and the other is
substitution cipher. Whereas PKCS is a modern asymmetric cipher.
Answer: d
Explanation: Asymmetric cipher makes use of 2 keys for the purpose of encryption. One is known as public
key whereas other is called private key.
Answer: c
Explanation: Asymmetric cipher makes use of 2 keys for the purpose of encryption. DSA is an example of
asymmetric encryption technique.
Answer: c
Explanation: Columnar cipher is a transposition cipher. It falls under the category of transposition cipher as
it encrypts the plain text by rearranging its letters.
advertisement
6. Which of the following ciphered text would have NOT used transposition cipher for encryption of the
plain text “CIPHER”?
a) EPIHRC
b) EHIPCR
c) DTIPRC
d) HRIPEC
Answer: c
Explanation: We know that transposition cipher encrypts the plain text by shuffling the letters of the plain
text. So out of the given options, only “DTIPRC” does not have the same set of letters as “CIPHER”.
7. Which of the following cipher is formed by applying columnar transposition cipher twice?
a) Rail Fence cipher
b) Route cipher
c) Double transposition cipher
d) One time pad
Answer: c
Explanation: Double transposition cipher is formed by applying columnar transposition cipher twice. For the
purpose of encryption, we may use the same key twice or we can use two different keys.
8. In which of the following cipher the plain text and the ciphered text does not have the same set of letters?
a) route cipher
b) columnar transposition cipher
c) myszkowski cipher
d) additive cipher
Answer: d
Explanation: In transposition cipher, the letters remain the same in ciphered and plain text. Their position is
only changed whereas in substitution cipher the letters become different in encrypted text. As additive cipher
is the only non transposition cipher out of the given options so it will be the correct option.
Answer: b
Explanation: Double transposition cipher is formed by applying columnar transposition cipher twice. So it is
harder to crack than a simple columnar transposition cipher.
10. How many columns do we need to have in the table, that is used for encryption in columnar
transposition cipher when a given keyword is “SECRET” and plain text is “SANFOUNDRY”?
a) 4
b) 5
c) 6
d) 7
Answer: c
Explanation: The number of columns in the table used for the purpose encryption in columnar transposition
cipher will always be equal to the number of letters in the keyword. So in this case it will be equal to 6.
11. What will be the encrypted text corresponding to plain text “CLASSIFIED” using columnar
transposition cipher with a keyword as “GAMES”?
a) LFDSIASECI
b) SECIAISDFL
c) CILFAISESD
d) LFSECIAISD
Answer: d
Explanation: For encrypting using columnar cipher we have to arrange the letters of the plain text in a table
which has the same number of columns as the letters of the keyword. Then the letters of the keyword are
arranged in alphabetical order and we read along each column.
31425
GAMES
CLASS
IFIED
So the ciphered text will be “IFSECIAISD”.
12. How many rows will the letters of the plain text occupy in the table, that is used for encryption in
columnar transposition cipher when a given keyword is “SECRET” and plain text is “SANFOUNDRY”?
a) 1
b) 2
c) 3
d) 4
Answer: b
Explanation: The number of columns in the table used for the purpose encryption in columnar transposition
cipher will always be equal to the number of letters in the keyword.So when we will write the letters of the
plain text row wise then there will be 2 rows of plain text in this case. The table is shown below :-
SECRET
1SANFOU
2NDRY
13. Which of the following statement is not true regarding columnar transposition cipher?
a) it is a weak cipher
b) probability of error is high while deciphering
c) it cannot be combined with other ciphers
d) it is a traditional symmetric cipher
Answer: c
Explanation: Altho
1. Which of the following cipher makes use of linear algebra for encrypting data?
a) polybius square cipher
b) affine cipher
c) caesar cipher
d) rail fence cipher
Answer: b
Explanation: Affine cipher is the only cipher out of the given options that make use of linear algebra for the
purpose of encryption. It is a type of mono alphabetic cipher.
2. Which of the following cipher requires only one key for decoding the ciphered text?
a) Affine cipher
b) RSA
c) DSA
d) PKCS
Answer: a
Explanation: Asymmetric cipher makes use of 2 keys for the purpose of encryption. As affine cipher is the
only symmetric cipher out of the given options so it requires only one key.
Answer: c
Explanation: Affine cipher is the weakest cipher out of the given options as it is a mono alphabetic cipher
and other options are poly alphabetic ciphers. So it is quite vulnerable to frequency analysis.
4. What is the formula used for encryption of data using affine cipher(a,b are constants and x is the
numerical equivalent of a letter to be encrypted)?
a) ax+b
b) (ax+b)%26
c) ax2+bx
d) (ax2+bx)%26
Answer: b
Explanation: Affine cipher uses linear algebra for the purpose of encryption. It uses the formula (ax+b)%26
for this purpose.
5. What is the formula used for decoding the ciphered text using affine cipher(a,b are constants and x is the
numerical equivalent of a letter to be encrypted)?
a) a-1(x-b)%26
b) (ax+b)%26
c) b-1(x-a)%26
d) b-1(x-a)
Answer: a
Explanation: Affine cipher uses linear algebra for the purpose of encryption. It uses the formula a-1(x-b)%26
for decryption of ciphered text.
advertisement
Answer: a
Explanation: Affine cipher falls in the category of mono alphabetic substitution cipher. It uses linear algebra
for encrypting the plain text.
Answer: b
Explanation: Affine cipher is more secure as compared to caesar cipher. But affine cipher is a very weak
cipher as it can be easily broken using frequency analysis.
Answer: b
Explanation: Affine cipher is a very weak cipher as it can be easily broken using frequency analysis. It can
be easily cracked even if 2 characters are known.
9. What will be the ciphered text corresponding to plain text “sanfoundry” if an affine cipher is used with
key values as a=5, b=10?
a) wkxjcgxzra
b) gkxteuxfzw
c) ukxhmyxdfg
d) rfsexbsumv
Answer: a
Explanation: Affine cipher uses linear algebra for the purpose of encryption. It uses the formula (ax+b)%26
for this purpose. So the ciphered text will be “wkxjcgxzra”.
10. What will be the plain text corresponding to ciphered text “rmw ” if an affine cipher is used with key
values as a=5, b=10?
a) csk
b) kkr
c) srt
d) msd
Answer: c
Explanation: Affine cipher uses linear algebra for the purpose of encryption It uses the formula a-1(x-b)%26
for decryption of ciphered text. So the plain text will be “srt”.
11. While choosing the value of a and m (m is the no. of alphabets) in affine cipher it must be ensured that?
a) a and m are prime numbers
b) a and m are odd numbers
c) a and m are coprime
d) a and m are even numbers
Answer: c
Explanation: While choosi
Answer: a
Explanation: The most common hamming codes generalize to form hamming(7, 4) code. It encodes four bits
of data into seven bits by adding three parity bits.
2. What is the minimal Hamming distance between any two correct codewords?
a) 1
b) 2
c) 3
d) 4
Answer: c
Explanation: Since we use a generalized version of Hamming(7, 4) code, the minimal hamming distance is
3. It cannot correct burst errors.
4. Hamming codes can be used for both single-bit error and burst error detection and correction.
a) True
b) False
Answer: b
Explanation: Hamming bits are suitable only for single-bit error detection and correction and two bit error
detection. It is very unlikely to detect burst errors.
Answer: a
Explanation: Richard W. Hamming invented hamming codes in Bell Telephone Laboratory to minimize the
errors in punched card readers. Huffman invented huffman codes. Shannon invented Shannon-Fanno codes.
advertisement
Answer: b
Explanation: Hamming codes are a class of binary linear codes, hence r>=2. For a hamming(7, 4) code, the
block length ‘n’ is 2r-1 where r is the parity bit. Here, r=3.
Answer: c
Explanation: Hamming codes are a class of binary linear codes, hence r>=2. For a hamming(7,4) code, the
message length ‘k’ is 2r-r-1 where r is the parity bit. Here, r=3.
Answer: b
Explanation: A two-out-of-five code consists of three 0s and two 1s. Hence, it contains ten possible
combinations to represent digits from 0-9.
10. Including a parity bit along with the data surely detects the errors.
a) true
b) false
Answer: b
Explanation: If error has occurred in a data string, parity will change inorder to indicate errors. However, if
the error occurs in parity bit, the error goes undetected.
11. ________ is the mechanism of sending data bits multiple times to ensure consistency.
a) Repetition
b) Duplication
c) Mirroring
d) Redundancy
Answer: a
Explanation: Repeating data bits multiple times is done to ensure consistency. If the data bit to be sent is a 1,
a n=3 repetition code will send 111. If the bits are not the same, an error has occurred.
Answer: c
Explanation: An Extended Hamming code is also called as SECDED (Single Error Correction Double Error
Detection). The most popular codes are (72, 64) code and (127,120) code.
13. What is the code rate of a repetition Hamming code (3, 1)?
a) 1
b) 3
c) 1/3
d) 1.3
Answer: c
Explanation: The code rate of a repetition hamming code is the second number divided by the first number.
Here, it is 1/3.
14. For a hamming code of parity bit m=8, what is the total bits and data bits?
a) (255, 247)
b) (127, 119)
c) (31, 26)
d) (0, 8)
Answer: a
Explanation: Total bits are computed as, 2m-1 = 28-1 =255.
Data bits are computed as 2m-m-1= 28-8-1= 247.
15. What is the rate of the hamming code of parity bit m=8?
a) 0.94
b) 0.92
c) 0.90
d) 0.97
Answer: d
Explanation: For a hamm
Answer: a
Explanation: The worst-case efficiency of solving an problem in polynomial time is O(p(n)) where p(n) is
the polynomial time of input size.
Answer: b
Explanation: Problems that can be solved in polynomial time are known as tractable. Problems that cannot
be solved in polynomial time are intractable.
Answer: a
Explanation: One of the properties of polynomial functions states that the sum and composition of two
polynomials are always polynomials.
4. _________ is the class of decision problems that can be solved by non-deterministic polynomial
algorithms.
a) NP
b) P
c) Hard
d) Complete
Answer: a
Explanation: NP problems are called as non-deterministic polynomial problems. They are a class of decision
problems that can be solved using NP algorithms.
Answer: c
Explanation: Problems cannot be solved by any algorithm are called undecidable problems. Problems that
can be solved in polynomial time are called Tractable problems.
advertisement
Answer: d
Explanation: Mathematically, the run time of Euler’s circuit problem is determined to be O(N2).
Answer: a
Explanation: Euler’s circuit problem can be solved in polynomial time. It can be solved in O(N2).
Answer: b
Explanation: Halting problem by Alan Turing cannot be solved by any algorithm. Hence, it is undecidable.
Answer: b
Explanation: A non-deterministic algorithm is a two-stage procedure- guessing stage and verification stage.
Answer: a
Explanation: One of the properties of NP class problems states that A non-deterministic algorithm is said to
be non-deterministic polynomial if the time-efficiency of its verification stage is polynomial.
11. How many conditions have to be met if an NP- complete problem is polynomially reducible?
a) 1
b) 2
c) 3
d) 4
Answer: b
Explanation: A function t that maps all yes instances of decision problems D1 and D2 and t should be
computed in polynomial time are the two conditions.
Answer: c
Explanation: The CNF satisfiability problem belongs to NP complete class. It deals with Boolean
expressions.
13. How many steps are required to prove that a decision problem is NP complete?
a) 1
b) 2
c) 3
d) 4
Answer: b
Explanation: First, the problem should be NP. Next, it should be proved that every problem in NP is
reducible to the problem in question in polynomial time.
Answer: d
Explanation: Hamiltonian circuit, bin packing, partition problems are NP complete problems. Halting
problem is an undecidable problem.
15. The choice of polynomial class has led to the development of an extensive theory called ________
a) computational complexity
b) time complexity
c) problem complexity
d) decision complexity
Answer: a
Explanation: An exten
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
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
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
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.
advertisement
6. Who formulated the first ever algorithm for solving the Hamiltonian path problem?
a) Martello
b) Monte Carlo
c) Leonard
d) Bellman
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)
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
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
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)
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)
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
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
Answer: c
Explanation: The above graph has no Ham
Answer: b
Explanation: Any set A will be called a subset of set B if all elements of set A are also present in set B. So in
such a case set A will be a part of set B.
Answer: b
Explanation: In subset sum problem check for the presence of a subset that has sum of elements equal to a
given number. If such a subset is present then we print true otherwise false.
3. Which of the following is true about the time complexity of the recursive solution of the subset sum
problem?
a) It has an exponential time complexity
b) It has a linear time complexity
c) It has a logarithmic time complexity
d) it has a time complexity of O(n2)
Answer: a
Explanation: Subset sum problem has both recursive as well as dynamic programming solution. The
recursive solution has an exponential time complexity as it will require to check for all subsets in worst case.
4. What is the worst case time complexity of dynamic programming solution of the subset sum
problem(sum=given subset sum)?
a) O(n)
b) O(sum)
c) O(n2)
d) O(sum*n)
Answer: d
Explanation: Subset sum problem has both recursive as well as dynamic programming solution. The
dynamic programming solution has a time complexity of O(n*sum) as it as a nested loop with limits from 1
to n and 1 to sum respectively.
5. Subset sum problem is an example of NP-complete problem.
a) true
b) false
Answer: a
Explanation: Subset sum problem takes exponential time when we implement a recursive solution. Subset
sum problem is known to be a part of NP complete problems.
advertisement
6. Recursive solution of subset sum problem is faster than dynamic problem solution in terms of time
complexity.
a) true
b) false
Answer: b
Explanation: The recursive solution to subset sum problem takes exponential time complexity whereas the
dynamic programming solution takes polynomial time complexity. So dynamic programming solution is
faster in terms of time complexity.
Answer: d
Explanation: Recursive solution of subset sum problem is slower than dynamic problem solution in terms of
time complexity. Dynamic programming solution has a time complexity of O(n*sum).
8. Which of the following should be the base case for the recursive solution of subset sum problem?
a)
if(sum==0)
return true;
b)
if(sum==0)
return true;
if (n ==0 && sum!= 0)
return false;
c)
d)
if(sum<0)
return true;
if (n ==0 && sum!= 0)
return false;
Answer: b
Explanation: The base case condition defines the point at which the program should stop recursion. In this
case we need to make sure that, the sum does not become 0 and there should be elements left in our array for
recursion to happen.
#include <stdio.h>
bool func(int arr[], int n, int sum)
{
if (sum == 0)
return true;
if (n == 0 && sum != 0)
return false;
if (arr[n-1] > sum)
return func(arr, n-1, sum);
return func(arr, n-1, sum) || func(arr, n-1, sum-arr[n-1]);
}
int main()
{
int arr[] = {4,6, 12, 2};
int sum = 12;
int n = sizeof(arr)/sizeof(arr[0]);
if (func(arr, n, sum) == true)
printf("true");
else
printf("false");
return 0;
}
a) 12
b) 4 6 2
c) True
d) False
Answer: c
Explanation: The given code represents the recursive approach of solving the subset sum problem. The
output for the code will be true if any subset is found to have sum equal to the desired sum, otherwise false
will be printed.
#include <stdio.h>
bool func(int arr[], int n, int sum)
{
bool subarr[n+1][sum+1];
for (int i = 0; i <= n; i++)
subarr[i][0] = true;
for (int i = 1; i <= sum; i++)
subarr[0][i] = false;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= sum; j++)
{
if(j<arr[i-1])
subarr[i][j] = subarr[i-1][j];
if (j >= arr[i-1])
subarr[i][j] = subarr[i-1][j] ||
subarr[i - 1][j-arr[i-1]];
}
}
return subarr[n][sum];
}
int main()
{
int arr[] = {3, 3, 4, 4, 7};
int sum = 5;
int n = sizeof(arr)/sizeof(arr[0]);
if (func(arr, n, sum) == true)
printf("true");
else
printf("false");
return 0;
}
a) true
b) false
c) 0
d) error in code
Answer: b
Explanation: The given code represents the dynamic programming approach of solving the subset sum
problem. The output for the code will be true if any subset is found to have sum equal to the desired sum,
otherwise false will be printed.
11. What will be the worst case time complexity for the following code?
#include <stdio.h>
bool func(int arr[], int n, int sum)
{
if (sum == 0)
return true;
if (n == 0 && sum != 0)
return false;
if (arr[n-1] > sum)
return func(arr, n-1, sum);
return func(arr, n-1, sum) || func(arr, n-1, sum-arr[n-1]);
}
int main()
{
int arr[] = {4,6, 12, 2};
int sum = 12;
int n = sizeof(arr)/sizeof(arr[0]);
if (func(arr, n, sum) == true)
printf("true");
else
printf("false");
return 0;
}
a) O(n log n)
b) O(n2)
c) O(2n)
d) O(n2 log n)
Answer: c
Explanation: The given code repr
1. What is meant by the power set of a set?
a) subset of all sets
b) set of all subsets
c) set of particular subsets
d) an empty set
Answer: b
Explanation: Power set of a set is defined as the set of all subsets. Ex- if there is a set S={1,3} then power
set of set S will be P={{},{1},{3}{1,3}}.
Answer: c
Explanation: In set partition problem we check whether a set can be divided into 2 subsets such that the sum
of elements in each subset is equal. If such subsets are present then we print true otherwise false.
3. Which of the following is true about the time complexity of the recursive solution of set partition
problem?
a) It has an exponential time complexity
b) It has a linear time complexity
c) It has a logarithmic time complexity
d) it has a time complexity of O(n2)
Answer: a
Explanation: Set partition problem has both recursive as well as dynamic programming solution. The
recursive solution has an exponential time complexity as it will require to check for all subsets in the worst
case.
4. What is the worst case time complexity of dynamic programming solution of set partition
problem(sum=sum of set elements)?
a) O(n)
b) O(sum)
c) O(n2)
d) O(sum*n)
Answer: d
Explanation: Set partition problem has both recursive as well as dynamic programming solution. The
dynamic programming solution has a time complexity of O(n*sum) as it as a nested loop with limits from 1
to n and 1 to sum respectively.
6. Recursive solution of Set partition problem is faster than dynamic problem solution in terms of time
complexity.
a) true
b) false
Answer: b
Explanation: The recursive solution to set partition problem takes exponential time complexity whereas the
dynamic programming solution takes polynomial time complexity. So dynamic programming solution is
faster in terms of time complexity.
Answer: d
Explanation: Recursive solution of set partition problem is slower than dynamic problem solution in terms
of time complexity. Dynamic programming solution has a time complexity of O(n*sum).
8. Which of the following should be the base case for the recursive solution of a set partition problem?
a)
If(sum%2!=0)
return false;
if(sum==0)
return true;
b)
If(sum%2!=0)
return false;
if(sum==0)
return true;
if (n ==0 && sum!= 0)
return false;
c)
d)
if(sum<0)
return true;
if (n ==0 && sum!= 0)
return false;
Answer: b
Explanation: In this case, we need to make sure that, the sum does not become 0 and there should be
elements left in our array for recursion to happen. Also if the sum of elements of the set is an odd number
then that set cannot be partitioned into two subsets with an equal sum so under such a condition false should
be returned.
#include <stdio.h>
#include <stdbool.h>
bool func1(int arr[], int n, int sum)
{
if (sum == 0)
return true;
if (n == 0 && sum != 0)
return false;
if (arr[n-1] > sum)
return func1(arr, n-1, sum);
return func1(arr, n-1, sum) || func1(arr, n-1, sum-arr[n-1]);
}
bool func (int arr[], int n)
{
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i];
if (sum%2 != 0)
return false;
return func1 (arr, n, sum/2);
}
int main()
{
int arr[] = {4,6, 12, 2};
int n = sizeof(arr)/sizeof(arr[0]);
if (func(arr, n) == true)
printf("true");
else
printf("false");
return 0;
}
a) true
b) false
c) 4 6 2
d) 12
Answer: a
Explanation: The given code represents the recursive approach of solving the set partition problem. The
code checks whether a set can be divided into 2 subsets such that the sum of elements in each subset is
equal. If such a partition is possible then we print true otherwise false. In this case true should be printed.
#include <stdio.h>
bool func (int arr[], int n)
{
int sum = 0;
int i, j;
for (i = 0; i < n; i++)
sum += arr[i];
if (sum%2 != 0)
return false;
bool partition[sum/2+1][n+1];
for (i = 0; i <= n; i++)
partition[0][i] = true;
for (i = 1; i <= sum/2; i++)
partition[i][0] = false;
for (i = 1; i <= sum/2; i++)
{
for (j = 1; j <= n; j++)
{
partition[i][j] = partition[i][j-1];
if (i >= arr[j-1])
partition[i][j] = partition[i][j] || partition[i - arr[j-1]][j-1];
}
}
return partition[sum/2][n];
}
int main()
{
int arr[] = {3, 3, 4, 4, 7};
int n = sizeof(arr)/sizeof(arr[0]);
if (func(arr, n) == true)
printf("true");
else
printf("false");
return 0;
}
a) true
b) false
c) 0
d) error
Answer: b
Explanation: The given code represents the dynamic programming approach of solving set partition
problem. The code checks whether a set can be divided into 2 subsets such that the sum of elements in each
subset is equal. If such a partition is possible then we print true otherwise false. In this case, false should be
printed.
11. What will be the auxiliary space complexity of dynamic programming solution of set partition
problem(sum=sum of set elements)?
a) O(n log n)
b) O(n2)
c) O(2n)
d) O(sum*n)
Answer: d
Explanation: The auxiliary
1. __________ has the lowest fault rate of all the page replacement algorithms.
a) Optimal page replacement algorithm
b) LRU replacement algorithm
c) FIFO
d) Counting based
Answer: a
Explanation: Optimal page replacement algorithm has the lowest fault rate as it has the knowledge of all the
pages beforehand.
2. Optimal page replacement algorithm is also called as __________
a) LIFO
b) NRU
c) Clairvoyant replacement algorithm
d) Page buffering
Answer: c
Explanation: Optimal page replacement algorithm is also called a Clairvoyant replacement algorithm or
Belady’s optimal replacement algorithm.
3. In a optimal page replacement algorithm, when a page is to be replaced, which of the following pages is
chosen?
a) Oldest page
b) Newest page
c) Frequently occurred page in the future
d) Not frequently occurred page in the future
Answer: d
Explanation: The page which doesn’t occur more frequently in the future is chosen to be replaced with the
page in the frame.
4. A page that is not going to be used for the next 7 seconds will be swapped out over a page that is going to
be used within the next 0.7 seconds.
a) True
b) False
Answer: a
Explanation: In an optimal page replacement algorithm, the page that is to be used later in the future is
swapped out over a page that is to be used immediately.
Answer: b
Explanation: Analysis of the optimal paging algorithm is done through an online algorithm. Efficiency is
calculated through amortized analysis.
advertisement
Answer: b
Explanation: Optimal page replacement algorithm is used in special-purpose operating system because it is
impossible to compute time before which a page is used.
7. Optimal page replacement algorithm is said to satisfy __________
a) Online algorithm
b) Stack algorithm
c) Queue algorithm
d) Array algorithm
Answer: b
Explanation: Optimal page replacement algorithm is said to satisfy the stack algorithm. It is also called as
inclusion property.
8. In a stack algorithm, the set of pages in a k-frame memory is always a subset of pages in a __________
frame memory.
a) k-1
b) k
c) k+1
d) k(k+1)
Answer: c
Explanation: Stack algorithm is satisfied if the set of pages in a k-frame memory is always a subset of pages
in a k+1 frame memory.
9. When all software that runs on a system is known beforehand, optimal page replacement algorithm can be
used in a general-purpose operating system.
a) True
b) False
Answer: a
Explanation: The algorithm can be implemented in a general-purpose algorithm if the software is known
beforehand and if it is amenable to the static analysis of the memory.
10. Consider a reference string 7,0,1,2,0,3,0,4,2,3,0,3,2,1,2,0,1,7,0,1 of frame size 3. Calculate the number
of page faults using optimal page replacement algorithm.
a) 10
b) 9
c) 8
d) 7
Answer: b
Explanation: For the given string, the number of page faults using optimal page replacement algorithm is 9.
It is solved in the given diagram.
11. Consider a reference string 7,0,1,2,0,3,0,4,2,3,0,3,2,1,2,0,1,7,0,1 of frame size 4. Calculate the number
of page faults using optimal page replacement algorithm.
a) 7
b) 9
c) 8
d) 6
Answer: c
Explanation: For the given reference string, the number of page faults using optimal page replacement
algorithm is said to be 8. It is solved in the given diagram.
12. Consider a reference string 1,2,3,2,1,5,2,1,6,2,5,6,3,1,3,6,1,2,4,3 of frame size 3. Calculate the number
of page faults using optimal page replacement algorithm.
a) 12
b) 16
c) 14
d) 15
Answer: c
Explanation: For the given
1. ________ is a typical online problem from the competitive analysis to determine the optimal solution.
a) Page replacement algorithm
b) Segmentation
c) Paging
d) Segmentation with paging
Answer: a
Explanation: Page replacement is a typical online problem from the competitive analysis. They determine
which pages to page out or write to disk.
Answer: a
Explanation: FIFO is the simplest page replacement algorithm since LRU and optimal replacement
algorithms require past and future data patterns respectively.
3. __________ algorithm associates with each page the time when the page was brought into memory.
a) Optimal page replacement
b) FIFO
c) LRU replacement algorithm
d) Counting based replacement
Answer: b
Explanation: FIFO algorithm associates with each page the time when the page was brought into memory.
The new page is inserted at the tail of the queue.
4. As the number of frames available increases, the number of page faults decreases.
a) True
b) False
Answer: a
Explanation: One of the rules of the page replacement algorithm is that, as the number of frames available
increases, the number of page faults decreases.
5. Which of the following page replacement algorithms return the minimum number of page faults?
a) LRU replacement algorithm
b) Optimal page replacement algorithm
c) FIFO
d) Counting based replacement
Answer: b
Explanation: Though FIFO is the simplest of all algorithms, optimal page replacement algorithm returns the
minimum number of page faults.
Join [email protected]
6. Which of the following is the main drawback of FIFO page replacement algorithm?
a) Requirement of large memory
b) Frame allocation
c) Reduction in multiprogramming
d) Reduced optimality
Answer: c
Explanation: The main drawback of FIFO page replacement algorithm is that it reduces the level of
multiprogramming and also causes Belady’s anomaly.
7. Which of the following is required to determine the number of page faults in FIFO?
a) Page number
b) Page frame number
c) Memory capacity
d) Segment number
Answer: b
Explanation: To determine the number of page faults in a page replacement algorithm using FIFO, we
require page frame number.
8. In a FIFO algorithm, when a page is to be replaced, which of the following page is chosen?
a) Oldest page
b) Newest page
c) Frequently occurred page in past
d) Frequently occurred page in future
Answer: a
Explanation: In FIFO page replacement algorithm, when a page is to be replaced, the oldest page is chosen
and replaced at the tail of the queue.
Answer: b
Explanation: The cost of a FIFO algorithm is cheap and intuitive and it is used in poor practical applications.
Answer: d
Explanation: Of the following given operating systems, VAX/VMS uses a FIFO algorithm.
Answer: d
Explanation: The competitive analysis of a FIFO algorithm is mathematically found to be k/(k-h+1) where k
and h are some constants used in page replacement and always, h<=k.
12. Under which of the following scenarios is page replacement algorithm required?
a) When total memory exceeds physical memory
b) To determine the number of frames for each process
c) When paging and segmentation are to be used
d) Execution of a process, not in memory
Answer: a
Explanation: An appropriate page replacement algorithm is required when the total memory requirements
exceed the physical memory.
Answer: d
Explanation: For the given reference string of frame size 3, the number of page faults is calculated to be 15.
It is explained in the diagram.
Answer: c
Explanation: For the given reference string of frame size 4, the number of page faults is calculated to be 10.
It is explained in the diagram.
15. _________ states that, on a page fault, the frame that has been in memory the longest is replaced.
a) Belady’s anomaly
b) Second chance algorithm
c) Partial second chance algorithm
d) LRU replacement algorithm
Answer: a
Explanation: Belady’s
Answer: d
Explanation: Every Directed Acyclic Graph has one or more topological ordering whereas Cyclic and
Undirected graphs can’t be ordered topologically.
2. Most Efficient Time Complexity of Topological Sorting 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 topological sort algorithm has complexity same as Depth First Search. So, DFS has a
complexity O(V+E).
3. In most of the cases, topological sort starts from a node which has __________
a) Maximum Degree
b) Minimum Degree
c) Any degree
d) Zero Degree
Answer: d
Explanation: Topological sort starts with a node which has zero degree. If multiple such nodes exists then it
can start with any node.
Answer: d
Explanation: Topological sort tells what task should be done before a task can be started. It also detects
cycle in the graph which is why it is used in the Operating System to find the deadlock. Ordered statistics is
an application of Heap sort.
advertisement
Answer: c
Explanation: The topological sort of a graph can be unique if we assume the graph as a single linked list and
we can have multiple topological sort order if we consider a graph as a complete binary tree.
Answer: c
Explanation: We can implement topological sort by both BFS and DFS. In BFS, we use queue as data
structure and in DFS, we use Linked list (if recursive) or Stack (if not recursive) as data structure.
8. A man wants to go different places in the world. He has listed them down all. But there are some places
where he wants to visit before some other places. What application of graph can he use to determine that?
a) Depth First Search
b) Breadth First Search
c) Topological Sorting
d) Dijkstra’s Shortest path algorithm
Answer: c
Explanation: As the definition of topological sorting suggests, it is the way to do tasks in prescribed order.
So, if he does topological sorting, it will be easy for him to recognize what should be the order to visit
different places.
Answer: a
Explanation: A
Answer: b
Explanation: Quick select is a selection algorithm. It was developed by Tony Hoare, thus it is also known as
Hoare’s selection algorithm.
Answer: b
Explanation: Quickselect is an example of a selection algorithm. It finds the kth smallest element from the
given list.
3. What will be the output if quickselect algorithm is applied to the array arr={1,5,4,3,7} with k given as 4?
a) 1
b) 3
c) 4
d) 5
Answer: d
Explanation: Quickselect algorithm finds the kth smallest element from the given list. So as here the given
value of k is 4 so we need to find the fourth smallest element which is 5 in the given array.
Answer: d
Explanation: Quickselect algorithm requires no extra space in order to calculate the desired result. It
performs manipulations in the given array itself so its auxiliary space requirement will be O(1).
Answer: a
Explanation: Quickselect’s auxiliary space requirement is O(1). So quickselect qualifies as an in-place
algorithm.
advertisement
Answer: c
Explanation: Best case time complexity of quickselect is O(n). It is observed in the case where good pivots
are chosen consistently then the array size decreases exponentially and thus the required element is found in
linear time.
Answer: b
Explanation: Both quicksort and quickselect algorithms are closely related. They were developed by the
same person. Like quicksort, quickselect also works by choosing a pivot and partitioning array.
Answer: c
Explanation: In quickselect, we don’t recur for both portions of the array. Only that portion is considered
where the smallest element lies. So this causes the average time complexity to be O(n).
Answer: d
Explanation: Quickselect has a poor worst case time complexity of O(n2). There are algorithms which have
O(n) time complexity in the worst case.
b)
c)
d)
Answer: a
Explanation: In quicksel
Answer: a
Explanation: Co-ordinate compression is the process of reassigning co-ordinates in order to remove gaps.
This helps in improving efficiency of a solution.
Answer: c
Explanation:Co-ordinate compression is the process of reassigning co-ordinates in order to remove gaps.
This helps in improving both time and space complexity of a solution.
#include <bits/stdc++.h>
using namespace std;
void convert(int a[], int n)
{
vector <pair<int, int> > vec;
for (int i = 0; i < n; i++)
vec.push_back(make_pair(a[i], i));
sort(vec.begin(), vec.end());
for (int i=0; i<n; i++)
a[vec[i].second] = i;
}
void printArr(int a[], int n)
{
for (int i=0; i<n; i++)
cout << a[i] << " ";
}
int main()
{
int arr[] = {10,8,2,5,7};
int n = sizeof(arr)/sizeof(arr[0]);
convert(arr , n);
printArr(arr, n);
return 0;
}
a) 4 3 0 1 2
b) 1 2 3 4 5
c) 5 4 1 2 3
d) 0 1 2 3 4
Answer: a
Explanation: The given code converts the elements of the input array. They are replaced with their
respective position number in the sorted array.
advertisement
#include <bits/stdc++.h>
using namespace std;
void convert(int a[], int n)
{
vector <pair<int, int> > vec;
for (int i = 0; i < n; i++)
vec.push_back(make_pair(a[i], i));
sort(vec.begin(), vec.end());
for (int i=0; i<n; i++)
a[vec[i].second] = i;
}
void printArr(int a[], int n)
{
for (int i=0; i<n; i++)
cout << a[i] << " ";
}
int main()
{
int arr[] = {10,8,2,5,7};
int n = sizeof(arr)/sizeof(arr[0]);
convert(arr , n);
printArr(arr, n);
return 0;
}
a) O(n)
b) O(n log n)
c) O(n2)
d) O(log n)
Answer: b
Explanation: The time complexity of the given code will be governed by the time complexity of the sorting
algorithm used. As this code uses in built sorting of C++ so it will take O(n log n) time.
5. What is the auxiliary space complexity of the given code?
#include <bits/stdc++.h>
using namespace std;
void convert(int a[], int n)
{
vector <pair<int, int> > vec;
for (int i = 0; i < n; i++)
vec.push_back(make_pair(a[i], i));
sort(vec.begin(), vec.end());
for (int i=0; i<n; i++)
a[vec[i].second] = i;
}
void printArr(int a[], int n)
{
for (int i=0; i<n; i++)
cout << a[i] << " ";
}
int main()
{
int arr[] = {10,8,2,5,7};
int n = sizeof(arr)/sizeof(arr[0]);
convert(arr , n);
printArr(arr, n);
return 0;
}
a) O(1)
b) O(n)
c) O(log n)
d) O(n log n)
Answer: b
Explanation: The given code uses an auxiliary space of O(n). It is used by a vector which pairs each element
of the array with their respective index number of the original array.
#include <bits/stdc++.h>
using namespace std;
void convert(int arr[], int n)
{
int temp[n];
memcpy(temp, arr, n*sizeof(int));
sort(temp, temp + n);
unordered_map<int, int> map;
int sort_index = 0;
for (int i = 0; i < n; i++)
map[temp[i]] = sort_index++;
for (int i = 0; i < n; i++)
arr[i] = map[arr[i]];
}
void printArr(int arr[], int n)
{
for (int i=0; i<n; i++)
cout << arr[i] << " ";
}
int main()
{
int arr[] = {3,5,2,4};
int n = sizeof(arr)/sizeof(arr[0]);
convert(arr , n);
printArr(arr, n);
return 0;
}
a) 0 2 3 4
b) 1 3 0 2
c) 2 4 1 3
d) 1 2 3 4
Answer: b
Explanation: The given code converts the elements of input array. They are replaced with their respective
position number in the sorted array.
#include <bits/stdc++.h>
using namespace std;
void convert(int arr[], int n)
{
int temp[n];
memcpy(temp, arr, n*sizeof(int));
sort(temp, temp + n);
unordered_map<int, int> map;
int sort_index = 0;
for (int i = 0; i < n; i++)
map[temp[i]] = sort_index++;
for (int i = 0; i < n; i++)
arr[i] = map[arr[i]];
}
void printArr(int arr[], int n)
{
for (int i=0; i<n; i++)
cout << arr[i] << " ";
}
int main()
{
int arr[] = {10, 20, 15, 12, 11, 50};
int n = sizeof(arr)/sizeof(arr[0]);
convert(arr , n);
printArr(arr, n);
return 0;
}
a) O(n)
b) O(1)
c) O(n log n)
d) O(n2)
Answer: c
Explanation: The time complexity of the given code will be governed by the time complexity of the sorting
algorithm used. As this code uses inbuilt sorting of C++ so it will take O(n log n) time.
#include <bits/stdc++.h>
using namespace std;
void convert(int arr[], int n)
{
int temp[n];
memcpy(temp, arr, n*sizeof(int));
sort(temp, temp + n);
unordered_map<int, int> map;
int sort_index = 0;
for (int i = 0; i < n; i++)
map[temp[i]] = sort_index++;
for (int i = 0; i < n; i++)
arr[i] = map[arr[i]];
}
void printArr(int arr[], int n)
{
for (int i=0; i<n; i++)
cout << arr[i] << " ";
}
int main()
{
int arr[] = {10, 20, 15, 12, 11, 50};
int n = sizeof(arr)/sizeof(arr[0]);
convert(arr , n);
printArr(arr, n);
return 0;
}
a) O(n)
b) O(1)
c) O(log n)
d) O(n log n)
Answer: a
Explanation: The given code uses an auxiliary space of O(n). It is used by a vector which pairs each element
of the array with their respective index number of the original array.
Answer: a
Explanation: The idea behind co-ordinate compression is to reduce the number of squares in a graph by
converting them into rectangles of viable size. This reduces the time complexity of traversal.
Answer: b
Explanation: Co-ordinate compression technique can be applied where such optimization is suitable. It does
not require to co
Answer: a
Explanation: Square decomposition is mainly used in competitive programming to optimize code. It reduces
the time complexity by a factor of √n.
2. By what factor time complexity is reduced when we apply square root decomposition to a code?
a) n
b) √n
c) n2
d) n-1/2
Answer: b
Explanation: In square root decomposition a given array is decomposed into small parts each of size √n.
This reduces the time complexity of the code by a factor of √n.
3. What will be the worst case time complexity of finding the sum of elements in a given range of (l,r) in an
array of size n?
a) O(n)
b) O(l+r)
c) O(l-r)
d) O(r-l)
Answer: a
Explanation: For a given array of size n we have to traverse all n elements in the worst case. In such a case
l=0, r=n-1 so the time complexity will be O(n).
4. What will be the worst case time complexity of finding the sum of elements in a given range of (l,r) in an
array of size n when we use square root optimization?
a) O(n)
b) O(l+r)
c) O(√n)
d) O(r-l)
Answer: c
Explanation: When we use square root optimization we decompose the given array into √n chunks each of
size √n. So after calculating the sum of each chunk individually, we require to iterate only 3*√n times to
calculate the sum in the worst case.
5. Total how many iterations are required to find the sum of elements in a given range of (l,r) in an array of
size n when we use square root optimization?
a) √n
b) 2*√n
c) 3*√n
d) n*√n
Answer: c
Explanation: After calculating the sum of each chunk individually we require to iterate only 3*√n times to
calculate the sum in the worst case. It is because two of the √n factors consider the worst case time
complexity of summing elements in the first and last block. Whereas the third √n considers the factor of
summing the √n chunks.
advertisement
6. What will be the time complexity of update query operation in an array of size n when we use square root
optimization?
a) O(√n)
b) O(n)
c) O(1)
d) O(n2)
Answer:c
Explanation: The time complexity of query operation remains the same in both square root optimized code
and non optimized code. We simply find the chunk in which the update requires to be performed and then
add the new updated value at the desired index.
7. Square root decomposition technique is only applicable when the number of indices in an array is a
perfect square.
a) true
b) false
Answer: b
Explanation: Square root decomposition technique can be applied to an array with any number of indices. It
does not require this number to be a perfect square.
8. What will be the worst case time complexity of code to find sum in given query range (l,r) in an array of
size n with q number of such queries?
a) O(n)
b) O(q)
c) O(n*q)
d) O(n+q)
Answer: c
Explanation: For finding the result of one query the worst case time complexity will be n. So for q queries
the time complexity will be O(q*n). This can be reduced by using square root optimization.
9. What will be the worst case time complexity of code to find sum in given query range (l,r) in an array of
size n with q number of such queries when we apply MO’s algorithm?
a) O(n*q)
b) O(n)
c) O((q+n)√n)
d) O(q*√n)
Answer: c
Explanation: Mo’s algorithm requires O(q*√n) + O(n*√n) time for processing all the queries. It is better
than the naive solution where O(n*q) time is required.
10. Mo’s algorithm can only be used for problems where the query can be calculated from the result of the
previous query.
a) true
b) false
Answer: a
Explanation: Mo’s algorithm uses the result of the previous query in order to compute the result of the given
query. It cannot be implemented where such a scenario is not possible.
11. What will be the time complexity of the code to find a minimum element from an array of size n and
uses square root decomposition(exclude pre processing time)?
a) O(√n)
b) O(n)
c) O(1)
d) O(n2)
Answer: a
Explanation: For finding the minimum element in a given array of size n using square root decomposition
we first divide t