38
CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS 2 marks questions with answers UNIT 1 1. Define Algorithm. An algorithm is a sequence of unambiguous instructions for solving a problem, which means to obtain a required output for any legitimate input in a finite amount of time. 2. What are the characteristics of an algorithm? · Simplicity · Generality · Definiteness · Finiteness · Effectiveness 3. What are three parts of algorithm? · Pre Condition · Body of Algorithm · Post Condition 4. What is Algorithm Design Technique? An algorithm design technique is a general approach to solving problems algorithmically that is applicable to a variety of problems from different areas of computing. 5. What are the criteria used to identify the best algorithm? · Order of Growth · Time Complexity · Space Complexity 6. Define time and space complexity. Time Complexity indicates how fast an algorithm runs. T(P)=Compile Time+ Run Time .(Tp) Where Tp is no of add, sub, mul... Space Complexity indicates how much extra memory the algorithm needs. Basically it has three components. They are instruction space, data space and environment space. Dept. of CSE, SVSCE

DAA2M

Embed Size (px)

Citation preview

Page 1: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

UNIT 1

1. Define Algorithm.An algorithm is a sequence of unambiguous instructions for solving a problem, which

means to obtain a required output for any legitimate input in a finite amount of time.

2. What are the characteristics of an algorithm?· Simplicity· Generality· Definiteness· Finiteness· Effectiveness

3. What are three parts of algorithm?· Pre Condition· Body of Algorithm· Post Condition

4. What is Algorithm Design Technique? An algorithm design technique is a general approach to solving problems algorithmically

that is applicable to a variety of problems from different areas of computing.

5. What are the criteria used to identify the best algorithm?· Order of Growth· Time Complexity· Space Complexity

6. Define time and space complexity.Time Complexity indicates how fast an algorithm runs.

T(P)=Compile Time+ Run Time .(Tp)Where Tp is no of add, sub, mul...

Space Complexity indicates how much extra memory the algorithm needs. Basically it has three components. They are instruction space, data space and environment space.

7. Difference between Compile and Running Time.

Dept. of CSE, SVSCE

Page 2: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

8. Find the time complexity for summation of N numbers.The time complexity for summation of N numbers is O (N).

9. What are the various types of time complexity of an algorithm?· Big Oh· Big Omega· Big Theta· Little Oh· Little Omega

10. Why is the need of studying algorithms?

From a practical standpoint, a standard set of algorithms from different areas of computing must be known, in addition to be able to design them and analyze their efficiencies. From a theoretical standpoint the study of algorithms in the cornerstone of computer science.

11. What is algorithmics?

The study of algorithms is called algorithmics. It is more than a branch of computer science. It is the core of computer science and is said to be relevant to most of science, business and technology.

12. What are the fundamental steps involved in algorithmic problem solving?

The fundamental steps are: 1) Understanding the problem 2) Ascertain the capabilities of computational device 3) Choose between exact and approximate problem solving 4) Decide on appropriate data structures 5) Algorithm design techniques 6) Methods for specifying the algorithm 7) Proving an algorithms correctness 8) Analyzing an algorithm 9) Coding an algorithm

13. What are the steps involved in the analysis framework?

The various steps are as follows.

1) Measuring the input’s size 2) Units for measuring running time 3) Orders of growth 4) Approaches in analysis of algorithms5) Worst case, best case and average case efficiencies

Dept. of CSE, SVSCE

Page 3: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

14. What are the basic asymptotic efficiency classes?

The various basic efficiency classes are:

1) Constant: 1 2) Logarithmic: log n 3) Linear: n 4) N-log-n: nlogn 5) Quadratic: n2 6) Cubic: n3 7) Exponential: 2n 8) Factorial: n!

15. What do you mean by Worst case-Efficiency” of an algorithm?The Worst case-Efficiency” of an algorithm is its efficiency for the worst-case input of

size n, which is an input (or inputs) of size n for which the algorithm runs the longest among all possible inputs of that size.

Ex: if you want to sort a list of numbers in ascending order when the numbers are given in descending order. In this running time will be the longest.

16. What do you mean by Best case-Efficiency” of an algorithm?The Best case-Efficiency” of an algorithm is its efficiency for the Best-case input of size

n, which is an input(or inputs) of size n for which the algorithm runs the fastest among all possible inputs of that size. Ex: if you want to sort a list of numbers in ascending order when the numbers are given in ascending order. In this running time will be the smallest.

17. Define the Average-case efficiency” of an algorithm?The Average-case efficiency” of an algorithm is its efficiency for the input of size n, for

which the algorithm runs between the best case and the worst case among all possible inputs of that size.

18. What do you mean by “Amortized efficiency”?The “Amortized efficiency” applies not only a single run of an algorithm but rather to a

sequence of operations performed on the same data structure. It turns out that in some situations a single operation can be expensive ,but the total time for an entire sequence of n such operations is always significantly better than the worst case efficiency of that single operation multiplied by n. This is known as “Amortized efficiency”.

19. How to measure the algorithm’s efficiency?It is logical to investigate the algorithm’s efficiency as a function of some parameter n

indicating the algorithm’s input size.Example: It will be the size of the list for problems of sorting, searching, finding the list’s smallest element, and most other problems dealing with lists.

Dept. of CSE, SVSCE

Page 4: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

