QP4
QP4
B.Tech Degree S6 (S, FE) / S6 (PT) (S) Examination January 2024 (2019 Scheme)
PART A
4. Define AVL tree. What is the advantage of AVL tree? Give an example
Ans:
o AVL Tree can be defined as height balanced binary search tree in which each
node is associated with a balance factor.
o Balance Factor
Balance Factor of a node = height of left subtree – height of right subtree
In an AVL tree balance factor of every node is -1,0 or +1
Otherwise the tree will be unbalanced and need to be balanced.
Example:
o Why AVL Tree?
Most of the Binary Search Tree(BST) operations (eg: search, insertion,
deletion etc) take O(h) time where h is the height of the BST.
The minimum height of the BST is log n
The height of an AVL tree is always O(log n) where n is the number of nodes
in the tree.
So the time complexity of all AVL tree operations are O(log n)
5. Strassen‟s multiplication method is used to multiply two nxn matrices when n is a power
of 2. How it can be modified when n is not a power of 2?
Ans:
If n is not a power of 2, then enough rows and columns of 0‟s can be added to
both matrices so that the resulting dimensions are the power of two.
6. Define spanning tree of a graph. Write the total number of spanning trees possible for a
complete graph with 4 vertices
Ans:
A spanning tree is a subset of undirected connected Graph G=(V,E), which has
all the vertices covered with minimum possible number of edges.
Total number of spanning trees possible for a complete graph with 4 vertices
= nn-2 = 44-2 = 42 =16
11.
a) Solve the following recurrence using iteration method
T(n)=2T(n/2) + n
Ans:
T(n) = n + 2 T(n/2)
= n + 2 [(n/2)+ 2 T(n/22)] = 2n + 22T(n/22)
= 2n + 22 [(n/22)+2T(n/23)]= 3n + 23T(n/23)
………………………….
=k n + 2kT(n/2k) kth term
Assume that n/2k=1 2k=n k=log2(n)
T(n) =nlog2 (n) + nT(1)
=nlog2 (n) + n
=O(nlog2(n))
b) Define the asymptotic notations: Big Oh, Big Omega, Theta and little omega
Ans:
Asymptotic notationsare the mathematical notations to represent frequency
count. Few asymptotic notations are
Big Oh (O)
The function f(n) = O(g(n)) iff there exists 2 positive constants c and n0
such that 0 ≤ f(n) ≤ c g(n) for all n ≥ n0
It is the measure of longest amount of time taken by an algorithm(Worst
case).
It is asymptotically tight upper bound
Omega (Ω)
The function f(n) = Ω (g(n)) iff there exists 2 positive constant c and n 0
such that f(n) ≥ c g(n) ≥ 0 for all n ≥ n0
It is the measure of smallest amount of time taken by an algorithm(Best
case).
It is asymptotically tight lower bound
Theta (Ɵ)
The function f(n) = Ɵ (g(n)) iff there exists 3 positive constants c1, c2
and n0 such that 0 ≤ c1 g(n) ≤ f(n) ≤ c2 g(n) for all n ≥ n0
It is the measure of average amount of time taken by an
algorithm(Average case).
f(n) becomes arbitrarily large relative to g(n) as n approaches infinity
12.
a) Illustrate best case, average case and worst-case complexity with insertion sort
algorithm
Ans:
Algorithm InsertionSort(A,n)
{
for i=1 to n-1 do
{
j=i
while j>0 and A[j-1] > A[j] do
{
Swap(A[j], A[j-1])
j=j-1
}
}
}
Best case complexity: Best case situation occurs when the array itself is in sorted
order. In this case the while loop will not execute successfully. So the time
complexity is proportional to number of times the for loop will execute. It will
execute O(n) time.
The best case time complexity = Ω(n)
Worst case complexity: Worst case situation occurs when the array itself is in
reverse sorted order. In this case the while loop will execute 1+2+3+ . .. .+(n-
1)=n(n+1)/2 times.
The time complexity is proportional to number of times the while loop will execute. It
will execute O(n2) time.
The worst case time complexity = O(n2)
Average case complexity: Average case situation occurs when the while loop will
iterate half of its maximum iterations. In this case the while loop will execute
[1+2+3+ . .. .+(n-1)]/2=n(n+1)/4 times.
The time complexity is proportional to number of times the while loop will execute. It
will execute O(n2) time.
The average case time complexity = Ɵ(n2)
o Find Operation
Determine which subset a particular element is in.
This will return the representative(root) of the set that the element belongs.
This can be used for determining if two elements are in the same subset.
Find(3) will return 1, which is the root of the tree that 3 belongs
Find(6) will return 6, which is the root of the tree that 6 belongs
Find Algorithm
Algorithm Find(n)
1. while nparent != NULL do
1.1 n = nparent
2. return n
Worst case Time Complexity = O(d), where d is the depth of the tree
o Union Operation
Join two subsets into a single subset.
Here first we have to check if the two subsets belong to same set. If no, then
we cannot perform union
i 1 2 3 4 5 6 7
P -1 1 1 1 6 1 6
Union Algorithm
Algorithm Union(a, b)
1. X =Find(a)
2. Y = Find(b)
3. If X != Y then
1. Yparent = X
Worst case Time Complexity = O(d), where d is the depth of the tree
b) Give Breadth First Search algorithm for graph traversal. Perform its complexity
analysis.
Ans:
Algorithm BFS(G, u)
1. Set all nodes are unvisited
2. Mark the starting vertex u as visited and put it into an empty Queue Q
3. While Q is not empty
3.1 Dequeue v from Q
3.2 While v has an unvisited neighbor w
3.2.1 Mark w as visited
3.2.2 Enqueue w into Q
4. If there is any unvisited node x
4.1 Visit x and Insert it into Q. Goto step 3
Complexity
If the graph is represented as an adjacency list
o Each vertex is enqueued and dequeued atmost once. Each queue
operation take O(1) time. So the time devoted to the queue
operation is O(V).
o The adjacency list of each vertex is scanned only when the vertex
is dequeued. Each adjacency list is scanned atmost once. Sum of
the lengths of all adjacency list is |E|. Total time spend in
scanning adjacency list is O(E).
o Time complexity of BFS = O(V) + O(E) = O(V+ E).
o In a dense graph:
E=O(V2)
Time complexity= O(V) + O(V2) = O(V2)
If the graph is represented as an adjacency matrix
o There are V2 entries in the adjacency matrix. Each entry is
checked once.
o Time complexity of BFS = O(V2)
14.
a) Write an algorithm to find strongly connected components of a graph. Illustrate with
an example
Ans:
Algorithm
1. Set all vertices of graph G are unvisited.
2. Create an empty stack S.
3. Do DFS traversal on unvisited vertices and set it as visited. If a vertex has no
unvisited neighbor, push it in to the stack.
4. Perform the above step until all vertices are visited
5. Reverse the graph G.
6. Set all nodes are unvisited.
7. While S is not Empty
7.1.1 POP one vertex v‟
7.1.2 If v‟ is not visited
7.1.2.1 Set v‟ as visited
7.1.2.2 Call DFS(v‟). It will print strongly connected component of v‟.
Answer:
Pass 1: DFS: 1,4,7,9,3,6,8,5,2
Perform DFS
Connected Components: 8-2-5 9-6-3 1-7-4
b) Give Depth First Search algorithm for graph traversal. How the edges of a graph are
classified based on DFS?
Ans:
Algorithm DFS(G, u)
1. Mark vertex u as visited
2. For each adjacent vertex v of u
2.1 if v is not visited
2.1.1 DFS(G, v)
Algorithm main(G,u)
1. Set all nodes are unvisited.
2. DFS(G, u)
3. For any node x which is not yet visited
3.1 DFS(G, x)
● Classification of Edges
15.
a) Write the control abstraction for Greedy design technique. Give a greedy algorithm
for fractional knapsack problem
Ans:
Greedy(a, n) //a[1..n] contains n inputs
{ solution = Φ;
for i=1 to n do
{ x = Select(a);
if Feasible(solution, x) then
solution = Union(solution, x);
}
return solution;
}
o Select() selects an input from the array a[] and remove it. The selected input
value is assigned to x.
o Feasible() is a Boolean valued function that determines whether x can be
included into the solution subset.
o Union() combines x with the solution and updates the objective function.
Algorithm GreedyKnapsack(m, n)
//p[1:n] is the profits and w[1:n] is the weights of n objects such that p[i]/w[i] ≥ p[i+1]/w[i+1].
{ for i= 1 to n do
x[i] = 0.0; // x[1:n] is the solution vector
U = m; // m is the knapsack capacity
for i=1 to n do
{ if w[i] > U then
break;
x[i] = 1.0
U = U – w[i];
}
If i ≤ n then
x[i] = U / w[i];
}
b) Illustrate the divide and conquer approach by applying 2 way merge sort for the input
array: [15,12,14,17,11,13,12,16]. Write the recurrence for merge sort and give the
complexity.
Ans:
Recurrence Relation of Merge Sort
T(n) = a if n=1
2 T(n/2) + cn Otherwise
16.
a) Find an optimal solution to the fractional knapsack instance n=5, m=60, (p1,p2,.....p5)
= (30,20,100,90,160) and (w1,w2,.....w5) = (5,10,20,30,40), Where m is the knapsack
capacity, pi is the profit of ith item and wi is the weight of ith item
Ans:
Arrange the objects in the descending order of profit/weight
i ={ 1, 2, 3, 4, 5 }
P ={ 30, 20, 100, 90, 160 }
W ={ 5, 10, 20, 30, 40 }
Pi/Wi ={ 6, 2, 5, 3, 4 }
Complexity
The complexity mainly depends on the implementation of Q
The simplest version of Dijkstra's algorithm stores the vertex set Q as an
ordinary linked list or array, and extract-minimum is simply a linear search
through all vertices in Q. In this case, the running time is O(E + V2) = O(V2)
Graph represented using adjacency list can be reduced to O(E log V) with the
help of binary heap.
17.
a) Find an optimal paranthesization of a matrix-chain product whose sequence of
dimensions is 4x10,10x3,3x12,12x20,20x7 using dynamic programming
Ans:
The values of m and s tables are computed as follows:
m[1][1] = 0, m[2][2]=0, m[3][3]=0, m[4][4]=0, m[5][5]=0
m[1][2] = 4*10*3 =120, m[2][3] = 360, m[3][4] =720, m[4][5]=1680
m[1][3] = min{m[1][1]+m[2][3]+4*10*12 , m[1][2]+m[3][3]+4*3*12}=264
m[2][4] = 1320, m[3][5] = 1140
m[1][4] = 1080, m[2][5] = 1350, m[1][5] = 1344
Cost reduced = r = 5
M2 is the matrix for node 2
Cost of node 2 = Cost of node 1 + M1[a, b] + r = 6 + 0 + 5 = 11
Cost reduced = r = 6
M4 is the matrix for node 4
Cost of node 4 = Cost of node 1 + M1[a, d] + r = 6 + 5 + 6 = 17
Now the live nodes are 2, 3 and 4. Minimum cost is for node 2 and 3.
Choose one node(say node 2) as the next E-node.
Cost reduced = r = 2
M5 is the matrix for node 5
Cost of node 5 = Cost of node 2 + M2[b, c] + r = 11 + 5 + 2 = 18
Now the live nodes are 5, 6, 3 and 4. Choose one node which having
minimum cost(say node 6) as the next E-node.
Cost reduced = r = 0
M7 is the matrix for node 7
Cost of node 7 = Cost of node 6 + M6[d, c] + r = 11 + 0 + 0 = 11
Now the live nodes are 5, 7, 3 and 4. Choose one node which having
minimum cost(say node 7) as the next E-node. Node 7 having no child node.
Now we can say that node 1 to node 7 path is the Traveling salesperson
path.
18.
a) Explain backtracking technique. How 4-queens problem can be solved using
backtracking?
Ans:
Backtracking Control Abstraction
(x1, x2.,…… xi) be a path from the root to a node in a state space tree.
Generating Function T(x1, x2.,…… xi) be the set of all possible values for
xi+1 such that (x1, x2.,…… xi+1) is also a path to a problem state.
T(x1, x2.,…… xn) = φ
Bounding function Bi+1(x1, x2.,…… xi+1) is false for a path (x1, x2.,……
xi+1) from the root node to a problem state, then the path cannot be extended
to reach an answer node.
Thus the candidates for position i+1of the solution vector (x1, x2.,…… xn)
are those values which are generated by T and satisfy Bi+1.
The recursive version is initially invoked by Backtrack(1).
Algorithm Backtrack(k)
{ for (each x[k] ϵ T(x[1], . . . .x[k-1])
{
if(Bk(x[1], x[2], . . . . . ., x[k]) != 0) then
{
if(x[1], x[2], . . . . . ., x[k] is a path to an answer node)
then write(x[1:k])
if(k<n) then Backtrack(k+1)
}
}
}
N-Queens Problem
Algorithm NQueens(k,n)
{
for i=1 to n do
{ if Place(k,i) then
{ x[k] = i
if(k==n) then write(x[1:n])
else NQueens(k+1, n)
}
}
}
Algorithm Place(k,i)
{
for j=1 to k-1 do
{
if( (x[j]==i) or ( Abs(j-k)==Abs(x[j]-i) ) then
Return false
}
Return true
}
o Place(k,i) returns true if the kth queen can be placed in column i.
i should be distinct from all previous values x[1],x[2], . . . . . . .,
x[k-1]
And no 2 queens are to be on the same diagonal
Time complexity of Place() is O(k)
o NQueen() is initially invoked by NQueen(1,n)
Time complexity of NQueen() is O(n!)
b) Explain Floyd-Warshall Algorithm. Using the algorithm find all pair of shortest paths
in the following graph.
Ans:
D(5) represents the shortest distance between each pair of the given graph
19.
a) Discuss the advantages of randomized algorithms over deterministic algorithms.
Discuss Las Vegas and Monte Carlo algorithms with a suitable example
Ans:
Deterministic Algorithm: The output as well as the running time are functions
of the input only.
Randomized Algorithm: The output or the running time are functions of the
input and random bits chosen
Algorithm findingA_LV(A, n)
{
repeat
{
Randomly choose one element out of n elements
}until(‘a’ is found)
}
The expected number of trials before success is 2.
Therefore the time complexity = O(1)
Monte Carlo algorithm
Algorithm findingA_MC(A, n, k )
{
i=0;
repeat
{
Randomly select one element out of n elements
i=i+1;
}until(i=k or ‘a’ is found);
}
o This algorithm does not guarantee success, but the run time is
bounded. The number of iterations is always less than or equal to
k.
o Therefore the time complexity = O(k)
b) Give a randomized version of quicksort algorithm and perform its expected running
time analysis
Ans:
Algorithm randQuickSort(A[], low, high)
o The probability that the randomly chosen element is central pivot is 1/n.
o Therefore, expected number of times the while loop runs is n.
o Thus, the expected time complexity of step 2 is O(n).
20.
a) Define bin packing problem. Discuss the first fit strategy for solving it. State the
approximation ratio of the algorithm
Ans:
Bin packing problem: Given n items of different weights and bins each of capacity
c, assign each item to a bin such that number of total used bins is minimized. It may
be assumed that all items have weights smaller than bin capacity
The vertex Cover of a graph is defined as a subset of its vertices, such for every
edge in the graph, from vertex u to v, at least one of them must be a part of the
vertex cover set.
Vertex cover problem is to find the minimum sized vertex cover of the given
graph.
Example: