Answer Key DSA
Answer Key DSA
Answer Key DSA
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
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 /
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*-
QP CODE X24331
-7-
Result: 4
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.
QP CODE X24331
-
10-
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
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.
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.
QP CODE X24331