20. What is called the basic operation of an algorithm?The most important operation of the algorithm is the operation contributing the most to

the total running time is called basic operation of an algorithm.

21. How to measure an algorithm’s running time?Let Cop be the time of execution of an algorithm’s basic iteration on a particular computer

and let C (n) be the number of times this operation needs to be executed for this algorithm. Then we can estimate the running time T(n) of a program implementing this algorithm on that computer by the formula

T(n) ≈ Cop C(n)

22. Define order of growth.The efficiency analysis framework concentrates on the order of growth of an algorithm’s

basic operation count as the principal indicator of the algorithm’s efficiency. To compare and rank such orders of growth we use three notations

i. O (Big oh) notationii. Ω (Big Omega) notation &

iii. Θ (Big Theta) notation

23. Difference between Best Case and Worst Case Complexities.The best case complexity of an algorithm is its efficiency for the best case input of

size N, which is an input of size N for which the algorithm runs fastest among allpossible inputs of that size.

The worst case complexity of an algorithm is its efficiency for the worst case inputof size N, which is an input of size N for which the algorithm runs longest among allpossible inputs of that size.

24. What is the Space Complexity for the following algorithm?void N()

int P,A,B,C;P=A+B-C;printf(“%d”, P);

Space Complexity = Space Needed For P, A, B, C = 8

25. Define asymptotic notation.The efficiency analysis framework concentrates on the order of growth of an algorithm’s

basic operation count as the principle indicator of the algorithm’s Efficiency. To compare and rank such orders of growth scientists’ use three notations (Big Oh, Big Omega, and Big Theta, which is called as asymptotic notation.

26. What are the 3 standard notations?a) Big Oh(O) b) Big Omega(Ω) c) Big Theta(Θ)

Dept. of CSE, SVSCE

Page 5: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

27. Define Big oh notation A function t(n) is said to be in O(g(n)) denoted t(n) ε O (g(n)), if t(n) is bounded above by

some constant multiple of g(n) for all large n, i.e., if there exist some positive constant c and some non negative integer n0 such that

T (n) < c g (n) for n > n0

28. Define Ω notationA function t(n) is said to be in Ω (g(n)), denoted t(n) Ω (g(n)), if t(n) is bounded below

by some positive constant multiple of g(n) for all large n, i.e., if there exist some positive constant c and some non negative integer n0 such that

T (n) < c g (n) for n > n0

29. Define Θ - notationA function t(n) is said to be in Θ(g(n)), denoted t(n) Θ (g(n)), if t(n) is bounded both

above and below by some positive constant multiples of g(n) for all large n, i.e., if there exist some positive constant c1 and c2 and some non negative integer n0 such that

c2 g (n) < t (n) < c1 g(n) for n > n0

30. What is the use of Asymptotic Notations?The notations O, and and are used to indicate and compare the asymptotic orders of

growth of functions expressing algorithm efficiencies.

31. Define Conditional Asymptotic Notation.Let F be an eventually nonnegative sequence of real numbers and Let X be a set. The

function O(F|X) yields a non empty set of functions from N to R and is defined as follows:

32. Define Smoothness Rule.Let F (N) be a nonnegative function defined on the set of natural numbers. F(N) is called

Smooth If it is eventually non decreasing and F(2n) ı Θ (F(N)).Let T(N) be an eventually a non decreasing function and F(N) be a smooth function. IfT(N) ı Θ (F(N)) For Values Of N That Are Powers Of B,Where B>=2, Then T (N) ı Θ (F(N)) For Any N.

33. What Are The Common Running Time For Big-Oh.The common running time for Big-Oh Are

· O(N)· O(Log N)· O(N Log N)· O(N^C),C>1

34. Define Recurrence Relation.The equation defines M (N) not explicitly, ie.., is a function of n, but implicitly as a

function of its value at another point, namely N-1. Such equations are called recurrence relation.

Dept. of CSE, SVSCE

Page 6: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

35. What are all the types of recurrence relation?· Geometric sequence· Arithmetic sequence· Linear sequence

36. Define Linear Search.In computer science, linear search or sequential search is a method for finding a

particular value in a list, which consists in checking every one of its elements, one at a time and in sequence, until the desired one is found.

37. What are the Best, Worst and Average Case complexity of Linear Search?· Best Case – O (1)· Average Case – O (N)· Worst Case – O (N)

38. Define Little Oh and Little Omega Notations.The relation is read as "f(x) is little-o of g(x)". Intuitively, it means that g(x) grows much

faster than f(x). It assumes that f and g are both functions of one variable. Formally, it states

For non-negative functions, f(n) and g(n), f(n) is little omega of g(n) if and only if f(n) = _(g(n)), but f(n) ≠ Θ(g(n)). This is denoted as "f (n) = ω (g (n))".

39. Define Substitution Method.Substitution method is a method of solving a system of equations wherein one of the

equations is solved for one variable in terms of the other variables.

40. Give Master Theorem.Let T(n) be a monotonically increasing function that satisfies

T(n) = aT(n/b ) + f(n)T(1) = c

where a ≥ 1, b ≥ 2, c > 0. If f(n)ε O(n^d) where d ≥ 0, thenO(n^d) if a < b^d

T(n) = O(n^d log n) if a = b^dO(n^logb a) if a > b^d

