Algorithms – Typical Campus Interview Questions

advertisement
FAQ’s during Campus Placement
Analysis and Design of Algorithms
About Technical Interviews
A technical interview is a type of interview that typically features questions that are specific to
the role you have applied for. Technical interviews are generally used to assess candidates for
technical or specialist graduate job positions (such as jobs in IT, Engineering and Science) rather
than general graduate schemes.
In a technical interview candidates are likely to be asked questions that relate to specific
knowledge about the company's technical activities relate to understanding the technical work
required to be completed as part of the job applied for relate to work completed as part of a
degree course (if this relates to the job applied for) require candidates to solve actual technical
problems that they would be likely to face if employed.
Data structures and algorithm questions are important part of any
programming job interview, be it a Java interview, C++ interview or
any other programming language. Since data structures is core
programming concept, its mandatory for all programmers, to know basic
data structures like stack, linked list, queue, array, tree and graph.
Though tree and graph are on tough side, I still see programmers to
get familiar will all these. Any list of programming job interview
questions is incomplete without questions from data structures and
algorithms. Similarly while going on questions from data structure you
may get some programming exercise as well e.g. swapping numbers
without temp variable . Linked list and arrays are favorite topics in
any data structure interview, questions like reversing linked list,
traversing linked list or deleting nodes from linked list, which
involves algorithm and data structures are quite common. Similarly,
finding duplicates in array, finding missing numbers, sorting arrays
are very popular. You can also expect questions from stack, queue,
array, linked list, tree, graph and HashMap are most common in any
data structure interview.
Some questions of best case, worst case etc are sure.
Algorithms Interview Questions-Interview Questions and Answers
1. Define the concept of an algorithm.
An algorithm is any well-defined computational procedure that takes
some value (or set of values) as input and produces some value (or set
of values) as output. In short, it can be seen as a sequence of
computational steps that transform the input into the output.
1
2.What are the arguments present in pattern matching algorithms?
These are the following arguments which are present in pattern
matching Algorithms.
1) Subject,
2) Pattern
3) Cursor
4) MATCH_STR
5) REPLACE_STR
6) REPLACE_FLAG
3. Explain the function SUB in algorithmic notation?
In the algorithmic notation rather than using special marker symbols,
generally people use the cursor position plus a substring length to
isolate a substring. The name of the function is SUB.
SUB returns a value the sub string of SUBJECT that is specified by
the parameters i and j and an assumed value of j.
4. In Algorithmic context how would you define book keeping
operations?
Usually when a user wants to estimate time he isolates the specific
function and brands it as active operation. The other operations in
the algorithm, the assignments, the manipulations of the index and the
accessing of a value in the vector, occur no more often than the
addition of vector values. These operations are collectively called as
“book keeping operations”.
5. Define and describe an iterative process with general steps of flow
chart?
There are four parts in the iterative process they are
Initialization: -The decision parameter is used to determine when to
exit from the loop.
Decision: -The decision parameter is used to determine whether to
remain in the loop or not.
Computation: - The required computation is performed in this part.
Update: - The decision parameter is updated and a transfer to the
next iteration results.
6. State recursion and its different types?
Recursion is the name given to the technique of defining a set or a
process in terms of itself. There are essentially two types of
recursion. The first type concerns recursively defined function and
the second type of recursion is the recursive use of a procedure.
7. Define and state the importance of sub algorithm in computation and
its relation ship with main algorithm?
A sub algorithm is an independent component of an algorithm and for
this reason is defined separately from the main algorithm. The purpose
of a sub algorithm is to perform some computation when required, under
control of the main algorithm. This computation may be performed on
zero or more parameters passed by the calling routine.
2
8. Name any three skills which are very important in order to work
with generating functions.
The three most important skills which are used extensively while
working with generating functions are
1)Manipulate summation expressions and their indices.
2)Solve algebraic equations and manipulate algebraic expressions,
including partial function decompositions.
3)Identify sequences with their generating functions
9. What is the general strategy for Markov Algorithm?
The general strategy in a Markov Algorithm is to take as input a
string x and y, through a number of steps in the algorithm, transform
x to an output string y. this transformation process is generally
performed in computers for text editing or program compilation.
10. Define string in an algorithmic notation and an example to support
it?
In the algorithmic notation, a string is expressed as any sequence of
characters enclosed in single quote marks.
11. How to find median of a BST?
Find the no. of elements on the left side.
If it is n-1 the root is the median.
If it is more than n-1, then it has already been found in the left
subtree.
Else it should be in the right subtree
12. What is Diffie-Hellman?
It is a method by which a key can be securely shared by two users
without any actual exchange.
13. What is the goal of the shortest distance algorithm?
The goal is completely fill the distance array so that for each
vertex v, the value of distance[v] is the weight of the shortest path
from start to v.
14. Explain the depth of recursion?
This is another recursion procedure which is the number of times the
procedure is called recursively in the process of enlarging a given
argument or arguments. Usually this quantity is not obvious except in
the case of extremely simple recursive functions, such as FACTORIAL
(N), for which the depth is N.
15. Explain about the algorithm ORD_WORDS?
This algorithm constructs the vectors TITLE, KEYWORD and T_INDEX.
16. Which are the sorting algorithms categories?
Sorting algorithms can be divided into five categories:
a) insertion sorts
b) exchange sorts
3
c) selection sorts
d) merge sorts
e) distribution sorts
17.Define a brute-force algorithm. Give a short example.
A brute force algorithm is a type of algorithm that proceeds in a
simple and obvious way, but requires a huge number of steps to
complete. As an example, if you want to find out the factors of a
given number N, using this sort of algorithm will require to get one
by one all the possible number combinations.
18. What is a greedy algorithm? Give examples of problems solved using
greedy algorithms.
A greedy algorithm is any algorithm that makes the local optimal
choice at each stage with the hope of finding the global optimum. A
classical problem which can be solved using a greedy strategy is the
traveling salesman problem. Another problems that can be solved using
greedy algorithms are the graph coloring problem and all the NPcomplete problems.
19. What is a backtracking algorithm? Provide several examples.
It is an algorithm that considers systematically all possible outcomes
for each decision. Examples of backtracking algorithms are the eight
queens problem or generating permutations of a given sequence.
20. What is the difference between a backtracking algorithm and a
brute-force one?
Due to the fact that a backtracking algorithm takes all the possible
outcomes for a decision, it is similar from this point of view with
the brute force algorithm. The difference consists in the fact that
sometimes a backtracking algorithm can detect that an exhaustive
search is unnecessary and, therefore, it can perform much better.
21. Describe divide and conquer paradigm.
When a problem is solved using a divide and conquer algorithm, it is
subdivided into one or more subproblems which are all similar to the
original problem in such a way that each of the subproblems can be
solved independently. In the end, the solutions to the subproblems are
combined in order to obtain the solution to the original problem.
22. Describe on short an insertion sorting algorithm.
An algorithm that sorts by insertion takes the initial, unsorted
sequence and computes a series of sorted sequences using the following
rules:
a) the first sequence in the series is the empty sequence
b) given a sequence S(i) in the series, for 0<=i<n, the next sequence
in the
series, S(i+1), is obtained by inserting the (i+1)th element of the
unsorted sequence S(i+1) into the correct position in S(i).
23. Which are the advantages provided by insertion sort?
Insertion sort provides several advantages:
4
a) simple implementation
b) efficient for small data sets
c) adaptive - efficient for data sets that are already substantially
sorted:
the time complexity is O(n + d), where d is the number of inversions
d) more efficient in practice than most other simple quadratic, i.e.
O(n2) algorithms such as selection sort or bubble sort; the best case
(nearly sorted input) is O(n)
e) stable - does not change the relative order of elements with equal
keys
f) in-place - only requires a constant amount O( 1) of additional
memory space
g) online - can sort a list as it receives it
24. Shortly describe the quicksort algorithm.
In quicksort, the steps performed are the following:
a) pick an element, called a pivot, from the list
b) reorder the list so that all elements with values less than the
pivot come
before the pivot, while all elements with values greater than the
pivot come after it (equal values can go either way)
c) recursively sort the sub-list of lesser elements and the sub-list
of greater elements
25. What is the difference between selection and insertion sorting?
In insertion sorting elements are added to the sorted sequence in an
arbitrary order. In selection sorting, the elements are added to the
sorted sequence in order so they are always added at one end.
26. What is merge sorting?
Merging is the sorting algorithm which combines two or more sorted
sequences into a single sorted sequence. It is a divide and conquer
algorithm, an O(n log n) comparison-based sorting algorithm. Most
implementations produce a stable sort, meaning that the implementation
preserves the input order of equal elements in the sorted output.
27. Which are the main steps of a merge sorting algorithm?
Sorting by merging is a recursive, divide-and-conquer strategy. The
basic steps to perform are the following:
a) divide the sequence into two sequences of length
b) recursively sort each of the two subsequences
c) merge the sorted subsequences to obtain the final result
28. Provide a short description of binary search algorithm.
Binary search algorithm always chooses the middle of the remaining
search space, discarding one half or the other, again depending on the
comparison between the key value found at the estimated position and
the key value sought. The remaining search space is reduced to the
part before or after the estimated position.
29. What is the linear search algorithm?
5
Linear search is a method for finding a particular value in a list
which consists of checking every one of its elements, one at a time
and in sequence, until the desired one is found. It is the simplest
search algorithm, a special case of brute-force search. Its worst case
cost is proportional to the number of elements in the list; and so is
its expected cost, if all list elements are equally likely to be
searched for. Therefore, if the list has more than a few elements,
other methods (such as binary search or hashing) may be much more
efficient.
30. What is best-first search algorithm?
It is a search algorithm that considers the estimated best partial
solution next. This is typically implemented with priority queues.
31. What is Huffman coding?
In computer science and information theory, Huffman coding is an
entropy encoding algorithm used for lossless data compression. The
term refers to the use of a variable-length code table for encoding a
source symbol (such as a character in a file) where the variablelength code table has been derived in a particular way based on the
estimated probability of occurrence for each possible value of the
source symbol.
Algorithms Advanced-Interview Questions and Answers
1. How do you count number of bits in a Integer?
1. Not Possible
2. Possible but have to convert Integer to binary format and check
manually
3. Solution exists in C
4. Possible using assembly language
Solution: 3
int no_of_bits = 0;
int given_number;
//this is the number taken as input
while (given_number != 0)
{
if (given_number % 2)
no_of_bits ++;
given_number = given_number >> 1;
}
This algorithm checks if the number is zero, in which case the number
of bits set will be zero, and enters ‘while’ loop if it is not zero.
Every time it enters the loop it will check if the right most digit is
set or not by doing mod 2 (any number mod 2 returns 1 if the right
most digit is one else returns 0). If it is set then it will increment
the counter by 1 and then right shifts the number by 1 digit. Like
6
this it will check for all digits until the number becomes zero and
exits the loop. When the loop exits no_of_bits will be the answer.
Alternate Solution:
int count = 0;
int n;
//input number
while (n)
{
n = n & (n-1);
count ++;
}
2. Given a string, can you find the first non-repeated character in
it?
1. Solution does not exists
2. Solution exists @ O(n^2)
3. Solution exists @ O(n.logn)
Solution: 3
/** declare a linked list named llist, also write basic functions to
add and
delete node from a linked list **/
char given_array [];
input
//this is the array taken as
add (llist, given_array [0] );
array to
linked list (make sure
appends the
new value at the end)
// adds the first character of
//the add function
for (int i = 1; given_number[i]; i++)
{
do
{
if (llist->value == given_array [i] )
delete (llist, given_array [i] );
7
else
add (llist, given_array [i] );
} while (llist = llist->next);
}
Form a linked list with the characters in the string as nodes. While
adding the character to the list, check if its already existing. If it
exists then delete that node from the linked list and go for the next
character. Once the whole string is completed, the node at the head of
the linked list contains the first non-repeated character of the
string.
3. What does the following algorithm do?
1. Reverse an integer bit-wise. E.g., if input is 12 (00001110) output
will be 01110000.
2. Reverse an Integer normally. E.g., if input is 1234, output will be
4321
3. Right Rotate a number by N positions
4. Left Rotate a number by N positions
Solution:1
int given_number;
int output_number = 0;
//this is the number taken as input
for ( int i = 0; i < INTEGER_SIZE; i++ )
{
output_number = output_number << 1;
if (given_number % 2)
output_number ++;
given_number = given_number >> 1;
}
4. Given an algorithm to revers an integer. Output of 1234 should be
4321.
1. Reverse an integer bit-wise. E.g., if input is 12 (00001110) output
will be 01110000.
2. Reverse an Integer normally. E.g., if input is 1234, output will be
4321
8
3. Right Rotate a number by N positions
4. Left Rotate a number by N positions
Solution:2
int given_number;
int output_number = 0;
//this is the number taken as input
while (given_number != 0)
{
output_number = output_number * 10;
output_number = given_number % 10;
given_number = given_number / 10;
}
5.
1.
2.
3.
4.
Can you right-rotate a string by k-positions.
Not Possible in C
Solution exists @ O(log n)
Solution exists @ O(n^2)
Solution exists @ O(n.log n)
Solution:4
int k;
char input [];
int len;
// given as input - ‘k’ position to be rotated
// given as input
// length of the input string
for (int i = 0; i < k; i++)
{
char c = input [len - 1];
for (int j = len -1; j > 0; j++)
input [j] = input [j -1];
input [0] = c;
}
6. Can you compare two strings whether the second string is rotated
version of the first? E.g., ‘GOOGLE’ is rotated version of ‘GLEGOO’,
‘OOGLEG’, etc,.
9
1.
2.
3.
4.
No Solution
Solution exists @ O(log n)
Solution exists @ O(n)
Solution exists @ O(n.log n)
Solution:3
Solution for this problem is a bit tricky one. First we have to form a
circularly linked list of the two strings. Now declare two pointers
for the two lists and move both the pointers forward. If the current
characters match, move both the pointers by 1 node else move only the
first pointer. One more condition which has to be checked is lets say
both the strings are moved by few characters and they matched but
after that they are different, in this case the second pointer has to
be reset to its head. At some point if both lists have same nodes
for the iterations equal to length of the string then they are rotated
versions else if first list reaches the end (i.e., completes
traversing for the length of the string) then they are not rotated
versions.
7. What does the following algorithm do?
int f1 (int x,int y)
{
if (!y)
return(x);
else
return(f1(y,x(mod)y);
}
1.
2.
3.
4.
Find
Find
Find
Find
X^Y
GCD of 2 Numbers
LCM of 2 Numbers
Yth element in GP of X, XY, XY2,..
Solution:2
8. In selecting the pivot for QuickSort, which is the best choice for
optimal partitioning:
a.The first element of the array
b.The last element of the array
c.The middle element of the array
d.The largest element of the array
e.The median of the array
Solution:e
10
While the choices a,b,c will always not guarantee O(NlogN)
complexity,choice d always gives quadratic run time.choice e
guarantees even partition of the array.Hence it is the optimal
partition. hence the sol is e.
9.
1.
2.
3.
What is the worst case scenario for QuickSort.
Pivot is Maximum
Pivot is Median
Both of the above.
Solution:1
In the worst case,the pivot selected will always be the maximum
element leading to quadratic time complexity.In this case as it
depicts the behaviour of bubble sort,where in maximum element always
bubbles to the end
10. What the following algorithm do?
void rep_str (char *str)
{
if (*str!=NULL)
rep_str(str+1);
printf (“%c”,str);
}
1.
2.
3.
4.
Prints
Prints
Prints
Prints
next character of every character in the string
the string character by character
reverse of the string
just last character of the string
Solution:3
TOP 30 IMPORTANT QUESTION OF DAA
Q1. Write Master’s method for solving recurrence relations.
Q2. What do u understand by STABLE SORT? Name two stable sort algorithms with
examples.
Q3. What do u mean by asymptotic notations? What is importance of average-case analysis
of algorithms?
Q4. Explain the concept of partitioning of the given set to be sorted using quick-sort
algorithm.
Q5. Discuss the basic steps in the complete development of an algorithm.
Q6. Write modify quick-sort algorithm.
Q7. Write Merge sort algorithm with an example.
11
Q8. Describe Red-black trees and B-tree properties. Also write down RB-INSERTION
algorithm.
Q9. Prove that a Red-black tree with n internal nodes has height at most 2log(n+1).
Q10.Prove that the maximum degree of any node in an n-node binomial tree is logn.
Q11. What do u understand by Binomial Heap? How to merge two binomial Heaps.
Q12. Describe RB-Deletion procedure with an example.
Q13. When and how Dynamic programming approach is applicable? Discuss matrix chain
multiplication with reference to dynamic programming technique.
Q14. Discuss backtracking problem solving approach with the help of an example.
Q15. Discuss Greedy approach for problem solving such as activity selection , fractional
knapsack.
Q16. Describe hamiltonian circuit and n-queen problem.
Q17. Give recursive solution to traveling sales man problem.
Q18. Given a graph G(V,E) and let V1 and V2 be two distinct vertices Explain how to modify
Dijkstra’s shortest path algorithm to determine the number of distinct shortest paths from
V! to V2.Also comment on whether Dijkstra’s shortest path algorithm work correctly if
weight are negative.
Q19. Explain the Floyd-Warshall algorithm with example.
Q20. Prove that if the weights on the edge of the connected undirected graph are distinct
then there is a unique minimum spanning tree. Give an example in this context. Also
discuss Kruskal’s algorithm.
Q21. Describe PRIM’s algorithm to find MST along with its running time.
Q22. What is Maximum flow problem? Describe FORD-FULKERSON algorithm for solving
maximum flow.
Q23. Explain LCS problem using dynamic programming approach.
Q24. Explain NP-Complete and NP- Hard problem. Also Discuss the decision problems of
class P and NP.
Q25. Explain KMP algorithm for String Matching .What is its running time.
Q26. Explain Rabin-Karp and Boyer-Moore String matching algorithm with examples
Q27. What are approximation algorithm ? What is meant by P(n)-approximation algorithm?
Give an approximation algorithm for TSP.
Q28. Discuss Vertex cover problem using approximation technique and prove that vertex
cover problem is 2- approximation .
Q29. Write about randomized algorithm .What is Convex Hull problem?
Q30. Explain deletion procedure into a B-tree.
NOTE:- These are only Theoretical problems. you must solve all numerical problems along
with these theoretical problems.
Data Structures and Algorithm Interview Questions for Java Programmers
Data Structure and Algorithm Interview Questions answers for Java
programmerThis is combined list of questions from various data
structure e.g. array, linked list, stack or queue. It includes some
coding questions as well, which gel with data structures.
Question 1 : How to find middle element of linked list in one pass?
One of the most popular question from data structures and algorithm,
mostly asked on telephonic interview. Since many programmer know that,
in order to find length of linked list we need to first traverse
through linkedlist till we find last node, which is pointing to null,
and then in second pass we can find middle element by traversing only
12
half of length. They get confused when interviewer ask him to do same
job in one pass. In order to find middle element of linked list in one
pass you need to maintain two pointer, one increment at each node
while other increments after two nodes at a time, by having this
arrangement, when first pointer reaches end, second pointer will point
to middle element of linked list. See this trick to find middle
element of linked list in single pass for more details.
Question 2 : How to find if linked list has loop ?
This question has bit of similarity with earlier algorithm and data
structure interview question. I mean we can use two pointer approach
to solve this problem. If we maintain two pointers, and we increment
one pointer after processing two nodes and other after processing
every node, we are likely to find a situation where both the pointers
will be pointing to same node. This will only happen if linked list
has loop.
Question 3 : How to find 3rd element from end in a linked list in one
pass?
This is another frequently asked linked list interview question. This
question is exactly similar to finding middle element of linked list
in single pass. If we apply same trick of maintaining two pointers and
increment other pointer, when first has moved upto 3rd element, than
when first pointer reaches to the end of linked list, second pointer
will be pointing to the 3rd element from last in a linked list.
Question 4 : In an integer array, there is 1 to 100 number, out of one
is duplicate, how to find ?
This is a rather simple data structures question, especially for this
kind of. In this case you can simply add all numbers stored in array,
and total sum should be equal to n(n+1)/2. Now just subtract actual
sum to expected sum, and that is your duplicate number. Of course
there is a brute force way of checking each number against all other
numbers, but that will result in performance of O(n^2) which is not
good. By the way this trick will not work if array have multiple
duplicates or its not numbers forming arithmetic progression. Here is
example of one way to find duplicate number in array.
Question 6 : How to reverse String in Java ?
This is one of my favorite question. Since String is one of the most
important type in programming, you expect lot of question related to
String any data structure interview. There are many ways to reverse
Sting in Java or any other programming language, and interviewer will
force you to solve this problem by using without API i.e. without
using reverse() method of StringBuffer. In follow-up he may ask to
reverse String using recursion as well. See 3 ways to reverse String
in Java to learn reversing String using both loops and recursion in
Java.
Question 7 : Write a Java program to sort a array using Bubble Sort
algorithm?
13
I have always send couple of questions from searching and sorting in
data structure interviews. Bubble sort is one of the simplest sorting
algorithm but if you ask anyone to implement on the spot it gives you
an opportunity to gauge programming skills of a candidate. See How to
sort array using Bubble Sort in Java for complete solution of this
datastrucutre interview question.
Question 8 : What is difference between Stack and Queue data structure
?
One of the classical datastrucutre interview question. I guess every
one know, No? Any way main difference is that Stack is LIFO(Last In
First Out) data structure while Queue is a FIFO(First In First Out)
data structure.
Question 9 : How do you find duplicates in array if there is more than
one duplicate?
Sometime this is asked as follow-up question of earlier datastrucutre
interview question, related to finding duplicates in Array. One way of
solving this problem is using a Hashtable or HashMap data structure.
You can traverse through array, and store each number as key and
number of occurrence as value. At the end of traversal you can find
all duplicate numbers, for which occurrence is more than one. In Java
if a number already exists in HashMap then calling get(index) will
return number otherwise it return null. this property can be used to
insert or update numbers in HashMap.
Question 10 : What is difference between Singly Linked List and Doubly
Linked List data structure?
This is another classical interview question on data structure, mostly
asked on telephonic rounds. Main difference between singly linked list
and doubly linked list is ability to traverse. In a single linked
list, node only points towards next node, and there is no pointer to
previous node, which means you can not traverse back on a singly
linked list. On the other hand doubly linked list maintains two
pointers, towards next and previous node, which allows you to navigate
in both direction in any linked list.
Question 11 : Write Java program to print Fibonacci series ?
This is not a data structures question, but a programming one, which
many times appear during data structure interview. Fibonacci series is
a mathematical series, where each number is sum of previous two
numbers e.g. 1,1, 2, 3, 5, 8, 13, 21. Interviewer is often interested
in two things, a function which returns nth number in Fibonacci series
and solving this problem using recursion in Java. Though, its easy
question, recursion part often confuses beginners. See this link to
find nth Fibonacci number in Java.
Question 12 : Write Java program to check if a number is palindrome or
not?
This is similar to previous question, not directly related to data
structures, but quite popular along with other questions. A number is
called palindrome, if reverse of number is equal to number itself.
14
Interviewer ask to solve this problem without taking help from Java
API or any open source library. Any way it’s simple question, you can
use division operator (/) and remainder operator (%) to solve this
question. Just remember, division operator can be used to get rid of
last digit e.g. 1234/10 will give you 123, and modulus operator can
give you last digit e.g. 1234%10 will return 4. By the way, here is a
Java program check if number is palindrome or not.
Question 13 : What is binary search tree?
This is a data structure question from Tree data structures. Binary
Search Tree has some special properties e.g. left nodes contains items
whose value is less than root , right sub tree contains keys with
higher node value than root, and there should not be any duplicates in
the tree. Apart from definition, interview can ask you to implement
binary search tree in Java and questions on tree traversal e.g. IN
order, preorder, and post order traversals are quite popular data
structure question.
Question 14 : How to reverse linked list using recursion and
iteration?
This is another good question on data structures. There are many
algorithm to reverse linked list and you can search of them using
google. I am thinking of writing another blog post to explain linked
list reversal and will share with you later.
Question 15 : Write a Java program to implement Stack in Java?
You can implement Stack by using array or linked list. This question
expect you to implement standard method provided by stack data
structure e.g. push() and pop(). Both push() and pop() should be
happen at top of stack, which you need to keep track. It’s also good
if you can implement utility methods like contains(), isEmpty() etc.
By the way JDK has java.util.Stack class and you can check it’s code
to get an idea. You can also check Effective Java book, where Josh
Bloch has explains how an incorrect implementation of stack can cause
memory leak in Java.
That's all on this list of data structure interview questions and
answers. This is one topic, which is always asked in any programming
interview, doesn't matter if you are C, C++, or Java developer, basic
knowledge of data structure like array, linked list, stack, queue,
tree are must to clear any programming interview.
Multiple Choice Questions
1.
If all c(i, j )’s and r(i, j)’s are calculated, then OBST algorithm in worst case
takes one of the following time.
(a) O(n log n)
(b) O(n3)
(c) O(n2)
(d) O(log n)
15
(e) O(n4).
2. The following is a weighted binary tree, then what is the weighted array for
the TVS problem?
(a)
(b)
(c)
(d)
(e)
3.
[9, 2, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 4]
[9, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 4, 6]
[9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 6, 7, 4]
[9, 2, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 6, 4]
[9, 2, 0, 0, 0, 7, 0, 0, 0, 0, 6, 4, 0, 0].
What are the entries of the array TREE[ ] for the above weighted binary tree
for the TVS problem.
(a) [1, 2, 3, 4, 5, 6, 0, 0]
(b) [1, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 4, 5, 6]
(c) [1, 2, 3, 0, 0, 0, 0, 4, 5, 6]
(d) [1, 2, 3, 0, 0, 0, 0, 0, 4, 5, 6]
(e) [1, 2, 3, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 5, 6].
4. For a 15-puzzle problem let the initial arrangement be the following one, then
answer the questions 4 – 7 with the following arrangement.
10
9
12
11
13
1
2
15
4
8
5
7
14
6
3
What is the value of ‘x’ used to find the reachability of the solution?
(a) 1
(b) 0
(c) 8
(d) 10
(e) 13.
16
5.
The values for the position(i), position(j) where i = 14 and j =11, are
(a) 2, 8
(b) 8, 2
(c) 8, 13
(d) 2, 13
(e) 13, 8.
6. The values for less(i), less(j) where i =5, j =7 are
(a) 0, 6
(b) 6, 0
(c) 2, 4
(d) 2, 6
(e) 1, 6.
7.
What is the value to find the reachability of the problem with which you can
say the solution is reachable or not?
(a) 71
(b) 72
(c) 73
(d) 69
(e) 68.
8. The upper bound on the time complexity of the nondeterministic sorting
algorithm is
(a) O(n)
(b) O(n log n)
(c) O(1)
(d) O( log n)
(e) O(n2).
9. The worst case time complexity of the nondeterministic dynamic knapsack
algorithm is
(a) O(n log n)
(b) O( log n)
(c) O(n2)
(d) O(n)
(e) O(1).
10. For the LCBB solution of knapsack problem with the data (p1–p4) =
(10,10,12,18) and (w1–w4) = (2, 4, 6, 9) and m = 18, then the values of u(1)
and ĉ(1) respectively are
(a) -38, -44
(b) -44, -38
(c) -44, -32
(d) -32, -44
(e) -32, -38.
17
Answers
1.
Answer : (b)
Reason: As we have to calculate c(i,j), w(i,j) and r(i,j).
2.
Answer : (d)
Reason: If we create a full binary tree then the non existing nodes will have the
corresponding edge values to zero.
3.
Answer : (e)
Reason: If we create a full binary tree then the non existing nodes will have the
corresponding node values to zero.
4.
Answer : (a)
Reason: ‘x’ takes the value 0 if it is there in shaded position which starts from second
square and goes across every alternative square in the initial arrangement,
otherwise it takes one. In this question it is there in shaded square.
5.
Answer : (c)
Reason: position( x ) = the square number with in which value ‘x’ is there.
6.
Answer : (e)
Reason: less( x ) is the number of all js, such that j < x and position( j ) >
position(x).
7.
Answer : (b)
Reason: The value to define reachable is “sum of less(i) + x”, where i takes the values
from 1 to 15, and ‘x’ is value defined in question(4).
8.
Answer : (a)
Reason: In the algorithm there is only one for loop which runs from 1 to n.
9.
Answer : (d)
Reason: In the algorithm there is only one for loop which runs from 1 to n.
10.
Answer : (d)
Reason: u(1) is the negation of sum of all profits so long as the weights as whole can be
taken [ -(10+10+12)]. ĉ(1) is the value of u(1) and the negation of profit of the
fraction of the next element taken to fill the knapsack [ u(1) + -( 6/9*18) ].
11. If for the above problem, the tree is created following the FIFOBB, then the
values for ĉ (5) and u(5) respectively are
(a) -40, -40
(b) -40, -38
(c) -40, -32
(d) -22, 32
(e) -32, -22.
12. There is a chain of 20 stores; each of the store having 5 departments. Then,
which of the following is a correct representation of array size?
(a) 5 * 20
(b) 6 * 21
(c) 20 * 5
(d) 21 *
6
(e) 19 * 4.
13. From the following, select the valid data structure which reflects hierarchical
relationship between the elements.
18
14.
15.
16.
17.
18.
19.
20.
(a) Graph
(b) Queue
(c) Linked list
(d)
Stack
(e) Tree.
Which of the following matrix does have high proportions of zero entries as
the elements?
(a) Inverse Matrix
(b) Sparse Matrix
(c)
Determinant Matrix
(d) Square Matrix
(e) Transpose Matrix.
Let there is a queue whose initial values for Front and Rear are 0 and 1
respectively. Later queue found to be having the elements 3, 2, 1, 5. If a new
element is inserted in the queue, then which of the following statements is
correct?
(a) Front = 0 and Rear = 5
(b) Front = 0 and Rear = 4
(c) Front = 1 and Rear = 4
(d) Front = 1 and Rear = 5
(e) Insertion is not possible as there is no space in the queue.
One from the following is also known as Pre-Order traversal. What that one
is?
(a) LNR
(b) LRN
(c) RLN
(d)
RNL
(e) NLR.
Which of the following data structure is the best example for the multitasking
systems?
(a) Tree
(b) Queue
(c) Stack
(d) Linked
List
(e) Graph.
The initial configuration of the queue is having the elements ‘x, y, z, a’ forming
a queue. To get the new configuration ‘a, z, y, x’ one needs a minimum of
(a) 3 additions and 4 deletion
(b) 3 deletions and 4 additions
(c) 3 deletions and 2 additions
(d) 3 deletions and 3 additions
(e) 4 deletions and 4 additions.
To form the new configuration in the above problem, what best data structure
is seems to be used?
(a) Tree
(b) Queue
(c) Linked List
(d) Circular
Queue (e) Stack.
Recursive algorithms are based on
(a) Divide and conquer approach
(b) Top-down approach
(c) Bottom-up approach
(d) Hierarchical approach
(e) Heuristic approach.
Answers
19
11.
Answer : (a)
Reason: Node 5 is a node generated if first element is taken and the second object is rejected. And just
calculate as question(10).
12.
Answer : (c)
Reason: Its array [20][5] and hence 20 * 5.
13.
Answer : (e)
Reason: Tree, according to the organization of tree a node may have a child and a parent also.
14.
Answer : (b)
Reason: As sparse matrix is a matrix where the number of zeros are much than that of non zero
elements.
15.
Answer : (a)
Reason: As a new element is inserted at a position pointed by Rear, And Rear is incremented after
insertion.
16.
Answer : (e)
Reason: As in Pre-Order the traverse is as Node( root node), then Left node and Right node.
17.
Answer : (b)
Reason: Because a queue is used to hold the jobs which are waiting for their turn to work with the
common processor.
18.
Answer : (d)
Reason: Because, first we have to delete ‘x’, ‘y’, ‘z’ and then insert ‘z’, ‘y’, ‘x’. And hence three deletions
first followed by three additions.
19.
Answer : (e)
Reason: As in the above discussion ‘x’ is deleted first but inserted at last. Hence there should be a stack
to hold the deleted entries from above queue.
20.
Answer : (b)
Reason: As in case of recursions the ARIs are created, and the recursive function is called by other
function first, then it calls itself util a condition is met.
21. What do you call the selected keys in the quick sort method?
(a) Outer key (b) Inner Key
(c) Partition key
(d) Pivot key (e) Recombine key.
22. Primary clustering occurs in
(a) Linear probing
(b) Quadratic probing
(c) Mid-square method (d) Order probing
(e)
Chaining.
23. How many nodes do a full binary tree with ‘N’ leaves contain?
(a) 2N nodes
(b) N nodes (c) 2N-1 nodes
(d) N-1 nodes
(e) 2(N-1) nodes.
24. How many nodes does a complete binary tree of level 5 have?
(a) 16 (b) 15 (c) 32
(d) 31 (e) 64.
25. How do you determine the cost of a spanning tree?
(a) By the sum of the costs of the edges of the tree
(b) By the sum of the costs of the edges and vertices of the tree
(c) By the sum of the costs of the vertices of the tree
20
26.
27.
28.
29.
30.
(d) By the sum of the costs of the edges of the graph
(e) By the sum of the costs of the edges and vertices of the graph.
What would be the depth of tree whose level is 9?
(a) 10 (b) 8
(c) 9
(d) 11 (e) 7.
A node of a directed graph G having no out-degree and a positive in-degree
is called
(a) Source node (b) Sink node
(c) Sibling node
(d) Null node (e) In-node.
The time complexity of the normal quick sort, randomized quick sort
algorithms in the worst case is
(a) O(n2), O(n log n)
(b) O(n2), O(n2)
2
(c) O(n log n), O(n )
(d) O(n log n), O(n log n)
2
(e) O(n log n), O(n log n).
Let there be an array of length ‘N’, and the selection sort algorithm is used to
sort it, how many times a swap function is called to complete the execution?
(a) N log N times
(b) log N times (c) N2 times
(d) N-1 times
(e) N times.
The Sorting method which is used for external sort is
(a) Bubble sort (b) Quick sort
(c) Merge sort
(d) Radix sort
(e) Selection sort.
Answers
21.
Answer : (d)
Reason: As in quick sort the division is made at an element which is pivotal element.
22.
Answer : (a)
Reason: As there is no chance for the other probing techniques to have primary clustering.
23.
Answer : (c)
Reason: According to full binary tree, if there are 2n-1 nodes, then there would be n leaves
exactly.
24.
Answer : (d)
Reason: This is 25 – 1. (2level – 1)
25.
Answer : (a)
Reason: As the other options are wrong, and the cost of a spanning tree is the cost of edges of the tree
only.
26.
Answer : (c)
Reason: As both the depth and level are same.
27.
Answer : (a)
Reason: Because the source vertex is a vertex which contains only leaving edges, but no any incoming
edge.
28.
Answer : (b)
Reason: Because, there is no difference between normal quick sort and randomized quick sort algorithms
for their efficiency, except the picking of a pivotal element.
21
29.
Answer : (d)
Reason: Because, every time we swap the ith smallest element with the ith position. And we do this for i=1
to n-1 times.
30.
Answer : (c)
Reason: As Merge sort is the only one from the given sorting techniques which is used for the external
sorting.
******
22
Download