You are on page 1of 24

-1-

K. RAMAKRISHNAN COLLEGE OF TECHNOLOGY


(AUTONOMOUS)

Question Paper Code: X24331


B.E./B.Tech. DEGREE EXAMINATION, NOV/DEC -2021
Third Semester
Department of Artificial Intelligence and Data Science
20AI3101 – Data Structures and Algorithms
(Regulation 2020)

Part-A (10 x 2 = 20 Marks)

1. Write down the rules for converting an infix to postfix expression?

2. What are the applications of linked list in dynamic storage management?


 A linked list is a dynamic arrangement so it can grow and shrink at runtime by allocating and deallocating
memory. So there is no need to give the initial size of the linked list as in array.
 Linked list can be used to maintain free blocks in dynamic memory allocation.
 In the Linked list, efficient memory utilization can be achieved since the size of the linked list increase or
decrease at run time so there is no memory wastage and there is no need to pre-allocate the memory.
 Adjacency list representation of graphs is most popular which uses linked list to store adjacent vertices.

3. A priority queue P is used to implement a stack that stores characters. PUSH (X) is implemented
INSERT(P,X, N) where N is an appropriate integer key chosen by the implementation. POP is implemented
as DELETEMIN(P). For a sequence of operations, Specify the order of the keys chosen.
 A Stack is implemented using Priority Queue. Note that Stack implementation is always last in first out
(LIFO) order. As given “POP is implemented as DELETEMIN(P)” that means Stack returns minimum
element always.
 PUSH(X) operation needs to be implemented using INSERT(P, X, N) where K is key chosen from strictly-
decreasing order(only this order will ensure stack will return minimum element when we POP an element).
That will satify Last In First Out (LIFO) property of stack.

4. If a binary tree T has n leaf nodes, what is the number of nodes of degree 2 in T?
 In Binary Tree a node can have at most 2 children. For the tree, the degree of a node is defined as the number
of sub-trees of the node or no of children of a node.
 Total number of node N = node with 0 child +node with 1 child + node with 2 child.
N = n0+n1+n2
It is given that no. of leaf nodes i.e) no. of nodes with 0 children is n, so n0=n
N=n+n1+n2
 Total number of edges e=N−1, and also e=n*0+n1*1+n2*2
N−1 = n*0+n1*1+n2*2
n+n1+n2−1 = n1*1+n2*2
QP CODE X24331
-2-
n2 = n−1
5. Define path in the graph.
 A path in a graph is a sequence of edges which joins a sequence of vertices which are all distinct
 A path is a trail in which all vertices (and therefore also all edges) are distinct

 The path between the vertices 1 and 4 is 1->2->4 (or) 1->3->4

6. What is the minimum condition to construct Euler circuit?


 Euler Path is a path that visits every edge of a graph exactly once. Euler Circuit is an Euler Path that always
starts and ends on the same vertex. 
 If a graph G has an Euler circuit, then all of its vertices must be even vertices. If the number of odd vertices
in G is anything other than 0, then G cannot have an Euler circuit.

7. Is it necessary to test the complexity of the algorithm? Justify your answer.


 Yes it is necessary to test the complexity of the algorithm
 The analysis of algorithms is the process of finding the computational complexity of algorithms – the amount
of time, storage, or other resources needed to execute them.
 Usually, this involves determining a function that relates the length of an algorithm's input to the number of
steps it takes (its time complexity) or the number of storage locations it uses (its space complexity).
 An algorithm is said to be efficient when this function's values are small, or grow slowly compared to a
growth in the size of the input.

8. List any two differences between big-oh, big-omega and big-theta.


S.No. Big Oh Big Omega Big Theta

It is like <=  It is like >=  It is like == 


1. rate of growth of an algorithm is rate of growth is greater than or meaning the rate of growth is equal to a
less than or equal to a specific value equal to a specified value specified value
2. Big oh (O) – Worst case Big Omega (Ω) – Best case Big Theta (Θ) – Average case
Big-O is a measure of the longest Big- Ω is a measure of the Big- Θ is a measure of the very
3. amount of time taken for the smallest amount of time taken smallest amount of time taken for the
algorithm to complete. for the algorithm to complete. algorithm to complete.

9. What is the best-case analysis of quick sort?


 The Quick Sort algorithm performs the best when the pivot is the middle value in the array.
 Best Case of quick sort is when the pivot element divides the list into two equal halves by coming exactly in
the middle position.
 It’s time complexity is O(n log n).

10. What is the key idea in shell sort technique?


 Donald Shell published the first version of this sort in 1959.
 Shell sort is an algorithm that first sorts elements that are far away from each other, and then gradually