41. Give the general plan for analyzing recursive algorithm.· Decide a parameter indicating an Input’s Size.· Identify the algorithms Basic Operation· Check whether the number of times the basic operation is executed only on the size of an input. If it also depends on some additional property, the worst case, average case, and if necessary, best case efficiencies have to be investigated separately.· Set up a recurrence relation, with an appropriate initial condition, for the number of times basic operation is executed.

Dept. of CSE, SVSCE

Page 7: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

42. Give the general plan for analyzing non recursive algorithm.· Decide a parameter indicating an Input’s Size.· Identify the algorithms Basic Operation· Check whether the number of times the basic operation is executed only on the size of an input. If it also depends on some additional property, the worst case, average case, and if necessary, best case efficiencies have to be investigated separately.· Using standard formulas and rules of sum manipulation either find a closed formula for the count or, at the very least, establish its order of growth.

43. Define Data Space, Instruction Space and Environment Space.· Data Space: The space needed to store all constants and variable values.· Instruction Space: The space needed to store the compiled version of all program instruction· Environment Space: The environment stack is used to save information needed to resume execution of partially completed functions. Each time a function is invoked the following data are saved the environment stack.

The return address. The values of all local variables.

44. What are all the methods available for solving recurrence relations?· Forward Substitution· Backward Substitution· Smoothness Rule· Master Theorem

45. Write down the problem types.· Sorting· Searching· String Processing· Graph Problem· Combinational Problem· Geometric Problem· Numerical Problem

46. What are the types of recurrence relations?· Homogeneous recurrence relation.· Non homogeneous recurrence relation.

Dept. of CSE, SVSCE

Page 8: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

UNIT 2

1. What is the order of an algorithm?A standard notation used to represent the computing time of the algorithm is termed as

the order of an algorithm and is denoted by O.

2. What are the objectives of sorting algorithms?The objective of the sorting algorithm is to rearrange the records so that their keys are

ordered according to some well-defined ordering rule.

3. What is meant by optimal solution?A solution to an optimization problem which minimizes (or maximizes) the objective

function is termed as an optimal solution. An optimization problem is a computational problem in which the object is to find the best of all possible solutions. More formally, find a solution in the feasible region which has the minimum (or maximum) value of the objective function.

4. Find the number of comparisons made by the sequential search in the worst case and the best case.

The numbers of comparisons made by the sequential search in the worst and best case areone and n key comparisons respectively.

5. Define divide and conquer strategy.Divide and conquer (D&C) is an important algorithm design paradigm based on

multibranched recursion. A divide and conquer algorithm works by recursively breaking down aproblem into two or more sub-problems of the same (or related) type, until these become simple enough to be solved directly. The solutions to the sub-problems are then combined to give a solution to the original problem.

6. Give some examples of divide and conquer method.Some of the examples of D&C method are binary search, Euclidean algorithm, Cooley-

Tukey fast Fourier transform (FFT) algorithm and merge sort algorithm.

7. Write control abstraction for D&C technique.The control abstraction for D&C technique is as follows:procedure D&C (P,Q) //the data size is from p to qif size(P,Q) is small Then

solve (P,Q)else

M ¬ divide (P, Q)Combine (D&C(P,M), D&C(M+1,Q))

Sometimes, this type of algorithm is known as control abstract algorithms as they give an

abstract flow. This way of breaking down the problem has found wide application in sorting, selection and searching algorithm.

Dept. of CSE, SVSCE

Page 9: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

8. Advantages of binary search.Binary search is a fast way to search a sorted array. The idea is to look at the element in

the middle. If the key is equal to that, the search is finished. If the key is less than the middle element, do a binary search on the first half. If it's greater, do a binary search of the second half.

9. What are all the advantages of Binary search?The Binary search is an optimal searching algorithm using us can search the desired

element effectively.Applications:

The binary search is an efficient searching method & is used to search desired record from database. For solving nonlinear equations with one unknown this method is used.

10. What is the time complexity of binary search?Best Case Average Case Worst Case O(1) O(log2n) O(log2n)

11. What is the time complexity of straight forward with D & C of finding Min-max?· Best case occurs when the elements are in increasing order, so the number of element comparisons is n· Worst case occurs when the elements are in decreasing order, so the number of element comparisons is 2(n-1).· Average case occurs when a[i] is greater than max half the time.

12. Define greedy techniqueThe greedy method is the most straight forward design technique that can be applied to a

wide variety of problems.

13. Define feasible solution.A feasible solution is a solution that satisfies the constraints

14. Define optimal solution.An optimal solution is a feasible solution that optimizes the objective/optimization

function. In general, finding an optimal solution is computationally hard.

15. What is the Control abstraction of greedy technique?· Select ()-is the function that selects an input from a [] and removes it.· Feasible ()-is a Boolean-valued function that determines whether x can be included into the solution vector.· Union ()-is the function that combines x with the solution and updates the objective function.

16. What is meant by Container-loading?Container-loading problem is a problem which is used to load the ship with the maximum

number of containers.

Dept. of CSE, SVSCE

Page 10: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

17. Define Complexity Analysis.· A complexity class is a set of problems of related complexity. Simpler complexity classes are defined by the following factors:· The type of computational problem: The most commonly used problems are decision problems. However, complexity classes can be defined based on function problems, counting problems, optimization problems, promise problems, etc.· The model of computation: The most common model of computation is the deterministic Turing machine, but many complexity classes are based on nondeterministic Turing machines, Boolean circuits, quantum Turing machines, monotone circuits, etc. · The resources (or resources) that are being bounded and the bounds: These two properties are usually stated together, such as "polynomial time", "logarithmicspace", "constant depth", etc.

18. Application of greedy algorithm:· Container loading.· Knapsack problem.· Topological sorting.· Bipartite cover· Single-source shortest paths· Minimum-cost spanning trees

19. How the choices are made in each step in greedy method:· Choices of solution made at each step of problem solving in greedy approach is asfollows...· Feasible-it should the problem's constraints.· Locally optimal-among all feasible solutions the best choice is to be made Irrevocable-once the particular choice is made then it should not get changed on subsequent steps.

20. General plan for divide & conquer algorithm:· Divide the problem into two or smaller sub problems· Conquer the sub problems by solving them recursively· Combine the solutions to the sub problems into the solutions for the original problem.

21. Define a knapsack problem.The knapsack problem or rucksack problem is a problem in combinatorial optimization:

Given a set of items, each with a weight and a value, determine the number of each item to include in a collection so that the total weight is less than a given limit and the total value is as large as possible. It derives its name from the problem faced by someone who is constrained by a fixed-size knapsack and must fill it with the most useful items.

Dept. of CSE, SVSCE

Page 11: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

UNIT 3

1. What is the difference between dynamic programming and greedy algorithm?

2. What is the difference between dynamic programming and divide and conquer?

3. What is dynamic programming?Dynamic programming is an algorithm design method, where the solution to the main

problem can be viewed as the result of a sequence of decisions. It avoids the calculation of same stuff twice, by keeping the table of known results of sub-problems.

4. What are the basic elements of dynamic programming?· Sub structure· Table structure· Bottom up computations

5. Define sub structure, table structure and bottom up computations.A problem is said to have optimal substructure if the globally optimal solution can be

constructed from locally optimal solutions to sub problems.

We can either build up solutions of sub-problems from small to large (bottom up) or we can save results of solutions of sub-problems in a table (top down + memorization).This forms the table structure.

Dept. of CSE, SVSCE

Page 12: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

6. What are the applications of dynamic programming?· Fibonacci numbers· Longest increasing sequence· Minimum weight triangulation· The partition problem· Appropriate string matching

7. Define multi stage graph.A multistage graph is a graph

o G=(V,E) with V partitioned into K >= 2 disjoint subsets such that if (a,b) is in E, then a is in Vi , and b is in Vi+1 for some subsets in the partition;

o and | V1 | = | VK | = 1.

The vertex s in V1 is called the source; the vertex t in VK is called the sink. G is usually assumed to be a weighted graph. The cost of a path from node v to node w is sum of the costs of edges in the path. The "multistage graph problem" is to find the minimum cost path from s to t. Each set Vi is called a stage in the graph.

8. Define the principle of optimality.It states that in an optimal sequence of decisions, each sub sequence must be optimal. To

use dynamic programming the problem must observe the principle of optimality that whatever the initial state is, remaining decisions must be optimal with regard the state following from the first decision.

9. Give the formula for cost (i,j) of multistage graph in both forward and backward approach.

Forward approachCost(i,j)=minc(i,j)+cost(i+1,l)

l Є vi+1 (vertex in next stage) , <j,l> Є E,Since, cost (k-1,j)=c(j,t), if <j,t> ≤ E andcost (k-1,j)= ∞, if<I,t> !Є E

Backward approachBcost(i,j)=minbcost(i-1,l)+c(l,j)

l Є vi-1 , <l,j>Є Esince,bcost(2,j)=c(1,j) if <1,j> Є E andbcost(2,j)= ∞ if<1,j> !Є E

10. Explain All-pair shortest-paths problem

Given a weighted connected graph (undirected or directed), the all pairs shortest paths problem asks to find the distances (the lengths of the shortest path) from each vertex to all other vertices.

Dept. of CSE, SVSCE

Page 13: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

11. Explain Floyd's algorithm

It is convenient to record the lengths of shortest paths in an n by n matrix D called the distance matrix: the element dij in the ith row and the jth column of this matrix indicates the length of the shortest path from the ith vertex to the jth vertex . We can generate the distance matrix with an algorithm that is very similar to warshall's algorithm. It is called Floyd's algorithm.

12. What does Floyd’s algorithm do?It is used to find the distances (the lengths of the shortest paths) from each vertex to all

other vertices of a weighted connected graph.

13. Derive the formula for the Floyd’s algorithm and running time of the algorithm.

for k<--1 to n dofor i<--1 to n dofor j<--1 to n doD[i,j]=min[i,j],D[i,k]+D[k,j]

RUNNING TIME OF THE ALGORITHM: O(n3)

14. What are the preconditions for the Floyd’s algorithm?The precondition for the Floyd’s algorithm is that the graph should not have a cycle of

negative length or cost.NOTE: Draw the graph given in class notes.

15. Define Binomial Coefficient

The Binomial Coefficient, denoted C(n,k) is the number of Combinations(subsets) of k elements from an n-element set(0<k<n). The name "binomial coefficients" comes from the participation of these numbers in the so called binomial formula (a+b)n =(n,0)an+..........+C(n,i)an-

ibi+.......+C(n,n)bn

16. Define Transitive closure

The transitive closure of a directed graph with n vertices can be defined as the n by n Boolean matrix T = ti,, in which the element in the i th row (1<i<n) and the jth column (l<j<n) is 1 if there exists a non trivial directed path from the ith vertex to jth vertex ; otherwise , tij is 0.

17. Explain Warshall’s algorithm

Warshall's algorithm constructs the transitive closure of a given digraph with n vertices through a series of n by n Boolean matrices R(0), ………, R(k-l)R(k),…….., R(n)

Each of these matrices provides certain information about directed paths in the digraph.

Dept. of CSE, SVSCE

Page 14: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

18. Define OBST.An OBST is a BST which has minimal expected cost.

One of the principal applications of Binary Search Tree is to implement the operation of searching. If probabilities of searching for elements of a set are known, it is natural to pose a question about an optimal binary search tree for which the average number of comparisons in a search is the smallest possible.

Criterion for an optimal tree:Each optimal binary search tree is composed of a root and (at most) two optimal sub

trees, the left and the right.

19. What is root table?The root table is a table which has 0 to n columns and 1 to n+ 1 row. The root value is

given by R [1, n].The k values the entries in the main table is entered into the root table.

20. What is the running time of traveling salesman problem and 0/1 knapsack problem?TSP: 0(n2 * 2n)0/1 Knapsack: 0(nw)

21. What is meant by TSP?The Traveling Salesman Problem (TSP) is a problem in combinatorial optimization

studied in operations research and theoretical computer science. Given a list of cities and their pair wise distances, the task is to find a shortest possible tour that visits each city exactly once. It is one of the most intensively studied problems in optimization.

22. Define 0/1 Knapsack problem.The most common formulation of the problem is the 0-1 knapsack problem, which

restricts the number xi of copies of each kind of item to zero or one.Mathematically the 0-1-knapsack problem can be formulated as:

23. What are the steps involved in dynamic programming?· Develop a mathematical relation that can express any solution and sub solutions for problem.· Prove the principle of optimality.· Develop a recurrence relation that is a solution to its sub solution using mathematical notation in step 1.· Write an algorithm to compute the recurrence relation.

Dept. of CSE, SVSCE

Page 15: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

24. Explain the Memory Function technique

The Memory Function technique seeks to combine strengths of the top down and bottom-up approaches to solving problems with overlapping subproblems. It does this by solving, in the top-down fashion but only once, just necessary sub problems of a given problem and recording their solutions in a table.

UNIT 4

1. Define exhaustive search.Exhaustive search is simply a “brute – force” approach to combinatorial problems. It

suggests generating each and every element of the problem’s domain, selecting those of them that satisfy the problem’s constraints, and then finding a desired element.

2. Difference between Backtracking & Exhaustive search.

3. Define Backtracking.Backtracking is to build up the solution vector one component at a time and to use

modified criterion function Pi(x1,..,xi) (sometimes called bounding function) to test whether the vector being formed has any chance of success. Desired solution expressed as an ntuple (x1,x2,…,xn) where xi are chosen from some set Si.

· If |Si|=mi, m=m1m2..mn candidates are possible· Yielding the same answer with far fewer than m trials· Advantage : if it is realized that the partial vector (x1,..,xi) can in no way lead to an

optimum solution, then mi+1…mn possible test vectors can be ignored entirely.”

4. Give the categories of the problem in backtracking.· Decision’s problem: - Whether there is any feasible solution.· Optimization problem: - Whether there exists any best solution.· Enumeration problem: - Finds all possible feasible solution.

5. List down the examples of backtracking.N-Queens problem, Subset-Sum problem, Hamiltonian circuit problem, Graph coloring, Constraint satisfaction problem

Dept. of CSE, SVSCE

Page 16: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

6. Define promising and non promising node.· Promising Node:

A node in a state space tree is said to be promising if it corresponds to a partially constructed solution that may still lead to a complete solution.· Non – Promising node:

A node in a state space tree is said to be non-promising if it corresponds to a partially constructed solution that would not be able to lead to a complete solution further.

7. What are the two types of constraints used in Backtracking?· Explicit constraints· Implicit constraints

8. Define implicit constraint.· Implicit constraints are rules that determine which of the tuples in the solution space of I that satisfy the criterion function.· Implicit constraints describe the way in which the x is must relate to each other.

9. Define explicit constraint.

Explicit constraints are rules that restrict each xi to take on values only from a given set.· Explicit constraints depend on the particular instance I of problem being solved· All tuples that satisfy the explicit constraints define a possible solution space for I· Examples of explicit constraints

10. Give a template for a generic backtracking algorithm.

ALGORITHM Backtrack(X[1..i])//Gives a template of a generic backtracking algorithm//Input X[1..i] specifies the first I promising components of a solution//Output All the tuples representing the problem’s solution if X[1..i] is a solution write X[1..i] else for each element xÎSi+1 consistent with X[1..i] and the constraints do X[i+1] Å x Backtrack(X[1..i+1])

11. Explain State Space Tree

If it is convenient to implement backtracking by constructing a tree of choices being made, the tree is called a state space tree. Its root represents an initial state before the search for a solution begins.

Dept. of CSE, SVSCE

Page 17: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

12. Explain promising and nonpromising nodeA node in a state space tree is said to be promising if it corresponds to a partially

constructed solution that may still lead to a complete solution; otherwise it is called nonpromising

13. How can the output of a backtracking algorithm be thought of?The output of a backtracking algorithm can be thought of as an n-tuple (x1, …xn) where

each coordinate xi is an element of some finite linearly ordered set Si. If such a tuple (x1, …xi) is not a solution, the algorithm finds the next element in Si+1 that is consistent with the values of (x1, …xi) and the problem’s constraints and adds it to the tuple as its (I+1)st coordinate. If such an element does not exist, the algorithm backtracks to consider the next value of xi, and so on.

14. What are the tricks used to reduce the size of the state-space tree?The various tricks are ._Exploit the symmetry often present in combinatorial problems. So

some solutions can be obtained by the reflection of others. This cuts the size of the tree by about half.

Preassign values to one or more components of a solution Rearranging the data of a given instance.

15. Define Feasible Solution A feasible solution is a point in the problem's search space that satisfies all the problem's constraints.Ex: A Hamiltonian Circuit in the traveling salesman problem. A subset of items whose total weight does not exceed the knapsack's Capacity

16. Define optimal solutionIs a feasible solution with the best value of the objective function?Eg: The shortest Hamiltonian CircuitThe most valuable subset of items that fit the knapsack

17. Mention two reasons to terminate a search path at the current node in a state-space tree of a branch and bound algorithm.

The value of the node's bound is not better than the value of the best solution seen so far. The node represents no feasible solutions because the constraints of the problem are already violated.

18. Explain n-Queens problemThe problem is to place n queens on an n by n chessboard so that no two queens attack

each other by being in the same row or same column or on the same diagonal.

19. What is Chess?Chess is a recreational and competitive game for two players. Sometimes called Western

Chess or International Chess to distinguish it from its predecessors and other chess variants, the current form of the game emerged in Southern Europe in the second half of the 15 th century after evolving from similar, much older games of Indian origin.

Dept. of CSE, SVSCE

Page 18: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

20. Draw the solution for the 4-queen problem

21. What is the method used to find the solution in n-queen problem by symmetry?The board of the n-queens problem has several symmetries so that some solutions can be

obtained by other reflections. Placements in the last n/2 columns need not be considered, because any solution with the first queen in square (1, i), n/2£ i£ n can be obtained by reflection from a solution with the first queen in square (1, n-i+1)

22. How can you represent the solution for 2 queen’s problem?There is no solution for 2 Queen’s problem since however the queens are arranged both

queens would be in same diagonal or column.

23. How can you represent the solution for 8 queen’s problem?All solutions represented as 8-tuples (x1, x2,…, x8) where xi is the column on which

queen “i” is placed.Constraints are,

o Explicit constraints Si=1,2,…,8

o Implicit constraints No two xi’s can be the same column or row (By this, solution space

reduced from 88 to 8!) No two queens can be on the same diagonal

24. Explain Subset-Sum ProblemWe consider the subset-sum problem: Find a subset of a given

set S=S1,S2,..........Sn of n positive integers whose sum is equal to a given positive integer d.

25. When can a node be terminated in the subset-sum problem?The sum of the numbers included are added and given as the value for the root as s’. The node can be terminated as a non-promising node if either of the two equalities holds:

26. Define problem state?· Problem state is each node in the depth-first search tree

Dept. of CSE, SVSCE

Page 19: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

27. Define state space of the problem?· State space is the set of all paths from root node to other nodes

28. Define solution states and answer state?Solution state:

· Solution states are the problem states s for which the path from the root node to‘s’ defines a tuple in the solution space· In variable tuple size formulation tree, all nodes are solution states· In fixed tuple size formulation tree, only the leaf nodes are solution states· Partitioned into disjoint sub-solution spaces at each internal node

Answer state:· Answer states are that solution states s for which the path from root node to s defines a tuple that is a member of the set of solutions· These states satisfy implicit constraints

29. Define state space tree?· State space tree is the tree organization of the solution space

30. Define static tree.Static trees are ones for which tree organizations are independent of the problem instance

being solved· Fixed tuple size formulation· Tree organization is independent of the problem instance being solved

31. Define dynamic tree.· Dynamic trees are ones for which organization is dependent on problem instance

32. Define live node.· Live node is a generated node for which all of the children have not been generated yet· E-node is a live node whose children are currently being generated or explored.

33. Define dead node.Dead node is a generated node that is not to be expanded any further

· All the children of a dead node are already generated· Live nodes are killed using a bounding function to make them dead nodes

34. Explain Graph coloring” problem. The graph coloring problem asks us to assign the smallest number of colors to vertices of

a graph so that no two adjacent vertices are the same color.

35. Define m color ability decision problem.Let G be a graph and m be a given positive integer. The nodes of G can be colored in

such a way that no two adjacent nodes have the same color yet only m colors are used. This is termed the m-colorability decision problem. If d is the degree of the given graph, then it can be colored with d+ 1 color. The m-colorability optimization problem asks for the smallest integer m

Dept. of CSE, SVSCE

Page 20: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

for which the graph G can be colored. This integer is referred to as the chromatic number of the graph. The color of each node is indicated next to it. If three colors are needed to color the graph then the graphs chromatic number is 3.