reduces the distance between them.
 In shell sort the whole array is first fragmented into K segments, where K is preferably a prime number.
 Shell sort, also known as Diminishing increment sort because the value of K decreases continuously.

QP CODE X24331
-3-
Part – B (5 x 13 = 65Marks)
11. a. Given two sorted linear linked lists A1 and A2, how do you create a list A3, which consists of the uncommon
elements of A1 and A2? Write a suitable ADT for the construction of doubly linked list A3. (13)
Intersection of two linked list: Explanation – 3M, Program – 10M
Since the array is sorted, duplicate numbers will occur together at consecutive positions, and we need to choose
only one of them. Therefore, to solve this problem pointer method can be used. Create one fast pointer which moves
by 1 element at each step one slow pointer which moves only when the fast pointer moves on to a new element. Now,
whenever the values of fast pointer and slow pointer differ we print the distinct value and move the slow pointer to the
location of fast pointer.
typedef struct node
{
int data;
node* next;
} node;
/* Initially HEAD is null because list is empty */
node* HEAD = NULL;
// Inserts a node with data at the end of current linked list
void insertAtTheEnd(int data) {
/* Step 1: Create a New Node dynamically by using new operator */
node* nodeToBeInserted = new node;
nodeToBeInserted->data = data;
nodeToBeInserted->next = NULL; /* Since, the node is getting inserted at the last, it's
next will be NULL */
/* If head is NULL, then this is the first node that is getting inserted */
if (HEAD == NULL) {
HEAD = nodeToBeInserted;
}
else {
/* At the end of this loop, curr will point to the last node */
node* curr = HEAD;
while (curr->next != NULL) {
curr = curr->next;
}
/* Attach the nodeToBeInserted to the end of last node (curr) */
curr->next = nodeToBeInserted;
}
}
void printOnlyDistinct() {
/* Create two pointers, slow and fast pointer */
node* sp = HEAD, *fp = HEAD;
while (fp != NULL) {
if (sp == fp) {
cout << sp->data << "\n";
}
fp = fp->next;
if (fp != NULL && fp->data != sp->data) {
sp = fp;
}
}
}
int main() {
/** Creating the linked list */
insertAtTheEnd(5);
insertAtTheEnd(10);
insertAtTheEnd(10);
insertAtTheEnd(15);
insertAtTheEnd(15);
/** Printing only the distinct elements of the list */
cout << "Printing only distinct elements \n";
printOnlyDistinct();
QP CODE X24331
-4-
return (0);
}
Or
11. b. Write an Algorithm to convert the infix expression to postfix expression and steps involved in evaluating the
postfix expression. Convert the expression P-(Q/R+(S%T*U)/V)*W to postfix form. Evaluate the given expression
9 3 4 * 8 + 4 / -. (13)
Definition – 2M, Algorithm - 6M, Example – 5M
Three are three different ways of representing the algebraic expressions: Infix, Prefix and Postfix notations
Infix: The arithmetic operator appears between the two operands to which it is being applied. A*(B+C)/D
Prefix: The arithmetic operator appears directly after the two operands to which it applies. /*A+BCD
Postfix: The arithmetic operator appears directly before the two operands to which it applies. ABC+*D /

Infix to Postfix Conversion


Given Infix expression is P-(Q/R+(S%T*U)/V)*W#
Read Character Stack Output

P P

- P

( P

QP CODE X24331
-5-

Q PQ

/ PQ

R PQR

+ PQR/

( PQR/

S PQR/S

% PQR/S

T PQR/ST

* PQR/ST%

QP CODE X24331
-6-

U PQR/ST%U

) PQR/ST%U*

/ PQR/ST%U*

V PQR/ST%U*V

) PQR/ST%U*V/+

* PQR/ST%U*V/+

W PQR/ST%U*V/+W

# PQR/ST%U*V/+W*-
The Postfix Expression is PQR/ST%U*V/+W*-

Evaluation of Postfix Expression 9 3 4 * 8 + 4 / -


Read Character Stack

QP CODE X24331
-7-

Result: 4

12. a. Explain tree traversal techniques with example. (13)


Definition – 2M, Routine – 6M, Example – 5M
Tree Traversal
 Process of visiting every node in the tree exactly once.
 There are no. of ways to traverse a tree.
 All traversal differ only in the order in which they visit the nodes.
 The three main methods of traversing a tree are
 Inorder traversal
 Preorder traversal
QP CODE X24331
-8-
 Postorder traversal
 Inorder Traversal (Symmetric Order)
1. Traverse the left subtree in inorder
2. Visit the root
3. Traverse the right subtree in inorder

 Preorder Traversal (Depth-First Order)


1. Visit the root
2. Traverse the left subtree in preorder.
3. Traverse the right subtree in preorder.

 Postorder Traversal
1. Traverse the left subtree in postorder
2. Traverse the right subtree in preorder
3. Visit the root

 Example

QP CODE X24331
-9-

Inorder Traversal: D B E A F C G
Preorder Traversal: A B D E C F G
Postorder Traversal: D E B F G C A
Or
12. b. Write an Algorithm for AVL tree insertion. Insert the following elements in the empty tree and how do you
balance the tree after each element insertion? Elements: 2, 5, 4, 6, 7, 9, 8, 3, 1, 0
Definition – 2M, Rotation– 3M, Insertion Routine – 4M, Example – 4M
AVL Tree
AVL tree is a self balanced binary search tree. That means, an AVL tree is also a binary search tree but it is a
balanced tree. A binary tree is said to be balanced, if the difference between the height of left and right subtrees
can differ by at most one. Balance factor of a node is the difference between the heights of left and right
subtrees of that node. In an AVL tree, balance factor of every node is either -1, 0 or +1.

Balance factor = heightOfLeftSubtree - heightOfRightSubtree

AVL Tree Rotations


Rotation is the process of moving the nodes to either left or right to make tree balanced. There are four rotations and
they are classified into two types.

Single Left Rotation (LL Rotation)


 In LL Rotation every node moves one position to left from the current position.

Single Right Rotation (RR Rotation)


 In RR Rotation every node moves one position to right from the current position

QP CODE X24331
-
10-

Left Right Rotation (LR Rotation)


 The LR Rotation is combination of single left rotation followed by single right rotation. In LR Rotation, first
every node moves one position to left then one position to right from the current position.

Right Left Rotation (RL Rotation)


 The RL Rotation is combination of single right rotation followed by single left rotation. In RL Rotation,
first every node moves one position to right then one position to left from the current position.

Operations on an AVL Tree


The following operations are performed on an AVL tree...
1. Search
2. Insertion
3. Deletion
Insertion Operation in AVL Tree
 In an AVL tree, the insertion operation is performed with O(log n) time complexity. In AVL Tree, new
node is always inserted as a leaf node. The insertion operation is performed as follows...
 Step 1: Insert the new element into the tree using Binary Search Tree insertion logic.
 Step 2: After insertion, check the Balance Factor of every node.
 Step 3: If the Balance Factor of every node is 0 or 1 or -1 then go for next operation.
 Step 4: If the Balance Factor of any node is other than 0 or 1 or -1 then tree is said to be imbalanced.
Then perform the suitable Rotation to make it balanced.

QP CODE X24331
-
11-

13.a. Write an Algorithm to find subset of edges that includes every vertex of the graph such that the sum of the
weights of the edges can be minimized for any undirected graph. (13)
Definition – 2M, Algorithm – 6M, Example – 5M
Marks can be given for either Kruskals or Prims Algorithm

Kruskals Algorithm

QP CODE X24331
-
12-

QP CODE X24331
-
13-

QP CODE X24331
-
14-

Or
13.b. Write an Algorithm to find the shortest path from a node to every other node for the given directed graph (13)
Definition – 2M, Algorithm – 6M, Example – 5M
Dijkstra’s Algorithm
 The one-to-all shortest path problem is the problem of determining the shortest path from node s to all the
other nodes in the network. The weights on the links are also referred as costs.
 Dijkstra’s algorithm is applied to automatically find directions between physical locations, such as driving
directions on websites like Mapquest or Google Maps.
 Dijkstra’s algorithm starts by assigning some initial values for the distances from node s and to every other
node in the network
 It operates in steps, where at each step the algorithm improves the distance values.
 At each step, the shortest distance from node s to another node is determined.
void Dijkstra(Graph G, Table T)
{

QP CODE X24331
-
Example15-
V known dv Pv
a 1 0 0
b 0 2 a
c 0 2 d
d 1 1 a

V known dv Pv
a 1 0 0
b 1 2 a
c 0 2 d
d 1 1 a

V known dv Pv
a 1 0 0
b 1 2 a
c 1 2 d
d 1 1 a

14.a. Analyze the time efficiency of sequential search. Describe in detail.


(13)
QP CODE X24331
-
Definition – 2M, Program – 4M, Analysis – 7M 16-
Linear Search Algorithm is an algorithm which checks all elements in a given list sequentially and compares with
element with a given element which is the element being searched. This algorithm is used to check if an
element is present in a list.
Program
void linear(int a[],int n,int x)
{
int i,flag=0;
for(i=0;i<n;i++)
{
if(a[i]==x)
{
printf(“Element %d is found in location:%d”,x,i+1);
flag=1;
}
}
if(flag==0)
printf(“Element not found”);
}
Analysis of Best Case Time Complexity
The Best Case will take place if:
 The element to be search is on the first index.
The number of comparisons in this case is 1. Therefore, Best Case Time Complexity of Linear Search is O(1).
Analysis of Average Case Time Complexity
Let there be N distinct numbers: a1, a2, ..., a(N-1), aN
We need to find element P.
There are two cases:
 Case 1: The element P can be in N distinct indexes from 0 to N-1.
 Case 2: There will be a case when the element P is not present in the list.
There are N case 1 and 1 case 2. So, there are N+ 1 distinct cases to consider in total.
If element P is in index K, then Linear Search will do K+1 comparisons.
Number of comparisons for all cases in case 1 = Comparisons if element is in index 0 + Comparisons if element is in
index 1 + ... + Comparisons if element is in index N-1
= 1 + 2 + ... + N
= N * (N+1) / 2 comparisons
If element P is not in the list, then Linear Search will do N comparisons.
Number of comparisons for all cases in case 2 = N
Therefore, total number of comparisons for all N+1 cases = N * (N+1) / 2 + N
= N * ((N+1)/2 + 1)
Average number of comparisons = ( N * ((N+1)/2 + 1) ) / (N+1)
= N/2 + N/(N+1)
The dominant term in "Average number of comparisons" is N/2.
So, the Average Case Time Complexity of Linear Search is O(N).
Analysis of Worst Case Time Complexity
The worst case will take place if:
 The element to be search is in the last index
 The element to be search is not present in the list
QP CODE X24331
-
In both cases, the maximum number of comparisons takes place
17-in Linear Search which is equal to N comparisons.
Hence, the Worst Case Time Complexity of Linear Search is O(N).
Number of Comparisons in Worst Case: N
Or
14.b. Summarize the key points in measuring the performance of algorithms.
(13)
Definition – 2M, Explanation for each – 8M, Table – 3M

QP CODE X24331
-
18-

QP CODE X24331
-
19-

15.a. Write an Algorithm to sort the following elements 32,76, 12, 23, 67, 45 using selection sort technique. (13)
Definition – 2M, Routine – 5M, Example-4M, Analysis – 2M
Selection sort selects the smallest element in the list and place it in the first position then selects the
second smallest element and place it in the second position and it proceeds in the similar way until the entire
list is sorted. For “n” elements, (n-1) passes are required. At the end of the i th iteration, the ith smallest
element will be placed in its correct position.
Routine:
void Selection_sort( int a[ ], int n )
{
int i , j , temp, position ;
for ( i = 0 ; i < n – 1 ; i ++ )
{
position = i ;
for ( j = i + 1 ; j < n ; j ++ )
{
if ( a[ position ] > a[ j ] )
position = j;
}
temp=a[ i ];
a[i]=a[position];
a[ position ] = temp;
}
}
Example
32 76 12 23 67 45
Step 1
First smallest element is 12. Place 12 in 1st position. Swap 32 with 12.
12 76 32 23 67 45
Step 2
Next smallest element is 23. Place 23 in 2nd position. Swap 76 with 23.
12 23 32 76 67 45
Step 3
Next smallest element is 32. It is in correct position. No swapping occurs.
QP CODE X24331
-
12 23 32 20-76 67 45
Step 4
Next smallest element is 45. Place 45 in 4th position. Swap 76 with 45.
12 23 32 45 67 76
Step 4
Next smallest element is 67. It is in correct position. No swapping occurs.
12 23 32 45 67 76
Step 4
Next smallest element is 76. It is in correct position. No swapping occurs.
12 23 32 45 67 76
Advantages of selection sort
• Memory required is small.
• Selection sort is useful when you have limited memory available.
• Relatively efficient for small arrays.
Analysis of selection sort
 Worst case: O(N)
 Average Case: O(N)
 Best Case: O(1)
15.b. Write down the importance of optimal binary search tree. Explain the procedure to construct optimal binary
search tree. (13)
Definition – 2M, Equation and Table – 3M, Procedure – 8M

QP CODE X24331
-
21-

QP CODE X24331
-
22-

PART –C (15X1=15)
16.a. Write an Algorithm to getMin(), decreaseKey(), and extractMin() binary heap operations.
(15)
Definition – 2M, Property – 4M, Algorithm – 5M, Example – 4M
Binary Heap
 A binary heap is a complete binary tree in which every node satisfies the heap property which states that:
If B is a child of A, then key(A) ≥ key(B)
 Elements at every node will be either greater than or equal to the element at its left and right child. Thus, the
root node has the highest key value in the heap. Such a heap is commonly known as a max-heap.
 Elements at every node will be either less than or equal to the element at its left and right child. Thus, the root
Has the lowest key value. Such a heap is called a min-heap.
Properties of Heap
1. Structure Property.
2. Heap Order Property.
1. Structure Property
 The Heap should be a complete binary tree, which is a completely filled tree, which is a completely filled
binary tree with the possible exception of the bottom level, which is filled from left to right.
 A Complete Binary tree of height H, has between 2h and (2h+1 - 1) nodes.
2. Heap Order Property
 The property that allows operations to be performed quickly is a heap order property.
Min-heap:
o The smallest element is always in the root node. Each node must have a key that is less than or equal
to the key of each of its children.
Max-Heap:
o The largest Element is always in the root node. Each node must have a key that is greater or equal to
the key of each of its children.

Operations on Min Heap:


1) getMin(): It returns the root element of Min Heap. Time Complexity of this operation is O(1).
QP CODE X24331
-
2) extractMin(): Removes the minimum element from MinHeap. Time 23- Complexity of this Operation is O(Logn) as this
operation needs to maintain the heap property (by calling heapify()) after removing root.
3) decreaseKey(): Decreases value of key. The time complexity of this operation is O(Logn). The Decrease
key(P,Δ,H) operation decreases the value of the key at position P, by a positive amount Δ. This may violate
the heap order property, which can be fixed by percolate up Ex : decreasekey(2,7,H)
Or
16.b. How do you solve knapsack problem using dynamic programming with an example.
(15)
Definition – 4M, Procedure – 6M, Example – 5M
Knapsack problem
 The knapsack problem or rucksack (bag) problem is a problem in combinatorial optimization: Given a set of
items, each with a mass and a value, determine the number of each item to include in a collection so that the total
weight is less than or equal to a given limit and the total value is as large as possible
 There are two versions of the problems
1. 0/1 knapsack problem
2. Fractional Knapsack problem
a. Bounded Knapsack problem.
b. Unbounded Knapsack problem.
Solutions to knapsack problem
Brute-force approach:-Solve the problem with a straight forward algorithm
Greedy Algorithm:- Keep taking most valuable items until maximum weight is reached or taking the largest value
of each item by calculating vi=valuei/Sizei
Dynamic Programming:- Solve each sub problem once and store their solutions in an array.
Dynamic Programming
 Given n items of known weights w1, . . . , wn and values v1, . . . , vn and a knapsack of capacity W , find the
most valuable subset of the items that fit into the knapsack.
 All the weights and the knapsack capacity are positive integers; the item values do not have to be integers.

 Derive a recurrence relation that expresses a solution to an instance of the knapsack problem in terms of
solutions to its smaller sub instances.

 Let us consider an instance defined by the first i items, 1 ≤ i ≤ n, with weights w1, . . . , wi, values v1, . . . , vi,
and knapsack capacity j, 1 ≤ j ≤ W. 

 Let F (i, j ) be the value of an optimal solution to this instance, i.e., the value of the most valuable subset of the
first i items that fit into the knapsack of capacity j. 

 Divide all the subsets of the first i items that fit the knapsack of capacity j into two categories: those that do not
include the ith item and those that do.

 Among the subsets that do not include the ith item, the value of an optimal subset is, by definition, F (i − 1, j ).

 Among the subsets that do include the ith item (hence, j − wi ≥ 0), an optimal subset is made up of this item
and an optimal subset of the first i − 1 items that fits into the knapsack of capacity j − wi. The value of such an
optimal subset is vi + F (i − 1, j − wi).

 Recurrence relation:

QP CODE X24331
-
Our goal is to find F (n,W), the maximal value of a subset
24-of the n given items that fit into the knapsack of
capacity W, and an optimal subset itself.

Thus, the maximal value is F (4, 5) = $37. 


Since F (4, 5) > F (3, 5), item 4 has to be included in an optimal solution along with an optimal subset for filling
5 − 2 = 3 remaining units of the knapsack capacity.
The value of the latter is F (3, 3). Since F (3, 3) = F (2, 3), item 3 need not be in an optimal subset.
Since F (2, 3) > F (1, 3), item 2 is a part of an optimal selection, which leaves element F (1, 3 − 1) to specify its
remaining composition.
Similarly, since F (1, 2) > F (0, 2), item 1 is the final part of the optimal solution {item 1, item 2, item 4}.

QP CODE X24331

You might also like