36. Define Hamiltonian circuit problem.Suppose we are given a graph G = (V,E) that is undirected. We say that a path v1, v2. . .vn

is a Hamiltonian path if every vertex of the graph occurs exactly once in this path.

Moreover, if the last vertex of the path duplicates the first one without ever repeating any other vertex in between, then the path is called a Hamiltonian circuit

37. State the equation which is used to represent 2 queens are in same diagonal.Let the diagonals be (i,j) and (k,l)The equation to represent 2 queens are in same diagonal is

i+j=k+l j-l=k-I ori-j=k-l j-l=i-k

38. Explain Knapsack ProblemFind the most valuable subset of n items of given positive integer weights and values that

fit into a knapsack of a given positive integer capacity.

UNIT 5

1. Define graph traversal.Searching a vertex in a graph can be solved by starting at vertex V and systematically

searching the graph G for vertices that can be reached from V. It starts at initial vertex and visits each and every vertex exactly once and finally reaches end vertex.

2. Mention the types of traversal.· Breath first search traversal.· Depth first search traversal.

3. What is meant by BFS traversal?· It starts from the arbitrary vertex.· It visits all vertices adjacent to starting vertex.· Then it visits next unvisited vertex.· This process is repeated until no more vertexes is left

4. What is the time complexity of BFS?· If the graph is represented by adjacency matrix: O (n2).· If the graph is represented by adjacency List: O (|V|+ |E|).

Dept. of CSE, SVSCE

Page 21: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

5. Define depth first search traversal.· It starts from the arbitrary vertex.· The exploration of the vertex V is suspended as soon as a new vertex is reached· At this time the exploration of new vertex U begins· The new vertex is explored the exploration of V continues· The search terminates when all reached vertices have been fully explored.

6. What is the time complexity of DFS?· If the graph is represented by adjacency matrix: O (n2).· If the graph is represented by adjacency List: O (|V|+ |E|).

7. Compare DFS and BFS.

8. Write pseudo code for BFS?

1 procedure BFS (Graph, source):2 create a queue Q3 enqueue source onto Q4 mark source5 while Q is not empty:6 dequeue an item from Q into v7 for each edge e incident on v in Graph:8 let w be the other end of e9 if w is not marked:10 mark w11 enqueue w onto Q

9. What are the applications of BFS?

Finding all nodes within one connected component Copying Collection, Cheney's algorithm Finding the shortest path between two nodes u and v Testing a graph for bipartiteness (Reverse) Cuthill–McKee mesh numbering Ford–Fulkerson method for computing the maximum flow in a flow network Serialization/Deserialization of a binary tree vs serialization in sorted order, allows the

tree to be re-constructed in an efficient manner

Dept. of CSE, SVSCE

Page 22: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

10. Write pseudo code for DFS.

1 procedure DFS (G, v):2 label v as explored3 for all edges e in G.incidentEdges (v) do4 if edge e is unexplored then5 w ← G.opposite (v, e)6 if vertex w is unexplored then7 label e as a discovery edge8 recursively call DFS (G, w)9 else10 label e as a back edge

11. What are the applications of DFS?

Finding connected components. Topological sorting. Finding 2-(edge or vertex)-connected components. Finding strongly connected components. Planarity Testing Solving puzzles with only one solution, such as mazes. (DFS can be adapted to find all

solutions to a maze by only including nodes on the current path in the visited set.) Maze generation may use a randomized depth-first search. Finding biconnectivity in graphs

12. Define connected component. A graph is said to be connected if for every pair of its vertices U and V, there is

path from U to V. A connected component is the maximal sub graph of a given graph. The set of maximally connected components of an undirected graph

Let G=(V, E) be a graph and G1=(V1, E1)..., Gm=(Vm, Em) be its connected components. Every vertex is in exactly in one connected component, that is, the components partition (1) V. formally, for all i ≠ j, Vi∩ Vj=ø. Further, V=V1∪...∪ Vm and E=E1∪...∪ Em.

13. How do identify connected component using breath first search?· BFS can be used to determine whether G is connected· Using BFS all newly visited vertices are put on the list.· Sub graph formed by the vertices on this list make up a connected component.

14. Define spanning tree.· A spanning tree is a minimal sub graph, G', of G such that V (G') = V (G) and G' is connected· A minimal sub graph is one with the fewest no.., of edges· Any connected graph with n vertices must have at least n -1edges, and all connected graphs with n -1 edges are trees· A spanning tree has n -1 edge

Dept. of CSE, SVSCE

Page 23: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

15. Define Minimum Spanning Tree

A minimum spanning tree of a weighted connected graph is its spanning tree of the smallest weight, where the weight of a tree is defined as the sum of the weights on all its edges.

16. Define Kruskal's Algorithm

Kruskal's algorithm looks at a minimum spanning tree for a weighted connected graph G =(V,E) as an acyclic subgraph with | V| - 1 edges for which the sum of the edge weights is the smallest.

17. Define Prim's Algorithm

Prim's algorithm is a greedy algorithm for constructing a minimum spanning tree of a weighted connected graph.It works by attaching to a previously constructed subtree a vertex to the vertices already in the tree.

18. What is meant by articulation point?An articulation point is a vertex v of G such that the deletion of v, together with

all edges incident on v, produces a graph, G', that has at least two connected components

19. Define bi connected graph and bi connected component.· A bi connected graph is a connected graph that has no articulation points· A bi connected component of a connected undirected graph is a maximal bi connected sub graph of G

20. What are biconnected components?A maximal subset of edges of a connected graph such that the corresponding induced

subgraph cannot be disconnected by deleting any vertex.

That is, the subgraph is biconnected or has no cut vertex

21. What are the methods to identify the articulation point?· Common vertex in bi connected component· Depth first spanning tree· Lowest depth first number

22. What is meant by lowest depth first number?For every vertex V in depth first spanning tree, we compute the L(u) that is reachable

from V by taking zero or more edges and then possible one back edge.

23. What is tree edge and cross edge?In the breath first search forest, whenever a new unvisited vertex is reached for the first

time, it is attached as a child to the vertex from which it is being reached. Such an edge is called tree edge. If an edge is leading to a previously visited vertex other than its immediate predecessor, that is noted as a cross edge.

Dept. of CSE, SVSCE

Page 24: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

24. List down the bi connected components for the following connected graph.Connected graph is

25. Define branch and bound.Branch-and-bound refers to all state space search methods in which all children of an

Enode are generated before any other live node can become the E-node.

26. Define live node, e node and dead node.· Live node is a node that has been generated but whose children have not yet been generated.· e-node is a live node whose children are currently being explored. In other words, an e-node is a node currently being expanded.· Dead node is a generated node that is not to be expanded or explored any further.All children of a dead node have already been expanded.

Dept. of CSE, SVSCE

Page 25: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

27. What are the types search strategies in branch and bound?· FIFO search· LIFO search· LC search

28. Compare the FIFO and LIFO search.· BFS is an FIFO search in terms of live nodes· List of live nodes is a queue· DFS is an LIFO search in terms of live nodes· List of live nodes is a stack

29. What is meant by Least Cost Search?The next E-node is selected on the basis of this ranking function. Heuristic is based on

the expected additional computational effort (cost) to reach a solution from the current live node.

30. Define intelligent function.Let ˆg(x) be an estimate of the additional effort needed to reach an answer from node x, x

is assigned a rank using a function ˆc (.) such that^c (x) = f(h(x)) + ˆg(x)

Where h(x) is the cost of reaching x from root and f (.) is any non decreasing function.

31. Define tractable and intractable problemsProblems that can be solved in polynomial time are called tractable problems; problems

that cannot be solved in polynomial time are called intractable problems.

32. Explain the theory of computational complexityA problem's intractability remains the same for all principal models of computations and

all reasonable input encoding schemes for the problem under consideration

33. Explain undecidable problemsIf the decision problem cannot be solved in polynomial time, and if the decision problems

cannot be solved at all by any algorithm. Such problems are called Undecidable.

34. Explain the halting problemGiven a computer program and an input to it, determine whether the program will halt on

that input or continue working indefinitely on it.

35. Define a HeuristicA heuristic is a common-sense rule drawn from experience rather than from a

mathematically proved assertion.Ex: Going to the nearest unvisited city in the traveling salesman problem is a good

illustration for Heuristic

Dept. of CSE, SVSCE

Page 26: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

36. What is meant by class P (Polynomial)?Class P consists of problems whose solutions are bounded by the polynomial of small

degree. Examples are Binary search O (log n), sorting O (n log n), and matrix multiplication 0(n 2.81).

37. What is meant by Class NP (Non Polynomial)?Class P consists of problems whose solutions are bounded by the non polynomial.

Examples are Traveling salesperson problem O(n22n), knapsack problem O(2n/2)

38. What are the two classes of non polynomial time problems?· NP- hard· NP-complete

39. Differentiate between the deterministic and non deterministic algorithm.

40. Differentiate between the decision and optimization problem.

41. State true or false.· All NP-complete problems are NP-hard – TRUE.· All NP-hard problems are not NP-complete- TRUE.

42. Define SATISFIABILITY.Let x1, x2, x3….,xn denotes Boolean variables.

Let xi denotes the relation of xi.A literal is either a variable or its negation.A formula in the prepositional calculus is an expression that can be constructed using literals and the operators and L or v.A clause is a formula with at least one positive literal.The satiability problem is to determine if a formula is true for some assignment of truth values to the variables.

43. Define COOK’S theorem.Satisfiability is in P if and only if P = NP.

Dept. of CSE, SVSCE

Page 27: DAA2M

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS2 marks questions with answers

44. What is meant by NP hard and NP complete problem?· NP-Hard Problem: A problem L is NP-hard if any only if Satisfiability reduces to L.· NP- Complete: A problem L is NP-complete if and only if L is NP-hard and L є NP.· There are NP-hard problems that are not NP-complete.

Halting problem is NP-hard decision problem, but it is not NP-complete.

45. Explain NP-complete problemsA decision problem d is said to be NP-complete if1) It belongs to class NP2) Every problem in NP is polynomially reducible to D.

46. Explain NP-Hard problemsThe notion of an NP-hard problem can be defined more formally by extending the notion

of polynomial reducibility to problems that are not necessary in class NP including optimization problems.

47. What is the difference between NP- hard and NP-completeness?If all problems R Є NP are reducible to P, then P is NP-hard. We say P is NP-Complete

if P is NP-hard and P Є NP. If P<pQ and P is NP-Complete, Q is also NP-Complete.

Dept. of CSE, SVSCE